We help IT Professionals succeed at work.

java- how to write in file line by line

Ravi_Jaganathan
on
hi
 I don't now how to write in file line by line.
Comment
Watch Question

If it has no line breaks, your string is simply a single line.
If it has line breaks, it will automatically be written line by line.
Commented:
here it is;
		 try {
		        BufferedWriter out = new BufferedWriter(new FileWriter("d:/test.txt"));
		        out.write("line1\r\n");
		        out.write("line2\r\n");
		        out.close();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }

Open in new window

Commented:
or
//Stream to write file
FileOutputStream fout;		
 
try
{
    // Open an output stream
    fout = new FileOutputStream ("d:/test.txt");
 
    // Print a line of text
    PrintStream p = new PrintStream(fout);
    p.println ("line1");
    p.println ("line2");
 
    // Close our output stream
    fout.close();		
}
// Catches any error conditions
catch (IOException e)
{
	System.err.println ("Unable to write to file");
	System.exit(-1);
}

Open in new window


FileWriter out = new FileWriter("c:/file.txt");
out.write("helle"+"\n");
out.close();

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.