【发布时间】:2016-11-09 06:03:31
【问题描述】:
我的猜测是,我编写的代码不适用于 .CSV 文件,而只能用于 .txt。
我的代码的目的是从 field1 获取用户输入,并检查我的 .CSV 文件以查看文件中是否存在用户输入的实例。如果有,则将其替换为来自 field2 的用户输入。
这适用于我的 .txt 文件,但不适用于我的 .CSV 文件。
这是按下按钮(保存按钮)激活的代码:
try{
// Input the file location into Path variable 'p'
//Cannot write to CSV files
//Path p = Paths.get("C:\\Users\\myname\\Documents\\Stock Take Program\\tiger.csv");
Path p = Paths.get("C:\\Users\\myname\\Desktop\\test.txt");
//Read the whole file to a ArrayList
List<String> fileContent = new ArrayList<>(Files.readAllLines(p));
//Converting user input from editSerialField to a string
String strSerial = editSerialField.getText();
//Converting user input from editLocationField to a string
String strLocation = editLocationField.getText();
//This structure looks for a duplicate in the text file, if so, replaces it with the user input from editLocationField.
for (int i = 0; i < fileContent.size(); i++)
{
if (fileContent.get(i).equals(strSerial))
{
fileContent.set(i, strLocation);
}
break;
}
// write the new String with the replaced line OVER the same file
Files.write(p, fileContent);
}catch(IOException e)
{
e.printStackTrace();
}
我的问题是,如何更新我的代码以使用用户输入更新和替换 .CSV 文件的内容,就像它适用于我的 .txt 文件一样。
写入文本文件时,仅替换第一行,但写入 .CSV 文件时,不替换任何内容。
我是否应该以不同的方式编写代码来替换 .CSV 文件中的文本。
非常感谢任何帮助,谢谢。
【问题讨论】:
-
如果 csv 文件位于路径中没有空格的位置会怎样?
-
这没什么区别。
-
我对你的问题感到困惑,正如标题所说的
as the file cannot be found -
它在错误输出中说,由于某种原因无法找到 .csv 文件。但最重要的是,我怀疑这是因为我无法使用我的代码读取/写入 .csv 文件。
-
显示错误堆栈跟踪
标签: java file csv arraylist path