未处理的异常:FileNotFoundException

use*_*492 2 java bufferedreader

我在java中读取文件时遇到一些问题:我的文件是例如:

3,4
2
6
4
1
7
3
8
9
Run Code Online (Sandbox Code Playgroud)

第一行3和4是数组A和B的长度,然后是每个数组的元素.我做的

import java.io.*;
import java.util.Arrays;

public class Progetto  {

    public static void main(String args[])
      {
// Open the file that is the first 
// command line parameter

            FileInputStream fstream = new FileInputStream("prova.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine = br.readLine(); // step 1

            if (strLine != null) {
              String[] delims = strLine.split(","); // step 2

              // step 3
              int[] a = new int[Integer.parseInt(delims[0])];
              int[] b = new int[Integer.parseInt(delims[1])];

              // step 4
              for (int i=0; i < a.length; i++)
                a[i] = Integer.parseInt(br.readLine());

              // step 5
              for (int i=0; i < b.length; i++)
                b[i] = Integer.parseInt(br.readLine());

              br.close(); // step 6

              // step 7
              System.out.println(Arrays.toString(a));
              System.out.println(Arrays.toString(b));
            }
        }
      }
Run Code Online (Sandbox Code Playgroud)

但它给了我错误: - 未处理的异常类型FileNotFoundException(第11行) - 未处理的异常类型IOException(第15行26 30 32行),但我不知道为什么.有人可以帮助我.提前致谢

Ruc*_*era 7

更改main方法抛出的方式IOException.由于这些操作可能导致FileNotFoundExceptionIOException.

    public static void main(String[] args) throws FileNotFoundException {

    }
Run Code Online (Sandbox Code Playgroud)

或者添加一个try-catch

   try {
        FileInputStream fstream = new FileInputStream("prova.txt");
        String strLine = br.readLine();
    } catch (IOException e) {
        e.printStackTrace(); 
    }
Run Code Online (Sandbox Code Playgroud)

毕竟这些事情确保文件存在.


Bob*_*der 0

您所要做的就是为未处理的异常添加 try-catch 块。发生这种情况是因为FileInputStream抛出了FileNotFoundException一个受检查的异常(您可以在此处阅读更多内容)

同样的问题也发生在这里

String strLine = br.readLine()
Run Code Online (Sandbox Code Playgroud)