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?
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, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With