Reputation: 8648
I used the code below to write record into a File. The record can be written in the file, but is append in one Line, each time I call this method example:
Hello WorldHello WorldHello WorldHello World
How can I modify the code so the output look like below, so that when read the text I can use line.hasNextLine() to check?
Hello World
Hello World
Hello World
Hello World
// Create file
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//Close the output stream
out.close();
// Code I used to read record I am using | as a seperator name and id
String fileName = folderPath + "listCatalogue.txt";
String line = "";
Scanner scanner;
String name, id;
scanner = new Scanner(fileName);
System.out.println(scanner.hasNextLine());
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "|");
name = st.nextToken();
id = st.nextToken();
catalogues.add(new Catalogue(name, id));
}
Upvotes: 15
Views: 125253
Reputation: 1
.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n
Upvotes: -1
Reputation: 7116
out.write(c.toString());
out.newLine();
here is a simple solution, I hope it works
EDIT: I was using "\n" which was obviously not recommended approach, modified answer.
Upvotes: 18
Reputation: 8873
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
Upvotes: 8
Reputation: 5786
I'm not sure if I understood correctly, but is this what you mean?
out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...
Upvotes: 55