出于某种原因,当我在我的程序中创建一个新的 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();
}