I need to append text repeatedly to an existing file in Java. How do I do that?
我需要将文本添加到Java中现有的文件中。我该怎么做呢?
29 个解决方案
#1
631
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
您这样做是为了记录日志吗?如果有,那么有几个库。最流行的两个是Log4j和Logback。
Java 7+
If you just need to do this one time, the Files class makes this easy:
如果您只需要这样做一次,那么文件类就会使这个简单:
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 answer covers how you could do this with Files
class.
注意:如果文件不存在,上述方法将抛出NoSuchFileException。它也不会自动地附加一条新行(当附加到文本文件时,您经常需要它)。Steve Chambers的回答涵盖了如何使用文件类来完成这个任务。
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.) - FileWriter构造函数的第二个参数将告诉它附加到文件,而不是写入新文件。(如果文件不存在,它将被创建。)
- Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - 建议使用BufferedWriter作为昂贵的作者(如FileWriter)。
- Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - 使用PrintWriter可以让您访问println语法,您可能已经习惯了System.out。
- But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary. - 但是BufferedWriter和PrintWriter包装器并不是必须的。
Older 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:
如果您需要对*ava进行健壮的异常处理,它将变得非常冗长:
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
}
}
#2
145
You can use fileWriter
with a flag set to true
, for appending.
您可以使用带有标志设置为true的fileWriter作为附加。
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());
}
#3
63
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
这里的所有答案都不应该用try/catch块来完成,最后一个块中包含了。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- resources语句。关闭已声明的资源(因为它是自动处理的,而且也不那么冗长),因此不需要最后一个块。
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
}catch (IOException e) {
System.err.println(e);
}
#4
38
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();
}
}
}
#5
19
Make sure the stream gets properly closed in all scenarios.
It's a bit alarming how many of these answers leave the file handle open in case of an error. The answer https://*.com/a/15053443/2498188 is on the money but only because BufferedWriter()
cannot throw. If it could then an exception would leave the FileWriter
object open.
有多少这样的答案会在出现错误时打开文件句柄,这有点令人担忧。答案是https://*.com/a/15053443/2498188,但只因为BufferedWriter()不能抛出。如果它可以,则会让FileWriter对象打开。
A more general way of doing this that doesn't care if BufferedWriter()
can throw:
更一般的方法是,如果BufferedWriter()可以抛出:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
Edit:
As of Java 7, the recommended way is to use "try with resources" and let the JVM deal with it:
在Java 7中,推荐的方法是使用“尝试使用资源”,并让JVM处理它:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
#6
12
In Java-7 it also can be done such kind:
在Java-7中也可以这样做:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
/ / - - - - - - - - - - - - - - - - - - - - - - - -
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
#7
12
To slightly expand on Kip's answer, here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:
为了略微扩展Kip的答案,这里有一个简单的Java 7+方法,可以将新行添加到文件中,如果它还不存在,就创建它:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
Note: The above uses the Files.write
overload that writes lines of text to a file (i.e. similar to a println
command). To just write text to the end (i.e. similar to a print
command), an alternative Files.write
overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)
).
注意:上面使用的是文件。写入重载,将文本行写入文件(即类似于println命令)。将文本写到结尾(即类似于打印命令),另一个文件。写入重载可以使用,传入一个字节数组(例如:“mytext .getBytes(StandardCharsets.UTF_8))。
#8
6
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);
}
#9
6
This can be done in one line of code. Hope this helps :)
这可以在一行代码中完成。希望这有助于:)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
#10
5
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)是一个名为app的特性(或接口)。它负责将一些内容添加到特定文件/流的末尾。这个接口是在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
换句话说,您可以添加一些内容到您的gzip文件,或一些http进程。
#11
4
Using java.nio.Files along with java.nio.file.StandardOpenOption
使用nio。文件连同java.nio.file.StandardOpenOption
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,该文件接受标准openoption参数,并由结果BufferedWriter自动刷新PrintWriter。然后可以调用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.
在此代码中使用的标准openoption参数:打开文件以进行写入,只在文件中追加,如果文件不存在,则创建该文件。
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
.
路径。get("path here")可以用新文件("path here")替换。和字符集。可以修改forName(“charset name”)以适应所需的字符集。
#12
4
Try with bufferFileWriter.append, it works with me.
与bufferFileWriter试试。append,它和我一起工作。
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
#13
3
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..
这将达到你的目的。
#14
3
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
如果我们使用Java 7和以上,并且知道要添加的内容(附加到文件),我们可以在NIO包中使用newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
There are few points to note:
有几点需要注意:
- It is always a good habit to specify charset encoding and for that we have constant in class
StandardCharsets
. - 指定字符集编码一直是一个好习惯,并且我们在类标准字符集中有常量。
- The code uses
try-with-resource
statement in which resources are automatically closed after the try. - 代码使用try- resource语句,其中资源在尝试之后自动关闭。
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential
we can make use of stream APIs in Java:
虽然OP没有要求,但只是为了以防我们想要搜索一些有特定关键字的行,例如,我们可以在Java中使用流api:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
#15
2
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。
#16
2
Create a function anywhere in your project and simply call that function where ever you need it.
在项目的任何地方创建一个函数,并在需要的地方调用该函数。
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly
你们要记住,你们是在调用活动线程,而不是异步调用,因为它很可能是一个5到10页的好方法。为什么不花更多的时间在你的项目上,忘记写已经写好的东西。正确
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
三行代码,因为第三行实际上是附加文本。:P
#17
2
Library
图书馆
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Code
代码
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
#18
2
You can also try this :
你也可以试试:
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
#19
2
Better to use try-with-resources then all that pre-java 7 finally business
最好使用试用资源,然后所有的pre-java 7最终都是业务。
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
#20
2
This code will fulifil your need:
这段代码将使你的需要变得模糊。
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
#21
2
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
the true allows to append the data in the existing file. If we will write
true允许在现有文件中追加数据。如果我们将写
FileOutputStream fos = new FileOutputStream("File_Name");
It will overwrite the existing file. So go for first approach.
它将覆盖现有的文件。所以,选择第一种方法。
#22
2
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
#23
2
java 7+
java 7 +
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
在我看来,既然我是普通java的粉丝,我就会建议它是上述答案的结合。也许我聚会迟到了。这是代码:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
如果文件不存在,它会创建它,如果已经存在,它会将sampleText追加到现有文件中。使用此方法,可以避免在类路径中添加不必要的libs。
#24
1
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项目。这个项目已经提供了一个框架来满足您的需要(即对集合进行灵活的过滤)。
#25
1
The following method let's you append text to some file:
下面的方法是将文本附加到某个文件:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
Alternatively using FileUtils
:
或者使用FileUtils:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
It is not efficient but works fine. Line breaks are handled correctly and a new file is created if one didn't exist yet.
这不是有效的,但是很有效。如果一个新文件还不存在,则可以正确处理换行符,并创建一个新文件。
#26
1
My answer:
我的回答:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
#27
1
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
如果您想要在特定的行中添加一些文本,您可以首先读取整个文件,在需要的地方添加文本,然后在下面的代码中覆盖所有内容:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#28
0
/**********************************************************************
* it will write content to a specified file
*
* @param keyString
* @throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
#29
0
You can use the follong code to append the content in the file:
您可以使用以下代码在文件中添加内容:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
#1
631
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
您这样做是为了记录日志吗?如果有,那么有几个库。最流行的两个是Log4j和Logback。
Java 7+
If you just need to do this one time, the Files class makes this easy:
如果您只需要这样做一次,那么文件类就会使这个简单:
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 answer covers how you could do this with Files
class.
注意:如果文件不存在,上述方法将抛出NoSuchFileException。它也不会自动地附加一条新行(当附加到文本文件时,您经常需要它)。Steve Chambers的回答涵盖了如何使用文件类来完成这个任务。
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.) - FileWriter构造函数的第二个参数将告诉它附加到文件,而不是写入新文件。(如果文件不存在,它将被创建。)
- Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - 建议使用BufferedWriter作为昂贵的作者(如FileWriter)。
- Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - 使用PrintWriter可以让您访问println语法,您可能已经习惯了System.out。
- But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary. - 但是BufferedWriter和PrintWriter包装器并不是必须的。
Older 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:
如果您需要对*ava进行健壮的异常处理,它将变得非常冗长:
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
}
}
#2
145
You can use fileWriter
with a flag set to true
, for appending.
您可以使用带有标志设置为true的fileWriter作为附加。
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());
}
#3
63
Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?
这里的所有答案都不应该用try/catch块来完成,最后一个块中包含了。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- resources语句。关闭已声明的资源(因为它是自动处理的,而且也不那么冗长),因此不需要最后一个块。
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
}catch (IOException e) {
System.err.println(e);
}
#4
38
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();
}
}
}
#5
19
Make sure the stream gets properly closed in all scenarios.
It's a bit alarming how many of these answers leave the file handle open in case of an error. The answer https://*.com/a/15053443/2498188 is on the money but only because BufferedWriter()
cannot throw. If it could then an exception would leave the FileWriter
object open.
有多少这样的答案会在出现错误时打开文件句柄,这有点令人担忧。答案是https://*.com/a/15053443/2498188,但只因为BufferedWriter()不能抛出。如果它可以,则会让FileWriter对象打开。
A more general way of doing this that doesn't care if BufferedWriter()
can throw:
更一般的方法是,如果BufferedWriter()可以抛出:
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
Edit:
As of Java 7, the recommended way is to use "try with resources" and let the JVM deal with it:
在Java 7中,推荐的方法是使用“尝试使用资源”,并让JVM处理它:
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
#6
12
In Java-7 it also can be done such kind:
在Java-7中也可以这样做:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
/ / - - - - - - - - - - - - - - - - - - - - - - - -
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
#7
12
To slightly expand on Kip's answer, here is a simple Java 7+ method to append a new line to a file, creating it if it doesn't already exist:
为了略微扩展Kip的答案,这里有一个简单的Java 7+方法,可以将新行添加到文件中,如果它还不存在,就创建它:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
Note: The above uses the Files.write
overload that writes lines of text to a file (i.e. similar to a println
command). To just write text to the end (i.e. similar to a print
command), an alternative Files.write
overload can be used, passing in a byte array (e.g. "mytext".getBytes(StandardCharsets.UTF_8)
).
注意:上面使用的是文件。写入重载,将文本行写入文件(即类似于println命令)。将文本写到结尾(即类似于打印命令),另一个文件。写入重载可以使用,传入一个字节数组(例如:“mytext .getBytes(StandardCharsets.UTF_8))。
#8
6
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);
}
#9
6
This can be done in one line of code. Hope this helps :)
这可以在一行代码中完成。希望这有助于:)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
#10
5
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)是一个名为app的特性(或接口)。它负责将一些内容添加到特定文件/流的末尾。这个接口是在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
换句话说,您可以添加一些内容到您的gzip文件,或一些http进程。
#11
4
Using java.nio.Files along with java.nio.file.StandardOpenOption
使用nio。文件连同java.nio.file.StandardOpenOption
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,该文件接受标准openoption参数,并由结果BufferedWriter自动刷新PrintWriter。然后可以调用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.
在此代码中使用的标准openoption参数:打开文件以进行写入,只在文件中追加,如果文件不存在,则创建该文件。
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
.
路径。get("path here")可以用新文件("path here")替换。和字符集。可以修改forName(“charset name”)以适应所需的字符集。
#12
4
Try with bufferFileWriter.append, it works with me.
与bufferFileWriter试试。append,它和我一起工作。
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
#13
3
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..
这将达到你的目的。
#14
3
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
如果我们使用Java 7和以上,并且知道要添加的内容(附加到文件),我们可以在NIO包中使用newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
There are few points to note:
有几点需要注意:
- It is always a good habit to specify charset encoding and for that we have constant in class
StandardCharsets
. - 指定字符集编码一直是一个好习惯,并且我们在类标准字符集中有常量。
- The code uses
try-with-resource
statement in which resources are automatically closed after the try. - 代码使用try- resource语句,其中资源在尝试之后自动关闭。
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential
we can make use of stream APIs in Java:
虽然OP没有要求,但只是为了以防我们想要搜索一些有特定关键字的行,例如,我们可以在Java中使用流api:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
#15
2
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。
#16
2
Create a function anywhere in your project and simply call that function where ever you need it.
在项目的任何地方创建一个函数,并在需要的地方调用该函数。
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly
你们要记住,你们是在调用活动线程,而不是异步调用,因为它很可能是一个5到10页的好方法。为什么不花更多的时间在你的项目上,忘记写已经写好的东西。正确
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
三行代码,因为第三行实际上是附加文本。:P
#17
2
Library
图书馆
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Code
代码
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
#18
2
You can also try this :
你也可以试试:
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
#19
2
Better to use try-with-resources then all that pre-java 7 finally business
最好使用试用资源,然后所有的pre-java 7最终都是业务。
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
#20
2
This code will fulifil your need:
这段代码将使你的需要变得模糊。
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
#21
2
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
the true allows to append the data in the existing file. If we will write
true允许在现有文件中追加数据。如果我们将写
FileOutputStream fos = new FileOutputStream("File_Name");
It will overwrite the existing file. So go for first approach.
它将覆盖现有的文件。所以,选择第一种方法。
#22
2
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
#23
2
java 7+
java 7 +
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
在我看来,既然我是普通java的粉丝,我就会建议它是上述答案的结合。也许我聚会迟到了。这是代码:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
如果文件不存在,它会创建它,如果已经存在,它会将sampleText追加到现有文件中。使用此方法,可以避免在类路径中添加不必要的libs。
#24
1
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项目。这个项目已经提供了一个框架来满足您的需要(即对集合进行灵活的过滤)。
#25
1
The following method let's you append text to some file:
下面的方法是将文本附加到某个文件:
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
Alternatively using FileUtils
:
或者使用FileUtils:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
It is not efficient but works fine. Line breaks are handled correctly and a new file is created if one didn't exist yet.
这不是有效的,但是很有效。如果一个新文件还不存在,则可以正确处理换行符,并创建一个新文件。
#26
1
My answer:
我的回答:
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
#27
1
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
如果您想要在特定的行中添加一些文本,您可以首先读取整个文件,在需要的地方添加文本,然后在下面的代码中覆盖所有内容:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#28
0
/**********************************************************************
* it will write content to a specified file
*
* @param keyString
* @throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
#29
0
You can use the follong code to append the content in the file:
您可以使用以下代码在文件中添加内容:
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();