Android: How to write a new line in a CSV file?

I am trying to organize my data in a .CSV file. I want to put my data on a specific line, so I tried to put "\ n", but it does not work. Please help me put the data on a specific line. Thanks in advance.

public void writeData(String data,String strFilePath) { PrintWriter csvWriter; try { File file = new File(strFilePath); if(!file.exists()){ file = new File(strFilePath); } csvWriter = new PrintWriter(new FileWriter(file,true)); csvWriter.print(data+","+"hello"); csvWriter.append('\n'); csvWriter.print("world"); csvWriter.close(); } catch (Exception e) { e.printStackTrace(); } } 
+8
java android csv
source share
5 answers

You look good, and I'm sure the new line is correctly written in the file. The only reason I can think of is to open the file with an editor that does not treat \n as a line separator, it considers the \r\n pair as a line separator (for example, Notepad on Windows).

So, you can either write a new line using write.print("\r\n") , or simply open the file with some other editors, for example vim . No matter which editor you use to open the file, a newline appears.

+8
source share

CSV files are not as easy to create as they might seem. I ran into a lot of problems when trying to write a quick parser / CSV writer.

Just use OpenCSV and fix all your problems immediately.

Using OpenCSV, you can do something like this:

 CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t'); // feed in your array (or convert your data to an array) String[] entries = "first#second#third".split("#"); writer.writeNext(entries); 
+2
source share

Try using the following code (using StringBuffer ) - a thread-safe, mutable character sequence:

  public void writeData(String data, String strFilePath) { PrintWriter csvWriter; try { /*1. declare stringBuffer*/ StringBuffer oneLineStringBuffer = new StringBuffer(); File file = new File(strFilePath); if (!file.exists()) { file = new File(strFilePath); } csvWriter = new PrintWriter(new FileWriter(file, true)); /*2. append to stringBuffer*/ oneLineStringBuffer.append(data + "," + "hello"); oneLineStringBuffer.append("\n"); oneLineStringBuffer.append("world"); /*3. print to csvWriter*/ csvWriter.print(oneLineStringBuffer); csvWriter.close(); } catch (Exception e) { e.printStackTrace(); } } 
+1
source share
  • try to clear the stream before closing it. csvWriter.flush()
  • use print instead, try println
+1
source share

You just need to change csvWriter.print("world"); at csvWriter.println("world"); . The next output will be in the next new line.

 public void writeData(String data,String strFilePath) { PrintWriter csvWriter; try { File file = new File(strFilePath); if(!file.exists()){ file = new File(strFilePath); } csvWriter = new PrintWriter(new FileWriter(file,true)); csvWriter.println(data+","+"hello"); csvWriter.print("world"); csvWriter.close(); } catch (Exception e) { e.printStackTrace(); } } 
+1
source share

All Articles