Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a String to a text file? [closed]

I have a String that is storing the processed results for a few files. How do I write that String to a .txt file in my project? I have another String variable which is the desired name of the .txt file.

like image 333
user1261445 Avatar asked Apr 30 '12 20:04

user1261445


1 Answers

Files that are created using byte-based streams represent data in binary format. Files created using character-based streams represent data as sequences of characters. Text files can be read by text editors, whereas binary files are read by a program that converts the data to a human-readable format.

Classes FileReader and FileWriter perform character-based file I/O.

If you are using Java 7, you can uses try-with-resources to shorten method considerably:

import java.io.PrintWriter;
public class Main {
    public static void main(String[] args) throws Exception {
        String str = "写字符串到文件"; // Chinese-character string
        try (PrintWriter out = new PrintWriter("output.txt", "UTF-8")) {
            out.write(str);
        }
    }
}

You can use Java’s try-with-resources statement to automatically close resources (objects that must be closed when they are no longer needed). You should consider a resource class must implement the java.lang.AutoCloseable interface or its java.lang.Closeable subinterface.

like image 135
Paul Vargas Avatar answered Nov 05 '22 12:11

Paul Vargas