由于某种原因,当我在程序中创建新的 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)