【问题标题】:modify the file csv failed修改文件 csv 失败
【发布时间】:2017-12-12 06:48:53
【问题描述】:

我创建了包含修改 CSV 文件的服务。我为每一行的最后一列添加值,但在覆盖文件时发现了问题。如果新文件与旧文件具有不同的名称,则成功,但我想要具有相同名称的文件。如何解决这个问题?

public void modify() {
    BufferedReader br=null;
    BufferedWriter bw=null;

    try {
        File file = new File("C:\\Users\\c76266\\Documents\\bobby\\text\\sample2.csv");
        File newfile = new File("C:\\Users\\c76266\\Documents\\bobby\\text\\sample2_new.csv");

        br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile)));

        String line = null;
        String [] addedColumn = {"newstring1", "newstring2"};
        int i=0;

        while((line = br.readLine())!=null){
            String result = "\t"+addedColumn[i];
            bw.write(line+result+System.lineSeparator());
            i++;
        }
    } catch(Exception e){
        System.out.println(e);
    } finally  {
        try {
            br.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

在此代码中,由于文件和新文件的名称不同,因此运行良好。 sample2.csvsample2_new.csv 但我也想要新文件 sample2.csv 但失败了。当我打开一个文件时,空字符串。谢谢。

【问题讨论】:

  • 将文件内容保存到字符串中,然后将字符串写回sample2.csv
  • 您无法使用标准文件操作同时打开文件进行读取和写入 - 编程语言不是文本编辑器。一旦您打开它进行写入,它就会被截断。请改用临时文件。阅读基本文件操作。
  • 你没有发现任何异常吗?因为如果你有两行以上,你可能会得到 ArrayindexOutofBoundsexception

标签: java csv bufferedreader bufferedwriter


【解决方案1】:

用不同的名称保存修改后的文件,操作完成后用新的临时文件替换旧文件:

import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);

https://docs.oracle.com/javase/tutorial/essential/io/move.html

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多