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

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

    You could do this:

    import java.io.*;
    import java.util.*;
    
    class WriteText
    {
        public static void main(String[] args)
        {   
            try {
                String text = "Your sample content to save in a text file.";
                BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
                out.write(text);
                out.close();
            }
            catch (IOException e)
            {
                System.out.println("Exception ");       
            }
    
            return ;
        }
    };
    

提交回复
热议问题