1

i can't have newline in my text file with this code, what it's wrong with that?

try{
    oprint=new FileWriter("HighScores.txt",true);
} catch (IOException e1) {
    System.out.println("error");
}  
try{
    String stampa= "Player:  "+name+"  --- time "+ this.getDurata()+" s \n";
    oprint.write(stampa);
    oprint.close();
}catch(Exception e){
    System.out.println("error");
}
4
  • Well you definitely do have a line feed... are you saying you want one, or you don't? Commented Jun 25, 2012 at 11:37
  • 1
    Maybe you opened your file with an editor which expects to have a carriage return and linefeed (\r\n). Commented Jun 25, 2012 at 11:38
  • Note: Consider to use Automatic Resource Management if you're using Java SE 7. Commented Jun 25, 2012 at 11:41
  • 1
    What platform are you developing for? Try using %n instead of \n. Commented Jun 25, 2012 at 12:14

3 Answers 3

3

Try using this:

public static String newline = System.getProperty("line.separator");

and then:

oprint.write("Player:  " + "x" + "  --- time " + "durata" + " s " + newline);

This is better as different OS's have different ways of writing new lines. Linux uses "\n", Mac uses "\r", and Windows uses "\r\n" for newline.

Sign up to request clarification or add additional context in comments.

4 Comments

There is actually a newLine method in Writer, but the sensible approach is to utilise a PrintWriter or a PrintStream. Then you'll have println to take care of this.
f*** i'm using the basic txt editor of windows. if i use wordpad newlines appear. thx to everybody
Just a side-note but if he produces a file on a different platform than where he tries to read it, then it's a better ide to explicit write out the correct line separator, not the system preferred.
@ftom2 Windows uses \r\n, not Linux
0

Try maybe to wrap FileWriter in PrintWriter and use its println() method.

PrintWriter oprint;
try{
    oprint=new PrintWriter(new FileWriter("HighScores.txt",true));
    String stampa= "Player:  "+name+"  --- time "+ this.getDurata()+" s";
    oprint.println(stampa);//<- print with new line sign
    oprint.close();
}catch(Exception e){
    System.out.println("error");
}

Comments

0

Are you sure that your editor or viewer does not expect to have a carriage return (CR) at the end of the lines?

If so try with the following:

String stampa = "Player:  "+name+"  --- time "+ this.getDurata()+" s \r\n";

Or you could use the String.format:

String stampa = String.format("Player: %s  --- time %d s %n", name, this.getDurata());

From the format documentation:

'n' line separator The result is the platform-specific line separator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.