日期:2014-05-20  浏览次数:20626 次

java io 文件路径问题
首先我写出代码:

public class test {
public static void main(String[]args) throws Exception{
File file = new File("d.txt");//错误的
//File file = new File("H:\\eclipse\\workspace\\Socket\\d.txt");//正确的
System.out.println(file.getAbsolutePath());
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}else{
System.out.println("oh,yse !");
}
}
}

这个代码,存在于H:\\eclipse\\workspace\\Socket文件夹中,
为什么File file = new File("d.txt");就报错,
File file = new File("H:\\eclipse\\workspace\\Socket\\d.txt");就正确?
不是说,直接写文件名就默认所在工程的路径么?
那么,为什么File file = new File("d.txt");却父类文件getParentFile()为null?
而写全路径H:\\eclipse\\workspace\\Socket\\d.txt就有了?
-------------
注:我用的是Eclipse

------解决方案--------------------
File file = new File("d.txt");//错误的

的路径是:d.txt,(虽然绝对路径是:H:\\eclipse\\workspace\\Socket\\d.txt)在寻找父路径的时候就是以d.txt路径去寻找的,d.txt的父路径为null。你可以使用getPath()试一下

File file = new File("H:\\eclipse\\workspace\\Socket\\d.txt");//正确的

的路径是:H:\\eclipse\\workspace\\Socket\\d.txt,也就以这个路径去寻找父路径。


------解决方案--------------------
楼主 你编写java类每次运行都是被虚拟机编译成class文件之后运行的,所以直接指定d.txt 肯定找不到。
相对路径中去找文件:
String name = this.getClass().getResource("d.txt").getPath();
------解决方案--------------------
看一下File类的源码就很明了了

    public String getPath() {
        return path;
    }

    public File getParentFile() {
        String p = this.getParent();
        if (p == null) return null;
        return new File(p, this.prefixLength);
    }

    public String getParent() {
        int index = path.lastIndexOf(separatorChar);
        if (index < prefixLength) {
            if ((prefixLength > 0) && (path.length() > prefixLength))
                return path.substring(0, prefixLength);
            return null;
        }
        return path.substring(0, index);
    }

path是d.txt,当然getParentFile会得到null
------解决方案--------------------
File file = new File("d.txt"); 寻找的是工程所在路径,请参考http://www.itzlk.com/io/index.jhtml
------解决方案--------------------
3楼正解

    public String getPath() {
        return path;
    }

    public File getParentFile() {
        String p = this.getParent();
        if (p == null) return null;
        return new File(p, this.prefixLength);
    }

    public String getParent() {
        int index = path.lastIndexOf(separatorChar);        if (index < prefixLength) {
            if ((prefixLength > 0) && (path.length() > prefixLength))
                return path.substring(0, prefixLength);
            return null;
        }
        return path.substring(0, index);
    }
------解决方案--------------------
引用:
File file = new File("d.txt"); 寻找的是工程所在路径,请参考http://www.itzlk.com/io/index.jhtml