【问题标题】:Writing to a CSV file, can't write to first line写入 CSV 文件,无法写入第一行
【发布时间】:2019-11-21 16:18:39
【问题描述】:
try{
      Writer rwrite = new BufferedWriter(new FileWriter(file, true));
      rwrite.append(reservation.toString() + "\n");
      rwrite.close();
    }
    catch(IOException e){
      System.out.println("Could not open BufferedWriter.");
      e.printStackTrace();
    }

我的意思是基本上我的问题是我无法写入空 csv 文件的第一行。我可以写第二个就好了。也就是说,如果我自己手动输入了第一行,我可以写入第二行。

任何帮助感谢人们,真的,干杯。我被难住了。

更新:

try{

     File file = new File("reservations.csv");
     Scanner fileIn = new Scanner(file);

    try {
        if(fileIn.hasNext()){
        PrintWriter printWriter = new PrintWriter(new FileWriter("reservations.csv", true));
        printWriter.write(reservation.toString() + "\n");
        printWriter.close();
        }

        if(!fileIn.hasNext()){


            PrintWriter printWriter = new PrintWriter(new FileWriter("reservations.csv"));
            printWriter.write(reservation.toString() + "\n");
            printWriter.close();
        } 
        } catch (IOException e) {
            System.out.println("Could not open BufferedWriter.");
            e.printStackTrace();
        }


    }
    catch(IOException e){
     System.out.println("Error: failed to read from: " + "reservations.csv");
     e.printStackTrace();
    }

我把我的代码改成了这个,这行得通,但对我来说看起来有点怪异,哈哈。无论如何感谢您的帮助,并且仍然会阅读。

【问题讨论】:

  • 尝试新的 FileWriter(file)
  • 但是我不需要那个 true 来追加吗?我会试试的,谢谢。
  • 这将打印到第一行,但其他所有内容都会覆盖第一行。到达那里。
  • 您的代码在我的机器上运行正常。你遇到了什么错误?
  • 您应该尝试发布minimal reproducible example。在您发布的代码中,reservation 是什么?

标签: java csv bufferedwriter


【解决方案1】:

试试这个:-

try (PrintWriter printWriter = new PrintWriter(new FileWriter(file, true))) {
            printWriter.write(reservation.toString());
        } catch (IOException e) {
            logger.error("Error encountered whilst writing the file. Error : ", e);  e.printStackTrace();
        }

【讨论】:

  • 没有第二行。快把我逼疯了哈哈。无论如何,谢谢哥们。
  • hmm,但是,相同的代码写入 csv 的每一行,我在我的应用程序中广泛使用它。那么可能是其他问题
猜你喜欢
  • 2020-02-29
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 2023-01-30
  • 2015-05-15
  • 2018-03-26
  • 2021-05-07
  • 2021-09-24
相关资源
最近更新 更多