769

I need to append text repeatedly to an existing file in Java. How do I do that?

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
flyingfromchina
  • 9,571
  • 12
  • 35
  • 38

31 Answers31

915

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, 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). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

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 as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

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:

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
    }
}
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Kip
  • 107,154
  • 87
  • 232
  • 265
  • 35
    You should either use java7 try-with-resources or put the close() in a finally block, in order to make sure that the file is closed in case of exception – Svetlin Zarev Jan 02 '14 at 10:44
  • 3
    Lets imagine that `new BufferedWriter(...)` throws an exception; Will the `FileWriter` be closed ? I guess that it will not be closed, because the `close()` method (in normal conditions) will be invoked on the `out` object, which int this case will not be initialized - so actually the `close()` method will not be invoked -> the file will be opened, but will not be closed. So IMHO the `try` statement should look like this `try(FileWriter fw = new FileWriter("myFile.txt")){ Print writer = new ....//code goes here }` And he should `flush()` the writer before exiting the `try` block!!! – Svetlin Zarev Jan 14 '14 at 19:02
  • it's not work for me. in destination file, there is one "test" and many empty space – Mahdi Nov 17 '14 at 06:02
  • If you use Java 7+, then why not use a simple `Files.write` instead of a PrintWriter of a BufferedWriter of a FileWriter? – assylias May 18 '15 at 15:50
  • This answer fails to correctly handle exceptions. See @Emily's [answer](http://stackoverflow.com/a/18746974/603516) for proper way. – Vadzim Jun 16 '15 at 15:31
  • Why is FileWriter treated like expensive writer? – RadijatoR Jul 27 '15 at 18:35
  • @RadijatoR Because it has to do disk I/O operations. In the [JavaDoc for BufferedWriter](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html), it says "In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters" – Kip Jul 27 '15 at 19:21
  • This can be done in one line of code. Hope this helps :) Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND); – Rahbee Alvee Aug 06 '15 at 17:39
  • The `File` and filename-based constructors of `PrintWriter` mention that they buffer automatically. But when a `PrintWriter` wraps another `Writer`, there is no comment in the docs on whether it adds another layer of buffering or not. Given the ambiguity, it seems best to include a `BufferedWriter` explicitly, as in this answer. – Evgeni Sergeev Nov 14 '15 at 06:37
  • @Decoded your suggested edit was a syntax error. `out` is only defined in the `try` block. In the `finally` block it does not exist. You would have to move the declaration of `out` out of the `try` block. This is exactly the problem that the Java 7+ syntax resolves. As I've noted, I've left exception handling for the reader; I think it's beyond the scope of this answer. – Kip Mar 31 '16 at 12:12
  • You should close only the out variable! http://stackoverflow.com/questions/484925/does-closing-the-bufferedreader-printwriter-close-the-socket-connection – i000174 Dec 30 '16 at 12:49
  • 2
    A couple of possible "gotchas" with the Java 7 method: (1) If the file doesn't already exist, `StandardOpenOption.APPEND` won't create it - kind of like a silent failure as it won't throw an exception either. (2) Using `.getBytes()` will mean there is no return character before or after the appended text. Have added an [alternative answer](https://stackoverflow.com/questions/1625234#44301865) to address these. – Steve Chambers Jun 01 '17 at 08:10
  • 1
    @SteveChambers Thanks for the input. I couldn't believe that append mode does not create the file if it does not exist, so I had to try it to confirm. Not sure what they were thinking there... I found that it does actually throw an exception, but if you copy/paste my code and leave the `catch` block blank, then you don't see it. I've updated my answer to reflect these issues and I added a link to your answer. – Kip Jun 03 '17 at 20:23
  • Is it safe to use the faster, buffered operations? I'm trying to log something that happens right before a crash, and I need to make sure the file is going to get written. – Michael Jul 16 '17 at 20:51
  • @Michael when the buffered writer is closed, it will write whatever is in the buffer. Or you can explicitly call `flush()` to force it to flush its buffer (writing the contents) immediately. – Kip Jul 17 '17 at 20:32
  • "If you need robust exception handling for older Java, it gets very verbose." If by "verbose" you mean "a horrifying abomination". – Andrew Koster Nov 13 '18 at 16:44
  • This works in Scala as well: try { Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND) } catch { case ioe: IOException => { println("IOException thrown!") } case e: Exception => println("Non-IOException thrown!") } – Janac Meena Mar 21 '19 at 20:03
  • The `Files.writeString()` and `Path.of()` are both no symbol error, is it a typo? – Weekend Feb 28 '22 at 05:42
  • @Weekend it worked when i wrote the answer but i haven't done any serious java development in quite a long time – Kip Mar 02 '22 at 17:03
  • "Log4j" Haha, that part certainly didn't age well. – Nyde Jul 31 '22 at 19:48
