The Scanner is super useful for taking user inputs. However, you might want to pass a text file into it.

I’m going to show you how!

//IMPORT THE STUFF YOU NEED..

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

//Make a new Class... call it whatever the fuck you like
public class FileScanner {
    
    public static void main(String args[]){
        
        //make a new file called "filename", set the "location" in the parameters...
        File filename = new File("TextFile.txt");
        
        //make a new blank scanner... because we got to use try/catch stuff next...
        Scanner input = null; //make null to initialise the scanner...
        
        //make some try/catch thingy so that if the file doesn't exist you don't fuck the whole thing up.
        try {//try to....
            //set the scanner to the file...
            input = new Scanner(filename);
            
        } catch (FileNotFoundException e){// if you fuck it up...
            
            // say so..
            System.out.println("File not found.");    
        }
        
        //WHILE THE INPUT HAS ANOTHER LINE, PRINT DAT LINE!
        while(input.hasNextLine()){
            System.out.println(input.nextLine());            
        }
        
    }
    
}

There are some important things…

  • Import
    • Scanner
    • File IO
    • File not found exception
  • Try/Catch statements around Scanner using file
    • File might not exist and break everything so …
      • TRY IT, then
      • if not exist, CATCH THE ERROR
  • WHILE LOOP
    • Only do next thing if it exists
    • Otherwise, you get null pointer exception

Until next time, Josh.

Leave a Reply
You May Also Like

YouTube Adsense: How To Put AdSense on YouTube Videos

Putting AdSense on YouTube videos is a great way to generate extra…

CPAGrip WordPress: How to Install CPAGrip Content Lockers on WordPress

I’ve realised that a lot of you guys love the CPA methods…