出于某种原因,当我在我的程序中创建一个新的 BufferedWriter 和 FileWriter 时(即使我还没有用它写任何东西),它会清除我选择的文件的所有文本。
selectedFile 由 JFileChooser 决定。
public static File selectedFile;
public static void Encrypt() throws Exception {
try {
//if I comment these two writers out the file is not cleared.
FileWriter fw = new FileWriter(selectedFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
List<String> lines = Files.readAllLines(Paths.get(selectedFile.toString()),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
System.out.println(AESencrp.encrypt(line));
/*file is cleared regardless of whether or not these are commented out or
* not, as long as I create the new FileWriter and BufferedWriter the file
* is cleared regardless.*/
//bw.write(AESencrp.encrypt(line));
//bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
AEsencrp.encrypt 只是我的一个加密类,它不会影响它。如果我创建一个新的 FileWriter 和 BufferedWriter 那么这个循环甚至不会运行(至少我不相信,因为我没有得到行的加密或打印文件的原始内容,如果我没有打印' t 创建了新的 FileWriter/BufferedWriter。)
for (String line : lines) {
System.out.println(line);
System.out.println(AESencrp.encrypt(line));
/*file is cleared regardless of whether or not these are commented out or
* not, as long as I create the new FileWriter and BufferedWriter the file
* is cleared regardless.*/
//bw.write(AESencrp.encrypt(line));
//bw.close();
}
最佳答案
这是因为您正在使用的 FileWriter
的构造函数会在文件已存在时将其截断。
如果您想附加数据,请使用:
new FileWriter(theFile, true);
关于java - 出于某种原因使用 FileWriter 和 BufferedWriter 清除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244713/