2017-06-12 112 views
1

我正在编写一个简单的终端程序,记录一些信息,并将其放入一个文本文件中,稍后有人可以回忆。主要是为了记录他所做的事情。我在窗户上很好,并没有真正遇到这个问题,但我担心我正在寻找简单的东西。Linux和java:正在创建文件,但文本没有写入

就像我之前说的,如果我浏览到该项目目录,我看到文件已经创建,但是当我打开使用文本编辑器文件,打印没有创建的字符串中的数据。

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); 
    } 
} 
+0

无关你的问题,但变量'fileName'是一种严重命名。它是实际的'File'对象,而不是文件*名称*。 –

+0

哈哈很好,谢谢! – user3026473

+0

是否因为您需要关闭BufferedWriter和FileOutputStream以确保所有内容都写入文件? –

回答

0

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

所以,你的新代码应该是这样的:

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

} 
+1

在'close'完全没有必要之前调用'flush','flush'应该只有当我们想写某些东西时才会使用,但我们仍然希望让文件处理,以便稍后写入它(例如套接字编程) – niceman

+0

以关闭封装流,然后关闭底层流,再次不需要(所以'write.close'已经足够了,不需要'fos.close()') – niceman

+0

我不好,我会编辑我的答案以省略flush()。 – AMFTech

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()