Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

showtime

macrumors 6502
Original poster
May 10, 2007
291
1
How can I get a scanner object to get new line characters as well?

The text file is something like:

Code:
Hello world!

How are you?

Code:
while(myScanner.hasNext()){
	System.out.println(myScanner.nextLine());
}

when I run this code it'll print out:

Hello World!How are you?
 

plinden

macrumors 601
Apr 8, 2004
4,029
142
Scanner.nextLine cannot not read any newlines in your file, and System.out.println cannot not print out a new line. So your text file cannot have new lines in there and your Scanner must be loading it all as one line.

Your lines must be separated by some other character that looks like newline to your editor but not to Java.
 

showtime

macrumors 6502
Original poster
May 10, 2007
291
1
Thanks for the reply. I actually tried shortening the code down for the general idea but I guess that wasn't a good idea.

Here's the actual code I'm using
Code:
PrintWriter pw = null;
try {
	Scanner scan = new Scanner(textfile);
 
	pw = new PrintWriter(savefile);
		
	while(scan.hasNext()){
		pw.print(scan.nextLine());
	}			
}
finally {
	pw.close();
}
 

showtime

macrumors 6502
Original poster
May 10, 2007
291
1
Code:
	while(scan.hasNext()){
		pw.print(scan.nextLine() + "\n");
	}

wouldn't that just be forcing it to print out a new line even if it wasn't there?

for example if my text document document read

Code:
Hello


World

it would output?
Code:
Hello
World
 

plinden

macrumors 601
Apr 8, 2004
4,029
142
It's your PrintWriter.print - look at System.out.println. "println" means "print and add a new line". PrintWriter.print (or System.out.print) doesn't add a new line. So Dale Cooper is almost right, but use pw.println instead to get the same effect. Doing that, your output file will be exactly the same as the input.

I realise I may have been misleading before ... Scanner (or any other Java reader class) just reads up to the end of line. It never includes the new line itself. But that's what I meant by it "cannot not read a newline" ... ie it doesn't ignore new lines.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.