Purushottam
Purushottam

Reputation: 624

Printing a new line in a file, in Java

I aim to make an index of all files with a particular extension and store it into index.txt. I am getting all the right results but not getting the 'files' onto the new line, this is a snapshot of my code:

OutputStream f0 = new FileOutputStream("index.txt");
    String ind[] = f.list(only); // logic for getting only relevant files
        for(int i=0;i<ind.length;i++)
        {
            File n = new File(path + "/" +ind[i]);
                System.out.println(ind[i]+ " is a " +exten +" file");
                ind[i]+="\n";           // doesnt work      
                f0.write(ind[i].getBytes());    // here i am writing the filenames                              
        }           

is it due to the getBytes() function which overlooks the "/n" ? Please tell me what to do. I want to insert a new line everytime i exit the for loop.

One major edit: I am getting the desired result when I open the file with notepad++ or wordpad, but when i open the file with notepad i am getting the results on the same line. Please Explain this too!

Upvotes: 3

Views: 2229

Answers (5)

Unai Vivi
Unai Vivi

Reputation: 3101

There is a missing assumption here.

  1. If you assume that your text file should have MS Windows line separators (meant for Windows platforms), then you should use \r\n.
  2. If you assume that your text file should have Unix-like line separators (meant for GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), then you should use \n.
  3. If you assume that your text file should have Mac oldschool line separators (meant for Mac OS up to version 9, Apple II family, OS-9, etc.), then you should use \r.
  4. If you assume that your text file should have line separators of the kind of the platform your program is run from, then you should use System.getProperty("line.separator") (or print the new line with a .println()).

Upvotes: 2

Kushan
Kushan

Reputation: 10695

try this,

FileWriter.write("\r\n");

Upvotes: 1

creechy
creechy

Reputation: 405

Is there any reason you are working at such a low level of I/O in Java? First of all you should be using Writers instead of OutputStreams.

And then if you use PrintWriter you can do away with the getBytes piece:

PrintWriter f0 = new PrintWriter(new FileWriter("index.txt"));

And then later...

f0.print(ind[i]);

And finally to your question, outside the loop simply

f0.println();

Upvotes: 2

scarba05
scarba05

Reputation: 3001

Instead of using an FileOutputStream I'd use a PrintWriter.

PrintWriter out = new PrintWriter("index.txt");
String ind[] = f.list(only); // logic for getting only relevant files
for(int i=0;i<ind.length;i++)
{
    File n = new File(path + "/" +ind[i]);
    System.out.println(ind[i]+ " is a " +exten +" file");
    out.println(ind[i]);   
}

Upvotes: 2

Esselans
Esselans

Reputation: 1546

Try writing:

System.getProperty("line.separator") 

instead of \n

Upvotes: 5

Related Questions