804

In Java, I have text from a text field in a String variable called "text".

How can I save the contents of the "text" variable to a file?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Justin White
  • 8,273
  • 4
  • 19
  • 9

24 Answers24

814

If you're simply outputting text, rather than any binary data, the following will work:

PrintWriter out = new PrintWriter("filename.txt");

Then, write your String to it, just like you would to any output stream:

out.println(text);

You'll need exception handling, as ever. Be sure to close the output stream when you've finished writing.

out.close()

If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

You will still need to explicitly throw the java.io.FileNotFoundException as before.

Fangming
  • 24,551
  • 6
  • 100
  • 90
Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
  • What's exception handling? Where will this file be saved? – Justin White Jun 27 '09 at 21:18
  • it'll be saved in the current directory, whatever that is as far as the JVM is concerned. Exception handling is the try{} catch(){} stuff you see in other answers :) – Jeremy Smyth Jun 27 '09 at 21:42
  • 4
    @Justin, you could also pass an absolute path (e.g. "/tmp/filename.txt") to the FileOutputStream constructor, to save the file anywhere you want – Jonik Jun 28 '09 at 08:54
  • 8
    Btw, this could be simplified using the convenience constructors PrintStream has had since 1.5. This would suffice: PrintStream out = new PrintStream("filename.txt"); – Jonik Jun 28 '09 at 16:22
  • Futhermore, as we're outputting text, PrintWriter would be more appropriate, and just as convenient. From PrintStream javadocs: "The PrintWriter class should be used in situations that require writing characters rather than bytes." – Jonik Jun 28 '09 at 16:29
  • 10
    Need to close that file though at some point...? http://www.codecodex.com/wiki/ASCII_file_save#Java – JStrahl Jun 22 '12 at 08:03
  • new PrintWriter(file).println(output); results in 0 byte file. Output is a string of 6000 chars...No matter if the file exists already or not... – lisak Sep 04 '12 at 12:35
  • @Sloin @Devolus Did you make sure to call `out.close()`? It writes an empty file if the PrintWriter is garbage-collected before it's flushed or closed, but if you `close()` it correctly it writes the file. – Jeremy Smyth Aug 01 '13 at 13:21
  • 3
    You want to use try{} catch(){}finally{}, where in finally{} you close the file if it is not null. – Benas Aug 13 '14 at 13:34
  • 26
    In java8 you can try(PrintStream ps = new PrintStream("filename")) { ps.println(out); } this will handle close for you – Anton Chikin Feb 06 '15 at 16:14
  • 1
    Regarding @AntonChikin comment above: you can also do this in Java 7 – yegeniy Mar 17 '15 at 13:48
  • out.flush(); after this line only i can see data in my file – Srinivas Nangana Aug 24 '22 at 16:49
277

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data, Charset charset) 

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));

You might also want to consider specifying the encoding for the file as well.

tostao
  • 2,803
  • 4
  • 38
  • 61
Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
  • 10
    Just a minor correction, the second fragment should read: FileUtils.writeStringToFile(new File("test.txt"), "Hello File"); – pm_labs Feb 09 '12 at 00:31
  • 3
    For those of us who prefer Guava, [it can do this too](http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java/11254277#11254277). – Jonik Dec 29 '13 at 15:50
  • 16
    The function is now deprecated, you should add the default charset --> `FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8"));` – Paul Fournel Nov 09 '17 at 08:10
139

In Java 7 you can do this:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

Daniil Shevelev
  • 11,739
  • 12
  • 50
  • 73
  • 4
    In case someone later wondered, the encoding would be the platform standard. – Haakon Løtveit Nov 29 '15 at 14:12
  • 13
    `content.getBytes(StandardCharsets.UTF_8)` can be used to explicitly define the encoding. – John29 Apr 28 '16 at 20:43
  • 1
    Note that StandardOpenOption.CREATE is not the default one StandardOpenOption.CREATE and StandardOpenOption.TRUNCATE_EXISTING is the default. To use the default just remove the third parameter. – Tinus Tate Jan 10 '19 at 14:57
  • Please see Tinus Tate's comment! What is the process to edit this example? I wonder how many thousands of people have taken this example as-is only to find that they have unexpected results when they overwrite a file with a shorter string. As Tinus indicates, TRUNCATE_EXISTING is crucial unless you fully understand and have an actual reason for not wanting to truncate the existing file when overwriting with a shorter string. – jch Oct 08 '19 at 23:46
  • 2
    In java 11 you can simply put a String as a second parameter! Hooray! – Dennis Gloss Nov 20 '19 at 10:22
  • But you have to use `writeString()` instead of `write()` then, right? – anothernode Oct 14 '22 at 09:19
115

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}
everton
  • 7,579
  • 2
  • 29
  • 42
