类File的问题,求助
源码:File file=new File ("d:/work/newtemp.txt");
System.out.println(file.getName());
编译通过,也能输出文件名。。
但是为嘛d盘上没有这个txt文件。。目录也没有。。
用File.separator也试过。还是木有。。。
高手求助。
[解决办法]
执行时新建了一个啊, 程序执行完 你没刷新缓冲区,所以没写到磁盘
[解决办法]
你看下jdk的源码就知道了.
比如File.getParent()这个只是根据当前的路径,截断File.separator这个,将前面的String返回的.
不会去判断此文件是否存在.这个getName()就是将path返回而已.
public String getName() {
int index = path.lastIndexOf(separatorChar);
if (index < prefixLength) return path.substring(prefixLength);
return path.substring(index + 1);
}
[解决办法]
package com.ex;import java.io.File;import java.io.IOException;public class Test { /** * @param args */ public static void main(String[] args) { File file=new File ("d:/work/newtemp.txt"); String str = file.getAbsolutePath() ; String sDir = str.replaceAll(file.getName(), "") ; //得到所在目录 File dir = new File(sDir) ; if (! dir.exists() ){ //判断目录是否存在,如果不存在就创建 ; dir.mkdirs() ; //mkdirs()可以创建多级目录 } if (! file.exists()){ //判断文件是否存在 try { file.createNewFile() ; //创建文件 } catch (IOException e) { e.printStackTrace(); } } System.out.println(file.getName()); }}