201

You can use fileWriter with a flag set to true , for appending.

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());
}
eRaisedToX
  • 3,221
  • 2
  • 22
  • 28
northpole
  • 10,244
  • 7
  • 35
  • 58
  • 10
    `close` should be placed in `finally` block just like shown in [@etech's answer](http://stackoverflow.com/a/15053443/1393766) in case exception would be thrown between creation of FileWriter and invoking close. – Pshemo Mar 13 '15 at 21:19
  • 5
    Good answer, although its better to use System.getProperty( "line.separator" ) for a new line rather than "\n". – Henry Zhu Jul 13 '15 at 07:34
  • @Decoded I've rolled back your edit on this answer, as it does not compile. – Kip Mar 31 '16 at 12:15
  • @Kip, What was the issue? I must have entered a "typo". – Decoded Aug 17 '16 at 19:53
  • @Decoded you had `fw.close()` in a finally block, without a nested try/catch (`.close()` can throw `IOException`) – Kip Aug 17 '16 at 19:59
  • 4
    How bout try-with-resources? ```try(FileWriter fw = new FileWriter(filename,true)){ // Whatever }catch(IOException ex){ ex.printStackTrace(); } ``` – php_coder_3809625 Aug 18 '16 at 12:12
75

Shouldn't all of the answers here with try/catch blocks have the .close() pieces contained in a finally block?

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:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
etech
  • 2,548
  • 1
  • 27
  • 24
  • 1
    When `out` goes out of scope, it is automatically closed when it gets garbage-collected, right? In your example with the `finally` block, I think you actually need another nested try/catch around `out.close()` if I remember correctly. The Java 7 solution is pretty slick! (I haven't been doing any Java dev since Java 6, so I was unfamiliar with that change.) – Kip Aug 21 '13 at 18:23
  • 2
    @Kip Nope, going out-of-scope does nothing in Java. The file will get closed at some random time in the future. (probably when the program closes) – Navin Jun 17 '14 at 02:38
  • @etech Will the second approach need the `flush` method? – syfantid Feb 14 '16 at 10:55
53

Using Apache Commons 2.1:

import org.apache.logging.log4j.core.util.FileUtils;

FileUtils.writeStringToFile(file, "String to append", true);
Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 7
    Oh, thank you. I was amused by the complexity of all other answers. I really do not get why people like to complicate their (developer) life. – Alphaaa Jul 29 '13 at 16:05
  • 8
    The problem with this approach is that it opens and closes the output stream every single time. Depending on what and how often you write to your file, this could result in a ridiculous overhead. – Buffalo Jul 28 '15 at 08:42
  • 1
    @Buffalo is right. But you can always use StringBuilder for building large chunks (that are worth writing) before writing them to file. – Konstantin K Mar 19 '17 at 10:16
  • 1
    @KonstantinK but then all the content you need to write is loaded into memory. – Rafael Membrives Aug 06 '20 at 12:35
38

Slightly expanding 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:

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...
}

Further notes:

  1. 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)).

  2. The CREATE option will only work if the specified directory already exists - if it doesn't, a NoSuchFileException is thrown. If required, the following code could be added after setting path to create the directory structure:

    Path pathParent = path.getParent();
    if (!Files.exists(pathParent)) {
        Files.createDirectories(pathParent);
    }
    
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
  • 1
    Do you need to check if the file exists? I thought`.CREATE` does the job for you. – Enigmatic Jan 29 '19 at 18:05
  • If `.CREATE` is used when the file already exists it silently fails to append anything - no exception is thrown but the existing file contents remain unchanged. – Steve Chambers Aug 13 '20 at 21:06
  • Using `APPEND` + `CREATE` works perfectly, no check necessary: `Files.write(Paths.get("test.log"), (Instant.now().toString() + "\r\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);` – lapo Nov 12 '20 at 14:01
23

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://stackoverflow.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.

A more general way of doing this that doesn't care if BufferedWriter() can throw:

  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:

  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.
  }
Community
  • 1
  • 1
