我该如何修复我的读取文件方法?

时间:2016-04-28 03:07:14

标签: java arrays string for-loop try-catch

  

阅读文件:

     

此方法有一个参数,即文件的名称   此方法的目的是将文件的内容读入数组   您必须使用try / catch块和扫描仪对象   该文件的第一行有一个整数,指定行数   将此值读入变量numberLines   再次调用nextLine以丢弃剩下的行!
  将fileContents数组分配为numberLineThe元素   写一个for循环,将指定行数读入fileContents   catch异常代码不应该执行任何操作或报告错误。

这是我目前的代码。我做错了什么?

 public void readFile(String filename) {
        // TODO Auto-generated method stub
        try {

            Scanner read = new Scanner(new File(filename));
            int[] fileContents = {numberLines};
            numberLines = read.nextInt();
            read.nextLine();

            for(int i = 0; i < numberLines; i ++){

                fileContents[i] = read.nextInt();

                read.close();
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

1 个答案:

答案 0 :(得分:0)

public void readFile(String filename) {
        // TODO Auto-generated method stub
        try {

            Scanner read = new Scanner(new File(filename));
            //int[] fileContents = {numberLines}; //fileContents has one element
            numberLines = read.nextInt();
            //you can read numberLines first and then create fileContents array as you wish
            int[] fileContents = new int[numberLines];
            //if each line only contains a number, you can read line to String and convert it to int
            //read.nextLine();

            for(int i = 0; i < numberLines; i ++){
                String nextLine = read.nextLine();
                //fileContents[i] = read.nextInt();
                fileContents[i] = Integer.parseInt(nextLine);
                //read.close();
            }
            //close read after all lines were read
            read.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

可能抛出一些例外:

NoSuchElementException - 如果没有找到行

IllegalStateException - 如果此扫描仪已关闭