Java InputMismatchException 未知来源

Java InputMismatchException unknown source

我找不到错误的根源。我所做的只是从文件中读取文本

public static void main(String[] args) throws Exception {
    int T;

    Scanner sc = new Scanner(new FileInputStream("problem3.txt"));

    T = sc.nextInt(); // first int in file, so T should be 2
}

并且错误消息显示 InputMismatchException:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at round1.Problem3.main(Problem3.java:11)

problem3.txt内容如下(3行,无空格):

2
36
127

我已经搜索了解决 InputMismatchException 的其他问题,但大多数都存在 'wrong format' 错误(尝试将整数读取为字符串,反之亦然)。但就我而言,它应该没有问题,因为文件内容都是整数。

我还认为错误可能出在 'new line character (\n)' 上。所以尝试了

T = sc.nextInt(); // error
sc.nextLine();

反过来

sc.nextLine();
T = sc.nextInt(); // error

两者仍然在同一行上给出相同的错误。

看似简单的问题,但我就是找不到。提前致谢。


问题已解决:我将编码更改为 Cp1252,它读取的是 2。谢谢大家

尝试FileIO,这取决于你想读什么,它可能会容易得多

尝试给出正确的文件路径。我能够获取文件中的所有值

public static void main(String[] args) {
    // TODO Auto-generated method stub


    Scanner sc;
    try {
        sc = new Scanner(new FileInputStream("/Users/Zero/Desktop/problem3.txt"));


         int    T = sc.nextInt(); // first int in file, so T should be 2
         System.out.println(T);

        T = sc.nextInt();
         System.out.println(T);

         T = sc.nextInt();
         System.out.println(T);     
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

你能检查一下控制台上打印的是什么吗

     StringBuffer a = new StringBuffer();
        while(sc.hasNext())
        {
        a.append(sc.nextLine());    
        }
         System.out.println(a.toString());

这是一个编码问题。尝试使用 UTF-8 或 ANSI,您的代码应该 运行 没问题。