11

I am writing the data on the file and i am using ArrayList for it but my main problem is that how can i add the new line on the text file. Is it possible to do it.

In a such a way that when first data of ArrayList write on the text file than automatically in the new line next data of ArrayList should be write

 final String FILES = "/MY_FILE_FOLDER";

 String path= Environment.getExternalStorageDirectory().getPath()+FILES; // Folder path

 File folderFile = new File(path);
  if (!folderFile.exists()) {
    folderFile.mkdirs();
   }

 File myFile = new File(folderFile, fileName+".doc");
 myFile.createNewFile();

 FileOutputStream fOut = new FileOutputStream(myFile);
 OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

 for (int i = 0; i < getdata.size(); i++) {
    myOutWriter.append(getdata.get(i)); 
 }


 myOutWriter.close();
 fOut.close();
 Toast.makeText(getBaseContext(),
        "Done writing SD 'mysdfile.txt'",
        Toast.LENGTH_SHORT).show();
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
  • 1
    http://stackoverflow.com/questions/19084352/how-to-write-new-line-character-to-a-file-in-java – MOSO Nov 21 '14 at 06:50

4 Answers4

14

Change,

for (int i = 0; i < getdata.size(); i++) {
    myOutWriter.append(getdata.get(i)); 
}

to

for (int i = 0; i < getdata.size(); i++) {
    myOutWriter.append(getdata.get(i)); 
    myOutWriter.append("\n\r");
}

I Hope this helps!!

codePG
  • 1,754
  • 1
  • 12
  • 19
6

Try in this way,

FileOutputStream fOut = new FileOutputStream(myFile);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fOut));

  for (int i = 0; i < getdata.size(); i++) {
    bw.write(getdata.get(i));
    bw.newLine();
  }

bw.close();

fOut.close();
kiran boghra
  • 3,662
  • 2
  • 18
  • 23
3
for (int i = 0; i < getdata.size(); i++) {
    myOutWriter.append(getdata.get(i)); 
    myOutWriter.append("\n\r");
}
1

Following code will surely works for anyone..

FileOutputStream writer = new FileOutputStream(gpxfile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writer));
String str ="Apple,Fruit : Cabbage,Vegetable";

StringTokenizer strr = new StringTokenizer(str, ":");
        while (strr.hasMoreTokens()) {
            bw.write(strr.nextToken()+"\r\n");
        }
bw.flush();
writer.flush();
bw.close();
writer.close();