先交代一下背景。
src为这个项目源码的目录,user为用户目录,src和user都在同一个项目文件夹PROJECT
下,也就是说二者有相同父路径PROJECT。如何检测user目录下有opml这个文件?以下是代码片段File opml=new File("user\\opml");
if(opml.exists()==true){
System.out.print("ok");
}
else System.out.print("fuck");
src为这个项目源码的目录,user为用户目录,src和user都在同一个项目文件夹PROJECT
下,也就是说二者有相同父路径PROJECT。如何检测user目录下有opml这个文件?以下是代码片段File opml=new File("user\\opml");
if(opml.exists()==true){
System.out.print("ok");
}
else System.out.print("fuck");
难道是我的user.dir问题?
java project环境,使用java.io用相对路径读取文件的例子:
*目录结构:
DecisionTree
|___src
|___com.decisiontree.SamplesReader.java
|___resource
|___train.txt,test.txt
*SamplesReader.java:
String filepath="resource/train.txt";//注意filepath的内容;
File file=new File(filepath);
…… *我们留意filepath的内容,java.io默认定位到当前用户目录("user.dir")下,即:工程根目录"D:\DecisionTree"下,因此,此时的相对路径(以user.dir为基路径的路径)为"resource/train.txt"。这样,JVM就可以根据"user.dir"与"resource/train.txt"得到完整的路径(即绝对路径)"D:\DecisionTree\resource\train.txt",从来找到train.txt文件。 *注意:相对路径的起始处无斜杆"/";例如:
filepath="resource/train.txt";
而不是filepath="/resource/train.txt"; //error!
大家知道如何实现我的想法么?
例如 File opml=new File("user\\opml.txt");
System.out.print("ok");
}
else System.out.print("fuck");
public boolean exists()测试此抽象路径名表示的文件或目录是否存在。 返回:
当且仅当此抽象路径名表示的文件或目录存在时,返回 true;否则返回 false
与扩展名无关~
我试了一下 如果这个类用java bean调试 就能够找到这个文件;如果是在别的类里面创建这个类的对象就找不到。
而且如果是第一种情况,uer.dir就是C:\Documents and Settings\Administrator
如果第二种情况就是F:\rcp workspace\RssReader(这个才是我项目的真正路径)
而是共享上层目录。故相对路径应该是 "..\\user\\opml.类型".
File opml=new File(System.getProperty("user.dir") + "\\user\\opml");
if(opml.exists()==true){
System.out.print("ok");
}
else System.out.print("fuck");
如果在别的类调用时,把目标文件放在编译过的class文件目录下试试看
F:\rcp workspace\reader\user\opml