我正在编写一个简单的终端程序,用于记录一些信息,并将其放入一个文本文件中,供以后调用。主要是为了记录他的人所做的事情。我在 Windows 中一直很好,并没有真正遇到这个问题,但我担心我正在寻找一些简单的东西。
就像我之前说的,如果我导航到项目目录,我会看到文件已经创建,但是当我用文本编辑器打开文件时,创建的字符串中的任何数据都没有被打印出来。
private static void writeFile( String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{
File fileName = new File("log.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));
int i =0;
write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n");
i++;
System.out.println("File has been updated!");
} catch (FileNotFoundException ex) {
Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
您需要关闭输出,或者更准确地说,您需要编写代码以便将其关闭(不一定明确关闭)。 Java 7 引入了 try with resources巧妙地处理这种情况的语法。
任何 AutoCloseable
的对象都可以使用此语法自动安全地关闭,如下所示:
private static void writeFile( String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{
File fileName = new File("log.txt");
try (FileOutputStream fos = = new FileOutputStream(fileName);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));) {
int i =0;
write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n");
i++;
System.out.println("File has been updated!");
} catch (FileNotFoundException ex) {
Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
只需将可关闭对象的初始化移动到 try
资源 block 中即可确保它们已关闭,这将在关闭后 flush()
它们。
关于java - Linux 和 java : File is being created but text is not written,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44508910/