gpt4 book ai didi

java - 尝试替换CSV字符串中的/r/n以解决单元格中的换行符,而无需在.hasNextLine()之前使用API

转载 作者:行者123 更新时间:2023-12-01 06:05:20 28 4
gpt4 key购买 nike

我有一个CSV文件。在此文件中,有时它将在一个单元格中的不同行上包含多个项目。

我想使用replaceAll(“ / r / n”,“”);消除此问题。但是我不确定我该在代码中放哪?

    public static Scanner getFields(Scanner console) {
File f;
do {
System.out.print("Please give me the Fields: " );
String file = console.nextLine();
f = new File(file);
} while (!f.exists());
Scanner readMe = null;
try {
readMe = new Scanner(f);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
e.printStackTrace();
}
return readMe;
}

public static void readMe(Scanner fieldScan) {
int row = 0;
fieldScan = fieldScan.replaceAll("\r\n", " ");

while (fieldScan.hasNextLine()) {
row++;
String current = fieldScan.nextLine();
Field currentField = new Field(current, row);
if (!currentField.getRemove()) {
fieldArrayList.add(currentField);
}
}


我知道我不能将replaceAll与扫描仪一起使用,它必须与字符串一起使用-但是如果必须用新行将其分割-我什至应该怎么替换它?有没有其他方法可以设置while循环以使换行符不中断?

最佳答案

在读入CSV文件之前,我曾想过如何清理它,并遇到this SO线程,该线程涉及从Scanner对象读取到String变量。通过将扫描仪上的定界符设置为\\Z(即文件的末尾),则文件的全部内容将作为一个字符串读入。

因此,如果您在达到readMe方法之前对文件执行清理工作,则该方法应该起作用!请参阅以下有关我建议使用的方法:

public static void cleanseCsvFile(string FilePath) {
File csvFile = new File(FilePath);
String content = new Scanner(csvFile).useDelimiter("\\Z").next();
content = content.replaceAll("(\r\n){1}(?!$)"," ")

FileUtils.writeStringToFile(csvFile, content);
}


上面的方法在最后一行利用了Apache.Commons.IO库,因为这是将文本内容写回到同一文件的最简单方法。如果将此方法插入脚本并在 readMe方法之前调用它,则应该可以正常进行:)

关于java - 尝试替换CSV字符串中的/r/n以解决单元格中的换行符,而无需在.hasNextLine()之前使用API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46118831/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com