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


Answers

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

static void writeStringToFile(File file, String data) 

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

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

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

Question

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?




You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file. if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();

Text.add(TextArea.getText());

SaveFile(NameFile, Text);

}


public void SaveFile(String name, ArrayList< String> message) {

path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

File file1 = new File(path);

try {

    if (!file1.exists()) {

        file1.createNewFile();
    }


    File[] files = file1.listFiles();


    FileWriter fw = new FileWriter(file1, true);

    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < message.size(); i++) {

        bw.write(message.get(i));
        bw.newLine();
    }

    bw.close();
    fw.close();

    FileReader fr = new FileReader(file1);

    BufferedReader br = new BufferedReader(fr);

    fw = new FileWriter(file1, true);

    bw = new BufferedWriter(fw);

    while (br.ready()) {

        String line = br.readLine();

        System.out.println(line);

        bw.write(line);
        bw.newLine();

    }
    br.close();
    fr.close();

} catch (IOException ex) {
    ex.printStackTrace();
    JOptionPane.showMessageDialog(null, "Error in" + ex);        

}




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



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>



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




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.




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



Take a look at the Java File API

a quick example:

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



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