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

2018-12-31 07:46发布

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?

22条回答
谁念西风独自凉
2楼-- · 2018-12-31 08:01

In Java 7 you can do this:

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

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

查看更多
伤终究还是伤i
3楼-- · 2018-12-31 08:05

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

}

查看更多
其实,你不懂
4楼-- · 2018-12-31 08:06

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
}
查看更多
不流泪的眼
5楼-- · 2018-12-31 08:09

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();
        }
    }
}
查看更多
高级女魔头
6楼-- · 2018-12-31 08:09

Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
查看更多
栀子花@的思念
7楼-- · 2018-12-31 08:10

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;
}
查看更多
登录 后发表回答