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

后端 未结 24 1087
不知归路
不知归路 2020-11-22 04:18

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?

相关标签:
24条回答
  • 2020-11-22 04:43

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

    0 讨论(0)
  • 2020-11-22 04:45

    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);
    
    0 讨论(0)
  • 2020-11-22 04:48

    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

    0 讨论(0)
  • 2020-11-22 04:49

    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.

    0 讨论(0)
  • 2020-11-22 04:49

    Take a look at the Java File API

    a quick example:

    try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
        out.print(text);
    }
    
    0 讨论(0)
  • 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题