Linux和java:正在创建文件,但未写入文本

时间:2017-06-12 21:21:17

标签: java linux file

我正在编写一个简单的终端程序来记录一些信息,并将其放入一个人们以后可以回忆的文本文件中。主要是为了记录他所做的事情。我在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);
     }
}

2 个答案:

答案 0 :(得分:1)

您需要关闭输出,或者更准确地说,您需要编码以使其关闭(不一定明确地关闭它)。 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资源块中,就可以确保它们已关闭,因为关闭它们会flush()

答案 1 :(得分:0)

write()类调用BufferedWriter函数后,您需要调用close()函数。您还应该在close()对象上调用FileOutputStream函数。

所以你的新代码应如下所示:

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");

     // Close your Writer
     write.close();

     // Close your OutputStream
     fos.close();

     i++;
     System.out.println("File has been updated!");
 } catch (FileNotFoundException ex) {
     Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
 }

}