简体   繁体   中英

Reading integers from text file

I am trying to read integers from a text file but I failed. (It fails to read even the first integer)

public void readFromFile(String filename) {
    File file = new File(filename);
    try {
        Scanner scanner = new Scanner(file);
        if (scanner.hasNextInt()) {
            int x = scanner.nextInt();
        }
        scanner.close();

    } catch (FileNotFoundException e) {
        System.out.println("File to load game was not found");
    }
}

The error I get is: NoSuchElementException. The file looks like this:

N,X1,Y1,X2,Y2,X3,Y3

While n equals 3 in this example.

I call this method a in the main method like this:

readFromFile("file.txt");

I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.

    try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
        String input = br.readLine();
        int count = 0;
        for(int i = 0; i < input.length()- 1; i++){
            if(isNumeric(input.charAt(i))){

                // replace the Sysout with your own logic
                   System.out.println(input.charAt(i));
                }
            }
        } catch (IOException ex){
            ex.printStackTrace();
        }

where isNumeric can be defined as follows:

private static boolean isNumeric(char val) {
    return (val >= 48 && val <=57);
}

Scanner uses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

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