• Post Reply Bookmark Topic Watch Topic
  • New Topic

Newline using FileWriter class  RSS feed

 
Kamal Patel
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am using the FileWriter class method 'write' to write a new line to a file. For some reason, it does not like the standard \n as a parameter, as it treats it like a character instead of a new line.
My code is given below:
try{
File file = new File("c:\\directory\\password.txt");
FileWriter text = new FileWriter(file);
text.write("userid: "+userid);
text.write("\n");
text.write("pwd: "+pwd);
text.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
Does anyone know the answer to this one pls?
 
Jeff Langr
author
Ranch Hand
Posts: 799
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kamal Patel:
Hi,
I am using the FileWriter class method 'write' to write a new line to a file. For some reason, it does not like the standard \n as a parameter, as it treats it like a character instead of a new line.

Two things:
[list]Windows uses a \r\n combination (CR-LF), not just a linefeed. Use to determine the correct combination for your operating system (\n only is un*x).[/list]
  • Instead of a FileWriter, wrap the FileWriter in a BufferedWriter. Then call the BufferedWriter method newLine(), which uses the system line separator property.


  • -Jeff
     
    Jim Yingst
    Wanderer
    Sheriff
    Posts: 18671
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You can also use a PrintWriter, whose println() methods should look familiar, and are a bit more convenient in many cases. The BufferedWriter is a good idea for efficiency though, so you may end up with something like

    Often there will be an OutputStreamWriter as well so you can specify character encoding as well, but you can get into that later.
     
    Dirk Schreckmann
    Sheriff
    Posts: 7023
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Moving this to the I/O forum...
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!