【问题标题】:Add data to specific record in CSV file将数据添加到 CSV 文件中的特定记录
【发布时间】:2021-05-07 19:05:15
【问题描述】:

我在 CSV 文件中有一条记录,我正在尝试使用以下代码将一些额外信息(名称)添加到相同的特定记录中,但它不起作用。没有显示错误,但我试图添加的信息没有出现。我错过了什么?

public class AddName {
public static void main(String[] args) {

    String filepath="Zoo.csv";
    String editTerm="Fish";
    String addedName="Ron";

    addToRecord(filepath,editTerm,addedName);

}
public static void addToRecord(String filepath,String editTerm,String addedName){

    String animal= "";

    try{
        FileWriter fw=new FileWriter(filepath,true);
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter pw=new PrintWriter(bw);
            if (animal.equals(editTerm)){
                pw.println(editTerm+","+addedName);
                pw.flush();
                pw.close();
            }
        System.out.println("Your Record was saved");
    }
    catch(Exception e){
        System.out.println("Your Record was not saved");
        e.printStackTrace();
    }
}

【问题讨论】:

  • 特定记录或特定行、列?
  • 我需要将名称添加到第二列的特定记录中,如下所示: |动物1 |名称1 | - 记录 1
  • 我认为您甚至没有阅读输入的 CSV 文件,是吗?局部变量“animal”总是一个空字符串,大概你想先逐行读取文件,如果该行符合预期,在再次写入之前修改它?
  • 对我应该如何更改代码以实现这一目标有任何建议吗?

标签: java csv file record


【解决方案1】:

您可以考虑使用 CSV 库来帮助您解析 CSV,因为它比看起来更复杂,尤其是在引用时。

下面是一个使用OpenCSV 的快速示例,它克隆原始 CSV 文件并根据需要添加“Ron”:

public class Csv1 {
    public static void main(String[] args) throws IOException, CsvValidationException {
        addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
    }

    public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
            throws IOException, CsvValidationException {

        try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
            try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {

                String[] values;
                while ((values = reader.readNext()) != null) {
                    if (values.length > 2 && values[0].equals(editTerm)) {
                        values[1] = addedName;
                    }
                    writer.writeNext(values);
                }
            }
        }
    }
}

给定文件:

type,name,age
fish,,10
cat,,12
lion,tony,10

将产生:

"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"

(您可以在生成的 CSV 中查找有关输出引号的答案)

【讨论】:

    【解决方案2】:

    这里的要求是如果动物名称匹配,则添加一个额外的列。这相当于更改文件中的特定行。这是实现相同目的的简单方法,(不使用任何额外的库),

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    
    public class EditLineInFile {
    
        public static void main(String[] args) {
    
            String animal = "Fish";
    
            Path path = Paths.get("C:\\Zoo.csv");
            try {
                List<String> allLines = Files.readAllLines(path);
                int counter = 0;
                for (String line : allLines) {
                    if (line.equals(animal)) {
                        line += ",Ron";
                        allLines.set(counter, line);
                    }
                    counter++;
                }
                Files.write(path, allLines);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用此代码将文件内容“Fish”替换为“Fish, Ron”

      public static void addToRecord(String filepath, String editTerm, String addedName) {
      
          try (Stream<String> input = Files.lines(Paths.get(filepath));
               PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
          {
              input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
                      .forEachOrdered(output::println);
      
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-06
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多