源码:File file=new File ("d:/work/newtemp.txt");
System.out.println(file.getName());
编译通过,也能输出文件名。。
但是为嘛d盘上没有这个txt文件。。目录也没有。。
用File.separator也试过。还是木有
高手求助。
System.out.println(file.getName());
编译通过,也能输出文件名。。
但是为嘛d盘上没有这个txt文件。。目录也没有。。
用File.separator也试过。还是木有
高手求助。
解决方案 »
- 我想在字符串str中寻找字符a的位置
- 请问有没有中文的类似Professional Java JDK 6的JDK学习资料啊
- 求一个Select语句:如何实现MySQl的递归查询
- java+MySQL如何实现图像文件(*.jpg,*.gif)的存储和提取显示?
- 为什么创建不了数据源呢?(要用在连接sql server数据时),在线急盼!
- 关于actionlistener的简单问题
- 散分
- 关于滚动条显示的问题
- 如何用给定的一个类的名字(字符串)来实例化这个类,用newInstance()可以实例化这个类,但是构造函数不能带有参数的,如何实例化一个构
- jscript:想在dropDown(select控件)中动态增加一个option?帮帮忙吧!很急啊
- 用Java编写好的软件中如何编写保存按钮
- 我设计的一个计算器,截取字符串的时候出现错误,求帮助
比如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);
}
它不一定是代表一个硬盘上已经存在的文件
它也可能代表一个还不存在但你准备创建的文件
当然,它也可能是一个目录
理解了这些就能明白
new File(filename)
只是内存中的一个文件对象,它可能已经存在,也可能还未创建
如果你下一步往里面写入东西,这个文件就在硬盘上创建了。
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
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()); }}