5

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

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

4

1 回答 1

18

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

strLine = strLine.replaceAll("\\|", ",");   
于 2013-09-17T17:08:47.217 回答