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

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

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

提交回复
热议问题