• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Arraylist writing to a file with new Lines in it

 
Ranch Hand
Posts: 230
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Using the code below :-



import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;


public class WriteFile {
public static void main(String [] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("msjksl");
al.add("rakesh");
al.add("mnopq");
al.add("kmjdc");
al.add("ramesh");
al.add("rajesh");
al.add("hello");


FileWriter fw= null;
File file =null;
try {
file=new File("C:/Users/nayasant/Desktop/WriteFile.txt");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);

Iterator<String> iterator = al.iterator();
while (iterator.hasNext()){
fw.write(iterator.next());
}
fw.close();
System.out.println("File written Succesfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}


I want to achive as the WriteFile.txt should have entries with new lines:

Output should be :-
msjksl
rakesh
mnopq
kmjdc
ramesh
rajesh
hello


How to achive the same ?


 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Santosh Kumar Nayak wrote:
I want to achive as the WriteFile.txt should have entries with new lines:

How to achive the same ?



The easiest way to accomplish it is to write the newlines too. Or you can use a PrintWriter instead.

Henry
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you never tried a Formatter for a text file? The one problem I have had with Formatters is that I have never managed to get them to append to a file, which you can do quite simply with a Writer.
 
Santosh Kumar Nayak
Ranch Hand
Posts: 230
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry.
reply
    Bookmark Topic Watch Topic
  • New Topic