java - CSV 文件无法更新

标签 java arrays string csv bufferedreader

我正在尝试制作一个为学生评分的程序。

首先它应该询问学生ID,然后你需要给同一个学生的每个标准打分。

在我给出分数后,此代码不会改变任何内容。

BufferedReader br = new BufferedReader(new FileReader("project.csv"));
while ((line = br.readLine()) != null) {
    String[] cols = line.split(",");
    System.out.println("Please choose a criteria (2-7) ?");
    int subjectToGiveMark = in .nextInt(); // for creativity is 2
    System.out.println("Please enter a mark :");
    int mark = in .nextInt(); // which mark should be given 
    final int size = cols.length;
    String[] finalResult = new String[size];
    int index = 0;

    while (index < finalResult.length) {
        if (index == subjectToGiveMark) {
            finalResult[index] = mark + "";
        } else {
            finalResult[index] = cols[index];
        }
        index++;
    }
}

谁能告诉我这是怎么回事? enter image description here

最佳答案

首先,为了安全起见,您应该使用 try with resources 来读取和/或写入文件,因为您可能会忘记关闭文件,甚至异常也会阻止您这样做。

The try-with-resources statement ensures that each resource is closed at the end of the statement.

- The Java™ Tutorials

更多信息:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

如何?例如,在您正在阅读的内容中,只需尝试将其换行即可:

try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
  // The while code here...
}

此外,您正在修改 finalResult 变量,但没有对其执行任何操作,因此您的更改仅存储在那里,仅此而已,这就是您看不到更改的原因!

您应该在 while 循环之外创建一个变量,存储所有行,就像列表一样。否则,您可以打开另一个文件(例如:project-output.csv)并在读取另一个文件时写入它。

// Same principle as reading
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
  // Write the result
}

这个答案更详细地解决了写作的主题:https://stackoverflow.com/a/2885224/1842548

读写示例,我假设是 Java 8:

try (BufferedWriter writer = new BufferedWriter(new FileWriter("project-output.csv"))) {
  try (BufferedReader reader = new BufferedReader(new FileReader("project.csv"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        String[] cols = line.split(",");
        System.out.println("Please choose a criteria (2-7): ");
        final int subjectToGiveMark = in.nextInt(); // for creativity is 2
        System.out.println("Please enter a mark: ");
        final int mark = in.nextInt(); // which mark should be given
        cols[subjectToGiveMark] = Integer.toString(mark);
        // Here is where you write the output:
        writer.write(String.join(",", cols));
        writer.newLine();
    }
    writer.flush();
  }
}

您可以在 repl.it https://repl.it/repls/ScaredSeriousCookie 上看到一个工作示例

关于java - CSV 文件无法更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61445355/

相关文章:

java - JOOQ - 未应用内联转换器

Java 为 Integer 参数调用 String.valueOf(char[] data) 而不是 String.valueOf(int i) 并抛出 ClassCastException

java - 在java中获取数组json中的数组值

java - 同时比较二维数组的层

java - 与具有相同字符或字母的字符串进行比较

string - 如何将工期字符串格式化为天-小时-分钟的字符串?

java - Grails 一对多关系

c# - 泛型类型的术语

java - jboss 服务器中的 Spring Boot War 未加载静态内容

javascript - 如何按对象属性对数组进行分组