我在 java 中读取文件时遇到一些问题:
我的文件是例如:
3,4
2
6
4
1
7
3
8
9
其中第一行 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));
}
}
}
但它给了我错误:
- 未处理的异常类型 FileNotFoundException(第 11 行)
- 未处理的异常类型 IOException(第 15 26 30 32 行)
但我不知道为什么。有人可以帮助我。
提前致谢
最佳答案
改变你的 main 方法抛出的方式 IOException
.由于这些操作可能导致 FileNotFoundException
或 IOException
.
public static void main(String[] args) throws FileNotFoundException {
}
或添加
try-catch
堵塞 try {
FileInputStream fstream = new FileInputStream("prova.txt");
String strLine = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
毕竟这些事情确保文件存在。
关于java - 未处理的异常 : FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297732/