由於某種原因,當我在我的程序中創建一個新的BufferedWriter和FileWriter(即使我還沒有用它來寫任何東西),它會清除我選擇的所有文本文件。出於某種原因使用FileWriter和BufferedWriter清理文件?
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,那麼這個循環甚至不會運行(至少我不這麼認爲,因爲我沒有得到線的加密或打印文件的原始內容,如果我沒有'牛逼創建新的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();
}