How I can read the content from a text file line by line? When I try to output the content, the newline character seems to be ignored from reading.
public class ReadFile { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String str= ""; //Reading content from file Scanner in = new Scanner(new FileReader("text.txt")); while(in.hasNextLine()){ str = str + in.nextLine(); str.concat("\n"); //Not working!!!!!!!!!!! } in.close(); //Writing content to another file PrintWriter out = new PrintWriter(new FileWriter("output.txt")); out.println(str); out.close(); } }
Scanner.nextLinewill strip the linebreak.PrintWriter.printlnwill add it back. Where's the problem?Stringis immutable.String.concatis conventionally written as+- it's both shorter and more readable.str += "\n". "\n" is a UNIX linebreak - this won't work on Windows.\r\ninstead of only\n.