1

Possible Duplicate:
Java: How do I get a platform independent new line character?

I want to write enter into file with class RandomFileAccess, but I can't do it properly.

What should I do ?

Like this code :

char enter = '\n' ;
outputfile.writeChar(enter);

I'm Using Windows.... Thanks for your help but it didn't work :(

public class MainClass {
    public static void main(String[] args) {
        String BeforEnter = "It's Before Enter...";
        String Enter = System.getProperty("line.separator");
        String AfterEnter = "It must be on next Line...";

        File MyFile = new File("test.txt");
        try {
            RandomAccessFile TextFile = new RandomAccessFile(MyFile, "rw");
            TextFile.writeChars(BeforEnter);
            TextFile.writeChars(Enter);
            TextFile.writeChars(AfterEnter);
            TextFile.close();

I expected this Style of File :

It's Before Enter...

It must be on next Line...

But it gets like this : :(

I t ' s B e f o r e E n t e r . . . I t m u s t b e o n n e x t L i n e . . .

Community
  • 1
  • 1
Amir Hossein
  • 249
  • 2
  • 4
  • 14
  • 1
    What do you mean by "press enter"? What do you want to achieve? If you just need a line break this should acctually work :-/ – André Stannek Oct 31 '12 at 15:18
  • 1
    `RandomFileAccess`?!? DYM [`RandomAccessFile`](http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html). Take more care to copy/paste in future. – Andrew Thompson Oct 31 '12 at 15:20
  • 1
    Also note if you do mean `RandomAccessFile`, you cannot simply 'insert new lines' wherever you like without risking overwriting the following characters. – Andrew Thompson Oct 31 '12 at 15:23

2 Answers2

3

Use System.getProperty("line.separator"); instead new line character.

As per javadoc

Sequence used by operating system to separate lines in text files

kosa
  • 65,990
  • 13
  • 130
  • 167
3

What operating system are you using? Better use this:

String enter = System.getProperty("line.separator");

Using the above snippet, you won't have to worry about the exact details of line breaks, because they change depending on the operating system currently in use.

For instance, in Windows is \r\n, in current Macs and Linux is \n and in older Macs is \r.

Óscar López
  • 232,561
  • 37
  • 312
  • 386