Jorn
  • 20,612
  • 18
  • 79
  • 126
  • @XP1 I know, that's a great improvement. I've used Lombok for this in Java 6: just go `@Cleanup new FileOutputStream(...)` and you're done. – Jorn Sep 04 '11 at 09:31
  • 8
    Don't forget to call out.flush(); then out.close(); – Alex Byrth Jan 11 '16 at 01:16
  • @AlexByrth why should he? – Andrew Tobilko Sep 11 '18 at 16:51
  • 1
    Large files are recorded in the background (another thread) and take time to record. Calling flush () ensures that everything has been written on the next line, synchronizing the operation. But this is *optional*, but good practice if you handle large files, as logs. – Alex Byrth Sep 12 '18 at 18:10
  • 2
    Note that out.close() already flushes the stream, which means it is not necessary to call out.flush(). – hjk321 Dec 31 '19 at 05:38
83

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
  • 4
    Removing all try/catch and simplify it I'm also able to do it in one line just by doing the: (new BufferedWriter( new FileWriter( filename))).write(str); – Artem Barger Jun 27 '09 at 19:46
  • Wrapping a FileWriter in a BufferedWriter is superfluous when you're writing out the entire file in a single `write()` call. – Adrian Pronk Nov 22 '11 at 06:08
  • 2
    It seems that `.close()` doesn't throw (at least in Java 7?), is the last trycatch perhaps redundant? – Kos Jun 14 '12 at 10:43
  • 17
    Swallowing exceptions like that is going to make life hard for you when exceptions really do occur. At the very least you should rethrow them: `throw new RuntimeException(e);` – Roger Keays Feb 11 '13 at 19:05
70

Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.

Ankur
  • 50,282
  • 110
  • 242
  • 312
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 20
    I couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution. – skaffman Jun 27 '09 at 20:04
  • 1
    Would you suggest that he go back and re-implement java.file.IO and java.io.PrintStream in raw C? Of course not. You use the java.io abstractions, and save your effort for real problems. And Commons IO is a better abstraction than java.io when it comes to this particular problem. – skaffman Jun 27 '09 at 21:23
  • 3
    No, obviously not. I'm only disagreeing that your solution might not be the first thing I'd throw at someone who's a beginner Java programmer. You aren't suggesting that you've never written such a thing, are you? – duffymo Jun 27 '09 at 21:25
  • 8
    I have, yes, but that's before I found commons-io. Since finding that, I've never written that sort of thing by hand, even in a one-class project. If I'd known about it from day one, I'd have used it from day one. – skaffman Jun 27 '09 at 21:40
  • 5
    Exactly, but you're an experienced developer. Your bio says your a JBOSS/Spring user, but certainly you wouldn't have been up to either one in your first "Hello, World" effort. I'm not disagreeing with the proper use of libraries. I'm saying that people attempting a language for the first time should try to know it at its bottom, even if that means doing things that they'll discard later on when they're experienced and know better. – duffymo Jun 27 '09 at 21:45
  • 2
    I implemented this without commons and got a less than obvious exception thrown. I then implemented this using commons and it told me exactly what was wrong. Moral of the story: why live in the dark ages if you don't have to? – SilentNot Apr 14 '14 at 17:42
  • @duffymo: well Commons way now moved to [Java 7](http://stackoverflow.com/a/22445604/281545) anyway :D – Mr_and_Mrs_D Apr 17 '14 at 14:42
  • +1 for using a well-known library. We still need answers "from the bottom" and oriented to "experienced" developers – Sergio A. Jul 04 '19 at 11:33
54

In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:

Files.writeString(Path.of("my", "path"), "My String");

And the second method (see JavaDoc here) allows to specify an individual charset:

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Marcel
  • 1,104
  • 10
  • 11
  • 3
    This needs more upvotes. The answer gets buried in the amount of answers provided to this question, yet it is superior to many of them. *E.g.* only a minimal amount of lines is required, there is also no dependency on Apache Commons. – Koenigsberg Mar 29 '21 at 09:27
  • I second above comment, this is an elegant solution !! – sarath Nov 21 '22 at 14:50
25

You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...

import java.io.*;

public class Main {

    public static void main(String[] args) {

        try {
            String str = "SomeMoreTextIsHere";
            File newTextFile = new File("C:/thetextfile.txt");

            FileWriter fw = new FileWriter(newTextFile);
            fw.write(str);
            fw.close();

        } catch (IOException iox) {
            //do stuff with exception
            iox.printStackTrace();
        }
    }
}
Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
16

I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}
Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
Spina
  • 8,986
  • 7
  • 37
  • 36
