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

后端 未结 24 1104
不知归路
不知归路 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:35

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

提交回复
热议问题