Emily L.
  • 5,673
  • 2
  • 40
  • 60
  • +1 for correct ARM with Java 7. Here is good question about this tricky theme: http://stackoverflow.com/questions/12552863/correct-idiom-for-managing-multiple-chained-resources-in-try-with-resources-bloc. – Vadzim Jun 16 '15 at 15:34
  • 1
    Hmm, for some reason `PrintWriter.close()` is not declared as `throws IOException` in [the docs](http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#close%28%29). Looking at its [source](http://www.docjar.com/html/api/java/io/PrintWriter.java.html), the `close()` method, indeed, cannot throw `IOException`, because it catches it from the underlying stream, and sets a flag. So if you're working on the code for the next Space Shuttle or an X-ray dose metering system, you should use `PrintWriter.checkError()` after attempting to `out.close()`. This should really have been documented. – Evgeni Sergeev Nov 14 '15 at 07:02
  • If we're going to be super paranoid about closing, each of those `XX.close()` should be in its own try/catch, right? For example, `out.close()` could throw an exception, in which case `bw.close()` and `fw.close()` would never get called, and `fw` is the one that is most critical to close. – Kip Apr 06 '16 at 20:29
14

In Java-7 it also can be done such kind:

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);
Tsolak Barseghyan
  • 1,048
  • 11
  • 16
13

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:

 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.

Lefteris Bab
  • 787
  • 9
  • 19
9

This can be done in one line of code. Hope this helps :)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
Rahbee Alvee
  • 1,924
  • 7
  • 26
  • 42
  • 2
    its may be not enough:) better version is Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE); – evg345 Feb 02 '18 at 08:28
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

In other words, you can add some content to your gzipped file, or some http process

xhudik
  • 2,414
  • 1
  • 21
  • 39
5

Using java.nio.Files along with 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.

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.

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.

icasdri
  • 106
  • 1
  • 4
4

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);
}
dantuch
  • 9,123
  • 6
  • 45
  • 68
  • 13
    This is horrible advice. You open a stream to the file 42 times instead of once. – xehpuk Feb 06 '15 at 16:21
  • 3
    @xehpuk well, it depends. 42 is still ok, if it makes code much more readable. 42k wouldn't be acceptable. – dantuch Feb 10 '15 at 10:41
4

Try with bufferFileWriter.append, it works with me.

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);
}
ahajib
  • 12,838
  • 29
  • 79
  • 120
4
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

FileOutputStream fos = new FileOutputStream("File_Name");

It will overwrite the existing file. So go for first approach.

ahajib
  • 12,838
  • 29
  • 79
  • 120
4
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.
        }

    }

}
David Charles
  • 537
  • 6
  • 11
  • The above is just a quick example implementation of the solution presented [At this link](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java/18746974#18746974). So you can copy and and run the code and immediately see how it works, be sure that the output.out file is in the same directory as the Writer.java file – David Charles Feb 15 '17 at 15:02
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..

3

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
}
aashima
  • 1,203
  • 12
  • 31
3

Better to use try-with-resources then all that pre-java 7 finally business

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();
    }
}
mikeyreilly
  • 6,523
  • 1
  • 26
  • 21
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.

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:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

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:

//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();
}
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • a caveat: when using BufferedWriter `write(String string)` if one expects a new line after each string written, `newLine()` should be called – yongtw123 Jun 26 '15 at 10:20
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.

SharkAlley
  • 11,399
  • 5
  • 51
  • 42
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

    //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

Netcfmx
  • 121
  • 5
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);
    }
}
abSiddique
  • 11,647
  • 3
  • 23
  • 30
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).

Tom Drake
  • 527
  • 5
  • 11
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:

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.

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
1

This code will fulifil your need:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();
APC
  • 144,005
  • 19
  • 170
  • 281
Shalini Baranwal
  • 2,780
  • 4
  • 24
  • 34
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();
    }
}
lfvv
  • 1,509
  • 15
  • 17
0

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
}
userAsh
  • 147
  • 10
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()
Mihir Patel
  • 404
  • 6
  • 14
0

For JDK version >= 7

You can utilise this simple method which appends the given content to the specified file:

void appendToFile(String filePath, String content) {
  try (FileWriter fw = new FileWriter(filePath, true)) {
    fw.write(content + System.lineSeparator());
  } catch (IOException e) { 
    // TODO handle exception
  }
}

We are constructing a FileWriter object in append mode.

Saikat
  • 14,222
  • 20
  • 104
  • 125
-1

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(); 
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
shriram
  • 189
  • 4
  • 12
-1

1.7 Approach:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}