简体   繁体   中英

Java program file handle

Here is my program:

public class Mycode{
    public static void main(String[] args) {
        System.out.println("Welcome to the innovation and tech data mining table");
        Scanner sc = new Scanner(System.in);
        Scanner input = new Scanner(new File("Data2.txt"));
        while (input.hasNext()){
            String data = input.nextLine();
        }
        System.out.println(data);
    }
}

Basically I'm taking a text file and storing it in my variable data. The problem I'm having is that it refuses to print out the data as it says it can't be resolved to a variable. Anyone have any way around this?

Define the variable data before the while loop.
Currently it is local to the loop and thus not visible outside of it.

And... you're not taking the text file but only its last line.
If you want all the text, do: data += input.nextLine() in the loop
or (even better) use a StringBuilder and append to it in the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM