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

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

    import java.io.*;
    
    private void stringToFile( String text, String fileName )
     {
     try
     {
        File file = new File( fileName );
    
        // if file doesnt exists, then create it 
        if ( ! file.exists( ) )
        {
            file.createNewFile( );
        }
    
        FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
        BufferedWriter bw = new BufferedWriter( fw );
        bw.write( text );
        bw.close( );
        //System.out.println("Done writing to " + fileName); //For testing 
     }
     catch( IOException e )
     {
     System.out.println("Error: " + e);
     e.printStackTrace( );
     }
    } //End method stringToFile
    

    You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.

提交回复
热议问题