java io 路径,java io 文件路径有关问题

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 

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 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值