我正在处理文件并尝试使用多个文件,我得到例外:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at com.create.CreatingFiles.create(CreatingFiles.java:25)
at com.create.CreatingFiles.main(CreatingFiles.java:36)
,代码是:
File file = new File("F://fileIO");
StringBuffer buffer = null;
File newFile;
try {
if (!file.exists()) {
file.mkdir();
buffer = new StringBuffer(file.getAbsolutePath().toString());
} else {
System.out.println("DIRECTORY EXISTS");
buffer = new StringBuffer(file.getAbsolutePath().toString());
}
for (int i = 0; i < 10; i++) {
newFile = new File(buffer.append("/new File").append(i)
.append(".txt").toString()); //ERROR
if (!newFile.exists()) {
newFile.createNewFile();
System.out.println(newFile.getAbsolutePath());
} else {
System.out.println("FILE EXISTS");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在纠正我,如果我错了,我想,我需要关闭文件资源,以便我可以将其重新分配给新文件但不能关闭它。
OR
还有其他因素导致错误?
答案 0 :(得分:3)
File file = new File("C://TNS_ADMIN");
StringBuffer buffer = null;
File newFile;
try {
if (!file.exists()) {
file.mkdir();
buffer = new StringBuffer(file.getAbsolutePath().toString());
} else {
System.out.println("DIRECTORY EXISTS");
buffer = new StringBuffer(file.getAbsolutePath().toString());
}
for (int i = 0; i < 10; i++) {
newFile = new File(new StringBuffer(buffer).append("/new File").append(i)
.append(".txt").toString()); //ERROR
if (!newFile.exists()) {
newFile.createNewFile();
System.out.println(newFile.getAbsolutePath());
} else {
System.out.println("FILE EXISTS");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
当你调用StringBuffer的append方法时,它会自行写入。这就是问题所在。
答案 1 :(得分:0)
newFile = new File(buffer.append("/new File").append(i)
.append(".txt").toString());
这一行附加了前一个路径,如/newFile0.txt/newFile1.txt
,这就是为什么它会给你错误。不附加只是连接
解决方案1:
newFile = new File(buffer+"/newFile"+i+".txt");
解决方案2
newFile = new File(new StringBuilder(buffer).append("/new File").append(i)
.append(".txt").toString());
Java: String concat vs StringBuilder - optimised, so what should I do?