How do I save a String to a text file using Java?

JavaFileFile IoText Files

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 call out.close() when you've finished writing.

If you are using Java 7 or later, you can use the "https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">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.

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
	out.print(text);
}

Solution 5 - Java

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)
    {
    }
}

Solution 6 - Java

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

Solution 7 - Java

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);

Solution 8 - Java

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();
        }
    }
}

Solution 9 - Java

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
}

Solution 10 - Java

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);
}

Solution 11 - Java

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();
        }
    }
}

Solution 12 - Java

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>
            

Solution 13 - Java

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);

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());

Solution 17 - Java

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.

Solution 18 - Java

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);
    }
}

Solution 19 - Java

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();
     }
   }
}

Solution 20 - Java

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);
    }
  }

Solution 21 - Java

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.

Solution 22 - Java

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);
		}

	});

Solution 23 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin WhiteView Question on Stackoverflow
Solution 1 - JavaJeremy SmythView Answer on Stackoverflow
Solution 2 - JavaJonView Answer on Stackoverflow
Solution 3 - JavaDaniil ShevelevView Answer on Stackoverflow
Solution 4 - JavaJornView Answer on Stackoverflow
Solution 5 - JavaArtem BargerView Answer on Stackoverflow
Solution 6 - JavaskaffmanView Answer on Stackoverflow
Solution 7 - JavaMarcelView Answer on Stackoverflow
Solution 8 - JavawolfsnipesView Answer on Stackoverflow
Solution 9 - JavaSpinaView Answer on Stackoverflow
Solution 10 - JavaBullyWiiPlazaView Answer on Stackoverflow
Solution 11 - JavaPavel_HView Answer on Stackoverflow
Solution 12 - JavaAnirban ChakrabartiView Answer on Stackoverflow
Solution 13 - JavaRan AdlerView Answer on Stackoverflow
Solution 14 - JavaMostafa RezaeiView Answer on Stackoverflow
Solution 15 - JavaSean H. WorthingtonView Answer on Stackoverflow
Solution 16 - JavaGoYun.InfoView Answer on Stackoverflow
Solution 17 - Javabhathiya-pereraView Answer on Stackoverflow
Solution 18 - JavaJobin MathewView Answer on Stackoverflow
Solution 19 - JavaJohn DoeView Answer on Stackoverflow
Solution 20 - JavaBrad ParksView Answer on Stackoverflow
Solution 21 - Javaalb-i986View Answer on Stackoverflow
Solution 22 - JavaQA SpecialistView Answer on Stackoverflow
Solution 23 - JavaMouView Answer on Stackoverflow