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

2018-12-31 07:46发布

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?

22条回答
何处买醉
2楼-- · 2018-12-31 08:11

In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file (see JavaDoc here and here). In the simplest case it is now a one-liner:

Files.writeString(path, "foo")

With the optional Varargs parameter, further options, such as appending to a existing file or automatically creating a non-existent file can be set (see JavaDoc here).

查看更多
不再属于我。
3楼-- · 2018-12-31 08:14

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

查看更多
十年一品温如言
4楼-- · 2018-12-31 08:16

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}
查看更多
十年一品温如言
5楼-- · 2018-12-31 08:16

It's better to close the writer/outputstream in a finally block, just in case something happen

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}
查看更多
心情的温度
6楼-- · 2018-12-31 08:18
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.

查看更多
泛滥B
7楼-- · 2018-12-31 08:18

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);
查看更多
登录 后发表回答