This question already has an answer here:
这个问题在这里已有答案:
- How to append text to an existing file in Java 30 answers
- 如何在Java 30答案中将文本附加到现有文件
I would like to append a new line to an existing file without erasing the current information of that file. In short, here is the methodology that I am using the current time:
我想在不删除该文件的当前信息的情况下向现有文件追加新行。简而言之,这是我使用当前时间的方法:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
Writer output;
output = new BufferedWriter(new FileWriter(my_file_name)); //clears file every time
output.append("New Line!");
output.close();
The problem with the above lines is simply they are erasing all the contents of my existing file then adding the new line text.
上述行的问题只是它们删除了我现有文件的所有内容,然后添加了新的行文本。
I want to append some text at the end of the contents of a file without erasing or replacing anything.
我想在文件内容的末尾添加一些文本而不删除或替换任何内容。
7 个解决方案
#1
108
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append)
constructor.
您必须以附加模式打开文件,这可以通过使用FileWriter(String fileName,boolean append)构造函数来实现。
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
应该做的伎俩
#2
22
The solution with FileWriter
is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!
使用FileWriter的解决方案正在运行,但是您无法指定输出编码,在这种情况下将使用机器的默认编码,这通常不是UTF-8!
So at best use FileOutputStream
:
所以充其量使用FileOutputStream:
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
#3
10
Try: "\r\n"
试试:“\ r \ n”
Java 7 example:
Java 7示例:
// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true)))
{
output.printf("%s\r\n", "NEWLINE");
}
catch (Exception e) {}
#4
9
Starting from Java 7:
从Java 7开始:
Define a path and the String containing the line separator at the beginning:
在开头定义路径和包含行分隔符的String:
Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";
and then you can use one of the following approaches:
然后您可以使用以下方法之一:
-
Using
Files.write
(small files):使用Files.write(小文件):
try { Files.write(p, s.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { System.err.println(e); }
-
Using
Files.newBufferedWriter
(text files):使用Files.newBufferedWriter(文本文件):
try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) { writer.write(s); } catch (IOException ioe) { System.err.format("IOException: %s%n", ioe); }
-
Using
Files.newOutputStream
(interoperable withjava.io
APIs):使用Files.newOutputStream(可与java.io API互操作):
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) { out.write(s.getBytes()); } catch (IOException e) { System.err.println(e); }
-
Using
Files.newByteChannel
(random access files):使用Files.newByteChannel(随机访问文件):
try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) { sbc.write(ByteBuffer.wrap(s.getBytes())); } catch (IOException e) { System.err.println(e); }
-
Using
FileChannel.open
(random access files):使用FileChannel.open(随机访问文件):
try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) { sbc.write(ByteBuffer.wrap(s.getBytes())); } catch (IOException e) { System.err.println(e); }
Details about these methods can be found in the Oracle's tutorial.
有关这些方法的详细信息,请参阅Oracle教程。
#5
4
In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.
如果你正在寻找一个创建和写入文件的剪切和粘贴方法,这里是我写的一个只需要一个字符串输入。如果要每次都覆盖文件,请从PrintWriter中删除“true”。
private static final String newLine = System.getProperty("line.separator");
private synchronized void writeToFile(String msg) {
String fileName = "c:\\TEMP\\runOutput.txt";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName, true));
printWriter.write(newLine + msg);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
#6
2
You can use the FileWriter(String fileName, boolean append)
constructor if you want to append data to file.
如果要将数据附加到文件,可以使用FileWriter(String fileName,boolean append)构造函数。
Change your code to this:
将您的代码更改为:
output = new BufferedWriter(new FileWriter(my_file_name, true));
From FileWriter javadoc:
来自FileWriter javadoc:
Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
给定文件名构造FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。
#7
2
On line 2 change new FileWriter(my_file_name)
to new FileWriter(my_file_name, true)
so you're appending to the file rather than overwriting.
在第2行,将新的FileWriter(my_file_name)更改为新的FileWriter(my_file_name,true),这样您就可以附加到文件而不是覆盖。
File f = new File("/path/of/the/file");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.append(line);
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
#1
108
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append)
constructor.
您必须以附加模式打开文件,这可以通过使用FileWriter(String fileName,boolean append)构造函数来实现。
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
应该做的伎俩
#2
22
The solution with FileWriter
is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!
使用FileWriter的解决方案正在运行,但是您无法指定输出编码,在这种情况下将使用机器的默认编码,这通常不是UTF-8!
So at best use FileOutputStream
:
所以充其量使用FileOutputStream:
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
#3
10
Try: "\r\n"
试试:“\ r \ n”
Java 7 example:
Java 7示例:
// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true)))
{
output.printf("%s\r\n", "NEWLINE");
}
catch (Exception e) {}
#4
9
Starting from Java 7:
从Java 7开始:
Define a path and the String containing the line separator at the beginning:
在开头定义路径和包含行分隔符的String:
Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";
and then you can use one of the following approaches:
然后您可以使用以下方法之一:
-
Using
Files.write
(small files):使用Files.write(小文件):
try { Files.write(p, s.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { System.err.println(e); }
-
Using
Files.newBufferedWriter
(text files):使用Files.newBufferedWriter(文本文件):
try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) { writer.write(s); } catch (IOException ioe) { System.err.format("IOException: %s%n", ioe); }
-
Using
Files.newOutputStream
(interoperable withjava.io
APIs):使用Files.newOutputStream(可与java.io API互操作):
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) { out.write(s.getBytes()); } catch (IOException e) { System.err.println(e); }
-
Using
Files.newByteChannel
(random access files):使用Files.newByteChannel(随机访问文件):
try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) { sbc.write(ByteBuffer.wrap(s.getBytes())); } catch (IOException e) { System.err.println(e); }
-
Using
FileChannel.open
(random access files):使用FileChannel.open(随机访问文件):
try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) { sbc.write(ByteBuffer.wrap(s.getBytes())); } catch (IOException e) { System.err.println(e); }
Details about these methods can be found in the Oracle's tutorial.
有关这些方法的详细信息,请参阅Oracle教程。
#5
4
In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.
如果你正在寻找一个创建和写入文件的剪切和粘贴方法,这里是我写的一个只需要一个字符串输入。如果要每次都覆盖文件,请从PrintWriter中删除“true”。
private static final String newLine = System.getProperty("line.separator");
private synchronized void writeToFile(String msg) {
String fileName = "c:\\TEMP\\runOutput.txt";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName, true));
printWriter.write(newLine + msg);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
#6
2
You can use the FileWriter(String fileName, boolean append)
constructor if you want to append data to file.
如果要将数据附加到文件,可以使用FileWriter(String fileName,boolean append)构造函数。
Change your code to this:
将您的代码更改为:
output = new BufferedWriter(new FileWriter(my_file_name, true));
From FileWriter javadoc:
来自FileWriter javadoc:
Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
给定文件名构造FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。
#7
2
On line 2 change new FileWriter(my_file_name)
to new FileWriter(my_file_name, true)
so you're appending to the file rather than overwriting.
在第2行,将新的FileWriter(my_file_name)更改为新的FileWriter(my_file_name,true),这样您就可以附加到文件而不是覆盖。
File f = new File("/path/of/the/file");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.append(line);
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}