在java中用制表符或逗号替换管道分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18855816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replacing pipe delimiter with tab or comma in java
提问by CodeMed
I have to convert pipe delimited data into either tab delimited or comma delimited format. I wrote the following method in java:
我必须将管道分隔的数据转换为制表符分隔或逗号分隔的格式。我在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;
}
The problem is that the resulting data is still pipe delimited. Can anyone show me how to fix the code above, so that it returns either tab delimited or comma delimited data?
问题是结果数据仍然是管道分隔的。谁能告诉我如何修复上面的代码,以便它返回制表符分隔或逗号分隔的数据?
采纳答案by Rohit Jain
Since Strings in Java are immutable. The replaceAll
method doesn't do in-place replacement. It returns a new string, which you have to re-assign back:
因为 Java 中的字符串是不可变的。该replaceAll
方法不进行就地替换。它返回一个新字符串,您必须重新分配它:
strLine = strLine.replaceAll("\|", ",");