gpt4 book ai didi

Java程序在所有行中添加双引号

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:24 26 4
gpt4 key购买 nike

我正在编写一个简单的程序,它采用 csv 文件并生成带有新列的 csv。我的问题是:程序引用旧列和所有列。下面是我的代码

public class CSVmodifier {

public static void modify(String Path,String Escape) throws IOException {
int i=0;
String filename = new File(Path).getName().toString();
//setName(string) modify the original filename
String fileoutname = setName(filename);
File file= new File(fileoutname);
try {
FileWriter out = new FileWriter(file);
Reader reader =
Files.newBufferedReader(Paths.get(Path));
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(out);
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
int dimension = nextRecord.length;
String[] newline = new String[dimension+1];
int y = 0;
//formatNumber create a string number with 9
//zero in the front-> 1 > "000000001"
newline[0]=formatNumber(i+1);
while(y<dimension) {
newline[y+1] = nextRecord[y];
y++;
}
i+=1;
csvWriter.writeNext(newline);
}
csvWriter.close();


} finally {


}
}

public static String formatNumber(int i) {
String formatted = String.format("%09d", i);
return formatted;
}


}

我的样本是:

"John","Doe","120 jefferson st.","Riverside", "NJ", "08075"

错误的输出是:

"000000001","""John""",""Doe"",""120 jefferson st."",""Riverside"", ""NJ"", ""08075"""

我无法上传该文件,但我将向您展示一个出现相同问题的示例文件(输入行):

'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; 
'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale elemetare';'Ola!'

有输出行:

'000000001';"'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; "
'000000002';"'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale'; "

最佳答案

我假设您的 CSVWriter 类是 com.opencsv.CSVWriter
您正在使用csvWriter.writeNext(String[]) ,这是 writeNext(nextLine, true); ( JavaDoc ) 的快捷方式。
第二个参数(在本例中始终为 true)是 applyQuotesToAll:

True if all values are to be quoted. False applies quotes only to values which contain the separator, escape, quote, or new line characters.

所以您需要做的就是更改这一行:

csvWriter.writeNext(newline)

对此:

csvWriter.writeNext(newline, false);

关于Java程序在所有行中添加双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56931855/

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