我正在尝试制作一个为学生评分的程序。
首先它应该询问学生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/