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

Freelancer Writers: How to Make Money on Freelancer.com

There’s a whole load of money that can be made online as…

CPA: How to Make Money with CPA (The Ultimate Guide)

I’ve been involved in CPA marketing since 2012, and after experiencing the…

Shopify Dropshipping: How to Make Money Dropshipping on Shopify

Shopify and dropshipping tend to go hand-in-hand nowadays. For the longest time,…

Java Classes: How to Make A New Class in Java

Classes are super important in Java and most other Object-orientated programing languages.…