Reputation: 2214
I am working on java Application where I am dealing with read and
write file. But I want to do this process simultaneously. As my file
is log file from which I am reading contents by some time interval for
this I used java.util.Timer
. And during this time interval I am trying
to writing some contents in the file, but this is not updating in my
log file.
My Timer class is
public class Timer extends java.util.Timer {
public void startTimer() {
Timer t = new Timer();
Task task = new Task();
t.schedule(task, 0, 10000);
}
}
My class form which file read write class is called
public class Task extends TimerTask {
@Override
public void run() {
System.out.println("In task ....");
try {
SMSQuestions smsQuestions = new SMSQuestions();
smsQuestions.sendSMSAnswer();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
My file read write class is
public void sendSMSAnswer()
{
long sender;
String question;
try {
BufferedReader br = new BufferedReader(new FileReader("C:/temp/NowSMS/TEST.log"));
String line = br.readLine();
while (line != null) {
sender = 0;
question = "";
System.out.println(line);
line = br.readLine();
}
//To delete all contents in file
BufferedWriter bw = new BufferedWriter(new FileWriter("C:/temp/NowSMS/TEST.log"));
bw.write("");
getDetails();
}catch(Exception exp)
{
exp.printStackTrace();
}
}
My problem is when i updated my log file by writing new contents it can't be updated so my question is: is it possible in java to simultaneously read write file or not?
Upvotes: 2
Views: 2968
Reputation: 45
I have two things to say about your code. First: I think that you are missing the finally block where you are supposed to close br and bw. Try: finally {
br.close();
bw.close();
} after the catch block.
Second: It is not a good idea to write content to a file while it is opened. I mean, if you open a file with br maybe it is better to gives another file path to bw
Upvotes: 0
Reputation: 5082
I would suggest you have a look at random access files (see http://docs.oracle.com/javase/tutorial/essential/io/rafs.html). This API is a little more complicated to work with since you'll be reading bytes, not lines, but it should give you what you need.
If you don't want to deal with NIO you can use http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html instead.
Upvotes: 2
Reputation: 12943
Try this topic. But the only answer you will get is, its only working with a few OSs.
Upvotes: 0