如何将文本附加到 Java 中的现有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1625234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append text to an existing file in Java
提问by flyingfromchina
I need to append text repeatedly to an existing file in Java. How do I do that?
我需要将文本重复附加到 Java 中的现有文件。我怎么做?
采纳答案by Kip
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4jand Logback.
你这样做是为了记录目的吗?如果是这样,则有几个库可用于此。两个最受欢迎的是Log4j和Logback。
Java 7+
Java 7+
If you just need to do this one time, the Files classmakes this easy:
如果您只需要执行一次,Files 类可以让这一切变得简单:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Steve Chambers's answercovers how you could do this with Files
class.
小心:NoSuchFileException
如果文件不存在,上述方法将抛出一个。它也不会自动附加换行符(在附加到文本文件时您经常需要它)。史蒂夫钱伯斯的回答涵盖了如何通过Files
课堂做到这一点。
However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:
但是,如果您要多次写入同一个文件,则上述操作必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,缓冲写入器更好:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
笔记:
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
FileWriter
构造函数的第二个参数将告诉它附加到文件中,而不是写入一个新文件。(如果文件不存在,它将被创建。)BufferedWriter
对于昂贵的编写器(例如FileWriter
),建议使用 a 。- 使用 a 可以
PrintWriter
让您访问println
您可能习惯使用的语法System.out
。 - 但是
BufferedWriter
和PrintWriter
包装器并不是绝对必要的。
Older Java
较旧的 Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
异常处理
If you need robust exception handling for older Java, it gets very verbose:
如果您需要对旧 Java 进行健壮的异常处理,它会变得非常冗长:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
回答by northpole
You can use fileWriter
with a flag set to true
, for appending.
您可以将fileWriter
标志设置为true
, 用于附加。
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
回答by ripper234
Edit- as of Apache Commons 2.1, the correct way to do it is:
编辑- 从 Apache Commons 2.1 开始,正确的做法是:
FileUtils.writeStringToFile(file, "String to append", true);
I adapted @Kip's solution to include properly closing the file on finally:
我调整了@Kip 的解决方案,以包括最终正确关闭文件:
public static void appendToFile(String targetFile, String s) throws IOException {
appendToFile(new File(targetFile), s);
}
public static void appendToFile(File targetFile, String s) throws IOException {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
out.println(s);
} finally {
if (out != null) {
out.close();
}
}
}
public static void appendToFile(String targetFile, String s) throws IOException {
appendToFile(new File(targetFile), s);
}
public static void appendToFile(File targetFile, String s) throws IOException {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
out.println(s);
} finally {
if (out != null) {
out.close();
}
}
}
回答by xhudik
I just add small detail:
我只是添加小细节:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable(http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
2.nd 参数 (true) 是称为可附加( http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html)的功能(或接口)。它负责能够在特定文件/流的末尾添加一些内容。这个接口是从 Java 1.5 开始实现的。具有此接口的每个对象(即BufferedWriter、CharArrayWriter、CharBuffer、FileWriter、FilterWriter、LogStream、OutputStreamWriter、PipedWriter、PrintStream、PrintWriter、StringBuffer、StringBuilder、StringWriter、Writer)都可以用于添加内容
In other words, you can add some content to your gzipped file, or some http process
换句话说,你可以在你的 gzipped 文件中添加一些内容,或者一些 http 进程
回答by Benjamin Varghese
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
this will do what you intend for..
这会做你想要的..
回答by etech
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
此处所有带有 try/catch 块的答案不都应该包含在 finally 块中的 .close() 片段吗?
Example for marked answer:
标记答案示例:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:
此外,从 Java 7 开始,您可以使用try-with-resources 语句。关闭声明的资源不需要 finally 块,因为它是自动处理的,而且也不那么冗长:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
回答by dantuch
Sample, using Guava:
示例,使用番石榴:
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
回答by SharkAlley
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
Then catch an IOException somewhere upstream.
然后在上游某处捕获 IOException。
回答by icasdri
Using java.nio.Filesalong with java.nio.file.StandardOpenOption
使用 java.nio。文件和 java.nio.file。标准开放期权
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
This creates a BufferedWriter
using Files, which accepts StandardOpenOption
parameters, and an auto-flushing PrintWriter
from the resultant BufferedWriter
. PrintWriter
's println()
method, can then be called to write to the file.
这将创建一个BufferedWriter
using 文件,它接受StandardOpenOption
参数,并PrintWriter
从结果BufferedWriter
. PrintWriter
的println()
方法,然后可以调用写入文件。
The StandardOpenOption
parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
StandardOpenOption
此代码中使用的参数:打开文件进行写入,仅追加到文件中,如果文件不存在则创建文件。
Paths.get("path here")
can be replaced with new File("path here").toPath()
.
And Charset.forName("charset name")
can be modified to accommodate the desired Charset
.
Paths.get("path here")
可以替换为new File("path here").toPath()
。并且Charset.forName("charset name")
可以进行修改以适应所需的Charset
。
回答by Tom Drake
I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).
我可能会建议apache commons 项目。这个项目已经提供了一个框架来做你需要的事情(即灵活的集合过滤)。