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

时间:2013-09-17 17:07:33

标签: java regex pipe delimiter

我必须将管道分隔数据转换为制表符分隔或逗号分隔格式。我在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;
}

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

1 个答案:

答案 0 :(得分:13)

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

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