Reputation: 624
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
Reputation: 3101
There is a missing assumption here.
\r\n
.\n
.\r
.System.getProperty("line.separator")
(or print the new line with a .println()
).Upvotes: 2
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
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