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

后端 未结 24 1086
不知归路
不知归路 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.

    0 讨论(0)
  • 2020-11-22 04:28

    Basically the same answer as here, but easy to copy/paste, and it just works ;-)

      import java.io.FileWriter;
    
      public void saveToFile(String data, String filename) {
        try (
          FileWriter fw = new FileWriter(filename)) {
          fw.write(data);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    
    0 讨论(0)
  • 2020-11-22 04:31

    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();
         }
       }
    }
    
    0 讨论(0)
  • 2020-11-22 04:31

    My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

    As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

    public boolean writeStringToFile(File file, String string, Charset charset) {
        if (file == null) return false;
        if (string == null) return false;
        return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
    }
    
    public boolean writeBytesToFile(File file, byte[] data) {
        if (file == null) return false;
        if (data == null) return false;
        FileOutputStream fos;
        BufferedOutputStream bos;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(data, 0, data.length);
            bos.flush();
            bos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Logger.e("!!! IOException");
            return false;
        }
        return true;
    }
    
    0 讨论(0)
  • 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 ;
        }
    };
    
    0 讨论(0)
  • 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题