每次写入文本文件时,我都会丢失原始数据,如何读取文件并在空行或下一行中输入空数据?
public void writeToFile()
{
try
{
output = new Formatter(myFile);
}
catch(SecurityException securityException)
{
System.err.println("Error creating file");
System.exit(1);
}
catch(FileNotFoundException fileNotFoundException)
{
System.err.println("Error creating file");
System.exit(1);
}
Scanner scanner = new Scanner (System.in);
String number = "";
String name = "";
System.out.println("Please enter number:");
number = scanner.next();
System.out.println("Please enter name:");
name = scanner.next();
output.format("%s,%s \r\n", number, name);
output.close();
}
答案 0 :(得分:3)
答案 1 :(得分:1)
您需要在追加模式下打开myFile
。有关示例,请参阅this link。
答案 2 :(得分:1)
正如其他人所说,使用append选项。
此代码可以使用默认平台编码来写入数据:
private static void appendToFile() throws IOException {
boolean append = true;
OutputStream out = new FileOutputStream("TextAppend.txt", append);
Closeable resource = out;
try {
PrintWriter pw = new PrintWriter(out);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
有许多类可以围绕OutputStream来实现相同的效果。请注意,当代码在不使用Unicode默认编码(如Windows)的平台上运行时,上述方法可以lose data,并且可能会在不同的PC上生成不同的输出。
需要谨慎的一种情况是编码是否插入byte order mark。如果您想在标有小端BOM的UTF-16
中编写无损Unicode文本,则需要检查文件中的现有数据。
private static void appendUtf16ToFile() throws IOException {
File file = new File("TextAppend_utf16le.txt");
String encoding = (file.isFile() && file.length() > 0) ?
"UnicodeLittleUnmarked" : "UnicodeLittle";
boolean append = true;
OutputStream out = new FileOutputStream(file, append);
Closeable resource = out;
try {
Writer writer = new OutputStreamWriter(out, encoding);
resource = writer;
PrintWriter pw = new PrintWriter(writer);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
支持的编码:
答案 3 :(得分:0)
我们已经:new Formatter(myFile);
您要使用new Formatter(new FileWriter(myfile, true)
。 true表示您要附加到该文件。