gpt4 book ai didi

java - 在java中用制表符或逗号替换管道分隔符

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

我必须将管道分隔的数据转换为制表符分隔或逗号分隔的格式。我在java中编写了以下方法:

public ArrayList<String> loadData(String path, String fileName){
File tempfile;
try {//Read File Line By Line
tempfile = new File(path+fileName);
FileInputStream fis = new FileInputStream(tempfile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int i = 0;
while ((strLine = br.readLine()) != null) {
strLine.replaceAll("\\|", ",");
cleanedData.add(strLine);
i++;
}
}
catch (IOException e) {
System.out.println("e for exception is:"+e);
e.printStackTrace();
}
return cleanedData;
}

问题是结果数据仍然是管道分隔的。谁能告诉我如何修复上面的代码,以便它返回制表符分隔或逗号分隔的数据?

最佳答案

因为 Java 中的字符串是不可变的。 replaceAll方法不进行就地替换。它返回一个新字符串,您必须重新分配它:

strLine = strLine.replaceAll("\\|", ",");   

关于java - 在java中用制表符或逗号替换管道分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18855816/

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