Help with using the scanner class (java)

Discussion in 'Mac Programming' started by showtime, Jun 3, 2009.

  1. macrumors 6502

    Joined:
    May 10, 2007
    #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?
     
  2. macrumors 68040

    plinden

    Joined:
    Apr 8, 2004
    #2
    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.
     
  3. thread starter macrumors 6502

    Joined:
    May 10, 2007
    #3
    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();
    }
    
    
     
  4. macrumors regular

    Dale Cooper

    Joined:
    Sep 20, 2005
    #4
    Code:
    	while(scan.hasNext()){
    		pw.print(scan.nextLine() + "\n");
    	}			
    
     
  5. thread starter macrumors 6502

    Joined:
    May 10, 2007
    #5
    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
    
    
     
  6. macrumors 68040

    plinden

    Joined:
    Apr 8, 2004
    #6
    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.
     

Share This Page