我想问下,使用new file()构造函数时如果文件存在,会不会覆盖掉之前的文件?
如果不存在会不会自己创建一个新的?我就不需要creatNewfile方法了?请教解答!
public File getFile(String path, String fileName) {
File file = new File(path + File.separator + fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
} catch (IOException e) {
System.out.println("读取文件异常!");
e.printStackTrace();
}
return file;
}
会覆盖源代码的文件,如果不希望覆盖,而是追加数据,参考:http://blog.csdn.net/malik76/article/details/6408726/
文件存在,会覆盖原来的文件
createNewFile()会创建新的,
File file = new File(path + File.separator + fileName); 这一行,若文件存在,会获取到这个文件的“引用”
如果文件存在则覆盖原来的,不存在则创建一个,所以不需要手动