【发布时间】:2017-03-23 21:13:22
【问题描述】:
到目前为止,我的代码仅在单词被回车分隔时才编辑它们。如果我通过空格或逗号分隔单词,它们不会被替换。
例如如果我在一行上有“嘿”,在下一行有“嗨”。如果我愿意,我的代码可以同时替换它们。但是,如果我在一行中有“hey”,并且“hi”在“hey”旁边用逗号分隔,我的代码也不会替换。
我的代码的目标是替换 .CSV 文件中的单词,但如果我的代码无法替换以逗号或空格分隔的单词,那么它就不起作用。
这是我的代码,只需按一下按钮即可激活:
try{
// Input the file location into Path variable 'p'
Path p = Paths.get("test test.txt");
//Path p = Paths.get("tiger.csv");
//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();
}
如何编辑以逗号或空格分隔的单词?另外,如果我可以替换单词,无论它们是大写还是小写,那会很整洁,我该如何执行?
谢谢。
【问题讨论】:
-
看来您只是将 /entire lines/ 与已知字符串进行匹配,而您说您正在尝试替换单个单词。当然,您必须查看该行并挑选出单词来替换单个单词。考虑使用
Scanner类或 CSV 解析器,而不是自己进行字符串操作... -
当我使用
Scanner时,它无法转换为“路径”。List<String> fileContent = new ArrayList<>(Files.readAllLines(s));而“s”是Scanner s = new Scanner("test test.txt");。我是否打算以不同的方式使用 Scanner 来读取整个文件? -
扫描仪功能取代了
Files.readAllLines(),Scanner进行读取。见docs.oracle.com/javase/7/docs/api/java/util/Scanner.html -
看来我必须为这个
Scanner函数重新编写我的代码。感谢您的帮助。
标签: java csv arraylist replace