我有一个Runnable线程,每5秒刷新一次。 这个线程想要写入以时间和日期命名的文件。
我检查文件是否存在,我想在现有文件上附加新更新,并在更改分钟时生成一个新文件,并每隔5秒对其执行相同的操作。
该应用程序基于JFrame申请表
Runnable helloRunnable = new Runnable(){
@override
public void run(){
try{
String FileName = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + Calendar.getInstance().get(Calendar.MINUTE) + ".txt";
File f = new File(FileName);
FileWriter filewriter = new FileWriter(FileName);
BufferedWriter bufferedWriter = new BufferedWriter(filewriter);
FileWriter filewriter2 = new FileWriter(f, true);
BufferedWriter = bufferedWriter2 = new BufferedWriter(filewriter2);
if (f.isFile() && !f.isDirectory()){
bufferedWriter2.write("Hello"); //this part doesn't append "Hello" in file (as i want) but overwrite the existing file
bufferedWriter2.close();
}else{
bufferedWriter.write("Hello"); //this part must overwrite the existing file so i think this work
bufferedWriter.close();
}
} catch (IOExcception ex){
Logger.getLogger(Gestionale.class.getName()).log(Level.SEVERE,nell,ex);
}
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
SchedulateFuture<?> ez = executor.scheduleFixedRate(helloRunnable,0,5,TimeUnit.SECONDS);
答案 0 :(得分:2)
您始终要实例化覆盖现有文件的FileWriter
。
FileWriter filewriter = new FileWriter(FileName);
在此行之后,文件将始终为空
您必须将FileWriter
对象的创建移动到if语句中。