java - Linux 和 java : File is being created but text is not written

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

最佳答案

您需要关闭输出,或者更准确地说,您需要编写代码以便将其关闭(不一定明确关闭)。 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/

相关文章:

java - 使用 for 循环将多个 Jlabel 添加到 Jframe,删除它们并将它们打印在新位置

java - while 循环输出不完整

java - Spring Stomp over Websocket : Message/Buffer/Cache/Stream limits

linux - 使用 Bash 从文本文件创建用户

c++ boost asio异步编译错误

我可以从具有许多编译器标志的 c 程序中导出使用过的代码吗?

java - 为什么单线程使我的 Java 程序速度如此之快?

linux - 如何使用 sed 进行多行替换?

c - 如何从FILE中加载多个 "clones"结构? C

c - 使用 fseek() 更新二进制文件