我尝试使用java读取和写入文件。我已经尝试了我的代码,但它无法正常工作。
见下面是我的代码:
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();
}
}
}
它提供以下输出:
New Entry ::::
System=13042.827175
New System Time is :13042.827175
String Written
输出正确,但问题是当我打开" UptimeRecord.txt"文件,文件为空。我无法写入该文件。
答案 0 :(得分:3)
您需要.flush()
和.close()
FileWriter
。当flush FileWriter
时,数据被发送到其目的地。您还可以考虑使用BufferedFileWriter
来处理冲洗和关闭。
另请参阅:difference between flush and close function in case of filewriter in java
答案 1 :(得分:2)
您需要关闭FileWriter
fileWriter.close();
根据JoeBlade的建议,这应该在finally块中完成:
} catch (IOException e){
e.printStackTrace();
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
答案 2 :(得分:1)
文件必须关闭file.close()
fileWriter.close();