14

Using Java 7:

public static void writeToFile(String text, String targetFilePath) throws IOException
{
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
  • A word to the wise - this will create a new file if it isn't there, but will overwrite the characters of the existing file if it is. If the new data is smaller, that will mean you probably create a corrupted file. Ask me how I know! – Chris Rae Feb 05 '17 at 23:29
  • Ok, how do you know? – ojblass Mar 10 '18 at 02:58
  • 1
    Just use `Files.write(targetPath, bytes);` to overwrite the file then. It will work as expected. – BullyWiiPlaza Mar 10 '18 at 12:09
14

In case if you need create text file based on one single string:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class StringWriteSample {
    public static void main(String[] args) {
        String text = "This is text to be saved in file";

        try {
            Files.write(Paths.get("my-file.txt"), text.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Pavel_H
  • 358
  • 4
  • 9
  • 1
    Files.write(path, byte[]) will use UTF-8 encoding. String.getBytes() uses the default platform encoding. So this is a potential issue. Use string.getBytes(StandardCharsets.UTF_8)! – rmuller Jun 15 '19 at 07:04
13

Use Apache Commons IO api. Its simple

Use API as

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
12

Use this, it is very readable:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
BDL
  • 21,052
  • 22
  • 49
  • 55
Ran Adler
  • 3,587
  • 30
  • 27
11
import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // if file doesnt exists, then create it 
    if ( ! file.exists( ) )
    {
        file.createNewFile( );
    }

    FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
    BufferedWriter bw = new BufferedWriter( fw );
    bw.write( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.

Sean H. Worthington
  • 1,701
  • 15
  • 9
11

Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
GoYun.Info
  • 1,356
  • 12
  • 12
11

You could do this:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};
javaPlease42
  • 4,699
  • 7
  • 36
  • 65
Mostafa Rezaei
  • 500
  • 1
  • 5
  • 12
7

If you only care about pushing one block of text to file, this will overwrite it each time.

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

This example allows the user to select a file using a file chooser.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
bhathiya-perera
  • 1,303
  • 14
  • 32
  • @Eric Leschinski : thank you for making my answer more professional (i also assumed this was exactly what the OP wanted since this is what actually most people wants,just dump the text and replace it) – bhathiya-perera Aug 15 '13 at 17:36
  • 2
    Once the original question has been answered and the OP is satisfied and long-gone, pages like this serve only as a useful artifact to people who land here from a Google search. I landed on this page in order to create a mini text appender to a file. So it's good to speak to the entire audience rather than the OP after the OP has moved on. – Eric Leschinski Aug 15 '13 at 20:19
6
private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}
aboger
  • 2,214
  • 6
  • 33
  • 47
Jobin Mathew
  • 124
  • 1
  • 8
  • 3
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Johan May 10 '19 at 10:55
  • 1
    close() may never be called. Please, improve your answer adding the proper error case handling. – Boris Brodski Apr 27 '20 at 20:21
6

Basically the same answer as here, but easy to copy/paste, and it just works ;-)

  import java.io.FileWriter;

  public void saveToFile(String data, String filename) {
    try (
      FileWriter fw = new FileWriter(filename)) {
      fw.write(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
4

It's better to close the writer/outputstream in a finally block, just in case something happen

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}
  • 3
    even better: use try-with-resources – Janus Troelsen Feb 22 '13 at 18:35
  • Yes, @JanusTroelsen is right, better use The try-with-resources statement https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html –  Jun 21 '15 at 08:11
0

I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.

alb-i986
  • 325
  • 2
  • 14
0

If you wish to keep the carriage return characters from the string into a file here is an code example:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });
Supercoder
  • 1,066
  • 1
  • 10
  • 16
0

I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation

Github repository

and the answer to your question is so easy

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");
-1

My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}
Mou
  • 145
  • 1
  • 6