0

I am trying to write strings to a file but all the strings are being written to the file once the script is terminated.

To make my problem clear, in the below code I want to write a single string to my files per second and my file should be updated each second. Please help I am new to java.

import java.io.*;
public class Main
{
    public static void main(String[] args) throws IOException {
        String[] list = "Should write each word in each iteration".split("\\s");

        for(String word:list){
        Writer obj = new Writer();
        obj.func(word);
        try        
            {
                Thread.sleep(1000);
        } 
        catch(InterruptedException ex) 
            {
                Thread.currentThread().interrupt();
            }
        }
    }
}

class Writer{
    public void func(String word) throws IOException{
                FileWriter writer = new FileWriter("file" , true);
                writer.write(word);
                writer.close();
    }
}
DrDoggo
  • 149
  • 10
  • 2
    Your program works perfectly as intended. It's just that you have kept one-second interval and therefore you are not able to notice it. Change the interval to 5000 milliseconds and you will be able to notice it. – Arvind Kumar Avinash Dec 13 '20 at 20:03
  • Nooo. It is writing to a file all the strings I want but only once the program terminates. What I want is to update the file in every iteration. – DrDoggo Dec 13 '20 at 20:07
  • 2
    Hritik - As I've already mentioned, it works as you intend. Do it this way: Remove the content of the file > Change the interval to 5000 milliseconds or even bigger > Run the program and open the file every couple of seconds to view its content. If you change the extension of the file to .txt, it will be easier for you to open it just by double click; otherwise depending on your computer's settings, your computer may ask to select an application to open the file with, every time you double-click it in order to open it. – Arvind Kumar Avinash Dec 13 '20 at 20:11
  • Yes!! thanks for the answer it was being updated each time in my notepad but my IDE file was not updating, it was only updating once the program was ending I wasted a whole day for nothing. – DrDoggo Dec 13 '20 at 20:37

0 Answers0