6

I just started learning Java and I was interested in the File libraries. So I kept a notepad file open called filename.txt. Now I want to write to file using Java, but I want to get the result in real time.

I.e when the java code executes the changes should be visible in the text file without closing and reopening the file.

Here my code:

import java.io.*;
class Locker
{
    File check = new File("filename.txt");
    File rename = new File("filename.txt");
    public void checker()
    {
        try{
            FileWriter chk = new FileWriter("filename.txt");
            if(check.exists())
            {
                System.out.println("File Exists");
                chk.write("I have written Something in the file, hooray");
                chk.close();
            }
        }
            catch(Exception e)
            {
            }
        }

};
class start
{
    public static void main(String[] args) 
    {
        Locker l = new Locker();
        l.checker();
    }
}

Is it possible and if so can someone tell me how?

4

1 Answer 1

11

Simple answer: this doesn't depend on the Java side.

When your FileWriter is done writing, and gets closed, the content of that file in your file system has been updated. If that didn't happen for some reason, you some form of IOException should be thrown while running that code.

The question whether your editor that you use to look at the file realizes that the file has changed ... completely depends on your editor.

Some editors will ignore the changes, other editors will tell you "the file changed, do you want to reload it, or ignore the changes".

Meaning: the code you are showing does "synchronously" write that file, there is nothing to do on the "java side of things".

In other words: try using different editors, probably one intended for source code editing, like atom, slickedit, visual studio, ...

1
  • 5
    For instance Notepad++ detects when the opened file is changed on disk, and asks to reload. Linux has the tail tool that can continuously show the added lines to a file.
    – Joop Eggen
    Commented Jan 8, 2019 at 14:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.