FileWriter is not writing in to a file

后端 未结 5 1000
谎友^
谎友^ 2021-01-15 09:04

I have below code

    try
    {
        FileWriter fileWriter = new FileWriter(\"C:\\\\temp\\\\test.txt\");
        fileWriter.write(\"Hi this is sasi This t         


        
相关标签:
5条回答
  • 2021-01-15 09:16

    Closing was missing. Hence not the last buffered data was not written to disk.

    Closing also happens with try-with-resources. Even when an exception would be thrown. Also a flush before close is not needed, as a close flushes all buffered data to file.

    try (FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt"))
    {
        fileWriter.write("Hi this is sasi This test writing");
        fileWriter.append("test");
    }
    catch (IOException ioException)
    {
        ioException.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-15 09:21

    You must close the FileWriter, otherwise it won't flush the current buffer. You can call the flush method directly..

    fileWriter.flush()
    fileWriter.close()
    

    You don't need to use the flush method if you are closing the file. The flush can be used for example if your program runs for a while and outputs something in a file and you want to check it elsewhere.

    0 讨论(0)
  • 2021-01-15 09:21

    Try this:

    import java.io.*;
    
    public class Hey
    
    {
        public static void main(String ar[])throws IOException
        {
    
                File file = new File("c://temp//Hello1.txt");
                // creates the file
                file.createNewFile();
                // creates a FileWriter Object
                FileWriter writer = new FileWriter(file); 
                // Writes the content to the file
                writer.write("This\n is\n an\n example\n"); 
                writer.flush();
                writer.close();
        }
    }
    
    0 讨论(0)
  • 2021-01-15 09:27

    You need to close the filewriter else the current buffer will not flush and will not allow you to write to the file.

    fileWriter.flush(); //just makes sure that any buffered data is written to disk
    fileWriter.close(); //flushes the data and indicates that there isn't any more data.
    

    From the Javadoc

    Close the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.

    0 讨论(0)
  • 2021-01-15 09:37

    Please try this :

      try
        {
            FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt");
            fileWriter.write("Hi this is sasi This test writing");
            fileWriter.append("test");
            fileWriter.flush(); // empty buffer in the file
            fileWriter.close(); // close the file to allow opening by others applications
        }
        catch(IOException ioException)
        {
            ioException.printStackTrace();
        }
    
    0 讨论(0)
提交回复
热议问题