Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?

Tags:

java

class

input

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?

Here is how I have initialized the scanner in my main class:

public class Nimsys {
    public static Scanner keyboardIn;

    static {
        keyboardIn = new Scanner(System.in);
    } ...

In the main class Nimsys here is how I get input:

String inputString1 = keyboardIn.nextLine();

In another class here is how I use the scanner from Nimsys:

int inputInt1 = Nimsys.keyboardIn.nextInt();

But now in my main class Nimsys I am trying to scan in a whole file - so far I have used another scanner, as you can see in the code below. However, is it possible to have it all done by the original scanner?

try
        {
            inputStream = new Scanner(new FileInputStream("file.txt"));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("File morestuff.txt was not found");         
        }
        String[] reopenPlayers = new String[100];
        int i = 0;
        while(inputStream.hasNextLine()){
            reopenPlayers[i]=inputStream.nextLine();
        System.out.println(reopenPlayers[i]);
        }

Thanks a lot!

Tom

like image 310
tomglynch Avatar asked Dec 14 '25 12:12

tomglynch


1 Answers

If I understand your question (not that I think a global variable is a great solution), you could change (and perhaps rename)

keyboardIn = new Scanner(System.in);

to something like

try {
    keyboardIn = new Scanner(new FileInputStream("file.txt"));
} catch (FileNotFoundException e) {
    System.out.println("file \"file.txt\" not found");
    e.printStackTrace();
}

and then remove the try-catch from

inputStream = new Scanner(new FileInputStream("file.txt"));

and modify it to something like

inputStream = Nimsys.keyboardIn;

(or replace inputStream with Nimsys.keyboardIn and not to be prescriptive but perhaps rename Nimsys.keyboardIn to Nimsys.in). Hopefully you're using an IDE that supports refactoring.

like image 93
Elliott Frisch Avatar answered Dec 17 '25 02:12

Elliott Frisch