Java - 从文件中读取有符号整数

时间:2012-03-29 01:22:40

标签: java arrays java.util.scanner readfile

我试图将10个有符号整数从一个文件读入一个数组,由于某种原因,它没有发生,我在编译和运行时没有收到任何错误。我只是想让第二双眼睛看一眼,看看我可能会缺少什么。

测试文件是“input.txt”并包含:-1,4,32,0,-12,2,30,1,-3,-32

这是我的代码:

  public void readFromFile(String filename)
  {
     try {
        File f = new File(filename);
        Scanner scan  = new Scanner(f);
        String nextLine;
        int[] testAry = new int[10];
        int i = 0;

        while (scan.hasNextInt())
        {
           testAry[i] = scan.nextInt();
           i++;
        }
     }
        catch (FileNotFoundException fnf)
        {
           System.out.println(fnf.getMessage());
        }
  } 

2 个答案:

答案 0 :(得分:2)

您使用Scanner对象上的默认分隔符。

尝试使用我在行中使用的分隔符useDelimiter(\\ s *,\\ s *“)。它的正则表达式用逗号分隔文件中的输入。


 try {
            File f = new File("input.txt");
            Scanner scan = new Scanner(f);
            scan.useDelimiter("\\s*,\\s*");
            String nextLine; //left it in even tho you are not using it
            int[] testAry = new int[10];
            int i = 0;

            while (scan.hasNextInt()) {
                testAry[i] = scan.nextInt();
                System.out.println(testAry[i]);
                i++;
            }
        } catch (FileNotFoundException fnf) {
            System.out.println(fnf.getMessage());
        }

答案 1 :(得分:0)

你可能会抛出另一个你没有抓到的例外

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt()

从输入中扫描的int抛出:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

或者你可以去老学校并使用缓冲读卡器来验证你是否正在获取数据

try{

  FileInputStream fstream = new FileInputStream(filename);

  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;

  while ((strLine = br.readLine()) != null)   {

    System.out.println (strLine);
  }
  in.close();
  }catch (Exception e){
    System.err.println("Error: " + e.getMessage());
   }