java不知何故,这个方法删除了我的文件内容,但没有明显的原因
如果我没有错过任何东西,你应该能够运行这段代码,只需要一个跟踪。项目根文件夹中的日志文件
我不明白发生了什么。我只是声明了一些读写器,并尝试从文件中读取。我得到一个空值,文件似乎是空的。为什么
import java.io.*;
public class StubLogHandler {
private String name = "";
private String path = "";
public StubLogHandler (String filePath, String fileName) {
this.name = fileName;
this.path = filePath;
}
// THIS IS THE PESCKY BUGGER
public void testReadWrite() {
this.fixPath();
File file = new File (this.path+this.name);
try ( FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file);
BufferedReader reader = new BufferedReader(fileReader);
BufferedWriter writer = new BufferedWriter(fileWriter);) {
System.out.println("Works, I think.");
String line = "";
while (line != null) {
line = reader.readLine();
System.out.println(line);
// Should get a coupl'a lines, instead I get instant null
// Before you ask, no, the file is not initially empty
}
} catch (FileNotFoundException fnfe) {
System.out.println("File Not Found");
} catch (IOException ioe) {
System.out.println("Could not read or write to file");
}
}
private void fixPath () {
if (this.path.isEmpty())
return;
char lastChar = this.path.charAt(this.path.length()-1);
if (lastChar != '\\')
this.path += "\\"; // In case user forgets the final '\'
}
public String getAbsolutePath() {
this.fixPath();
return new File(this.path+this.name).getAbsolutePath();
}
}
public class Start {
public static void main (String[] args) {
Start.testStuff();
}
private static void testStuff() {
StubLogHandler log = new StubLogHandler("","trace.log");
System.out.println(log.getPath()+log.getName());
System.out.println(log.getAbsolutePath());
log.testReadWrite();
}
}
编辑
输出:
追踪。日志
D:\Personal\Java\workspace\Default\Practice\trace。日志
我觉得很管用
空的
# 1 楼答案
创造那个作家:
将立即截断该文件以准备写入。e、 g
将立即删除预先存在的文件
X