kavi kavi - 5 months ago 21
Java Question

I couldn't write a string in a txt

I try to read and write a file using java. I have tried my code, but it's not work properly.

See below is my code:

import java.util.*;
import java.io.*;

public class UptimeSample {


public static void main(String[] args) {
try
{
double oldTime=0;
BufferedReader read=new BufferedReader(new FileReader("C:/eGurkha/agent/sample/UptimeRecord.txt"));
String oldline=read.readLine();
if(oldline == null)
{
System.out.println("New Entry ::::");
Process p=Runtime.getRuntime().exec("C:\\eGurkha\\lib\\vmgfiles\\win\\VmgUptimeTest.exe");
BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=rd.readLine();
System.out.println(line);
String[] word=line.split("=");
FileWriter fileWriter=new FileWriter("C:/eGurkha/agent/sample/UptimeRecord.txt");
fileWriter.write(word[1]);
System.out.println("New System Time is :"+word[1]);
System.out.println("String Written");
}
else
{
oldTime=Double.parseDouble(oldline);
Process p=Runtime.getRuntime().exec("C:\\eGurkha\\lib\\vmgfiles\\win\\VmgUptimeTest.exe");
BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=rd.readLine();
String[] word=line.split("=");
FileWriter fileWriter=new FileWriter("C:/eGurkha/agent/sample/UptimeRecord.txt");
fileWriter.write(word[1]);
System.out.println("New System Time is :"+word[1]);
System.out.println("String Written");
double crrTime=Double.parseDouble(word[1]);
double diffTime=crrTime-oldTime;
System.out.println("Difference Time is :"+diffTime);
}
}
catch(IOException e)
{
e.printStackTrace();
}

}

}


It gives the following Output:

New Entry ::::
System=13042.827175
New System Time is :13042.827175
String Written


The output is correct, but the problem is when I open the "UptimeRecord.txt" file, the file is empty. I couldn't write in that file.

Answer

You need to close your FileWriter

fileWriter.close();

As Suggested by JoeBlade, this should be done in a finally block :

} catch (IOException e){
    e.printStackTrace();
} finally {
    if (fileWriter != null) {
        fileWriter.close();
    }
}