5

I have to convert pipe delimited data into either tab delimited or comma delimited format. I wrote the following method in 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?

1 Answer 1

18

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:

strLine = strLine.replaceAll("\\|", ",");   
4
  • Good catch. I didn't see that at all.
    – joescii
    Sep 17, 2013 at 17:11
  • Still say the compiler needs to throw an error for calling a non-void method without assigning it's value to something, unless annotated.
    – Cruncher
    Sep 17, 2013 at 17:11
  • @RohitJain bingo. +1. But can you show how to replace it with tabs instead of commas also?
    – CodeMed
    Sep 17, 2013 at 17:12
  • @CodeMed use "\t" instead of ",".
    – Cruncher
    Sep 17, 2013 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.