0

I am writing in a file and I want it to output into a csv file this way:

Group  Members  
 1     Name1  
       Name2  
       Name3  

code:

FileWriter fw = new FileWriter(csv);
BufferedWriter pw = new BufferedWriter(fw);
pw.write("Group,");
pw.write("Members");
pw.newline();
String mem=some_method();
pw.write("1,");
pw.write(mem);
pw.newLine();

My String mem has '\n' every after the names and so when it writes in the file, '\n' is read then writes into the next line. How can i achieve the above output without modifying the some_method()?

3 Answers3

0

Try as below,

String mem=some_method();
mem = mem.replace("\n", "");

Instead of \n you can also use System.getProperty("line.separator") which gives you platform independent line separator.

mem = mem.replace(System.getProperty("line.separator"), "");
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
0

You want to strip the new line characters in mem.

Check out Remove end of line characters from Java string

Put simply you can add the line mem = mem.replaceAll("(\\r|\\n)", "");

Community
  • 1
  • 1
Lionel Port
  • 3,492
  • 23
  • 26
  • If i'll remove them, then the names would not display in next lines within the cell. – user2431248 May 31 '13 at 01:56
  • If you want to keep the new line characters but have it appear as one cell then you just have to enclose the element in double quotes ("). e.g. pw.write("\"" + mem + "\""); – Lionel Port May 31 '13 at 02:05
  • Just bear in mind you need to make sure that mem doesn't contain double quotes or they are at least escaped. e.g. mem = mem.replaceAll("\"", "\\\""); – Lionel Port May 31 '13 at 02:07
  • this works, pw.write("\"" + mem + "\""); thanks. – user2431248 May 31 '13 at 02:20
-1

Why dont you combine the Group and Member together in one write method like:

pw.write("Group \t\t Members");

and do the same with the other contents. Hope this helps.

otep
  • 49
  • 2