我正在尝试读取文件并将其存储到私有类arraylist中但是我收到此编译器错误:WordList.java:8:未报告的异常java.io.IOException;必须被抓住或宣布被抛出
import java.util.*;
import java.io.*;
public class WordList
{
private ArrayList<String> words = new ArrayList<String>();
public void main(String[] args)
{
ArrayListConstructor("Cities.txt");
System.out.println(words);
}
public void ArrayListConstructor(String filename) throws IOException
{
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line != null)
{
this.words.add(line);
line = br.readLine();
}
br.close();
}
}
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
将throws IOException
添加到main
public void main(String[] args) throws IOException
或将方法包装在try/catch
块
public void main(String[] args)
{
try{
ArrayListConstructor("Cities.txt");
}
catch(IOException ex){
ex.printStackTrace();
}
System.out.println(words);
}
答案 1 :(得分:0)
package testing;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class WordList
{
private static ArrayList<String> words = new ArrayList<String>();
public static void main(String[] args) throws IOException
{
arrayListConstructor("Cities.txt");
System.out.println(words);
}
public static void arrayListConstructor(String filename) throws IOException
{
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line != null)
{
words.add(line);
line = br.readLine();
}
br.close();
}
}
答案 2 :(得分:0)
您在方法ArrayListConstructor(String filename)中抛出IOException异常因此,无论何时使用此方法,都应捕获此异常
import java.io.*;
import java.util.*;
public class WordList {
private ArrayList<String> words = new ArrayList<String>();
public void main(String[] args) {
try {
ArrayListConstructor("Cities.txt");
} catch (IOException ex) {
System.out.println("Exception occured");
}
System.out.println(words);
}
public void ArrayListConstructor(String filename) throws IOException {
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line != null) {
this.words.add(line);
line = br.readLine();
}
br.close();
}
}
或者您可以再次抛出此异常
import java.io.*;
import java.util.*;
public class WordList {
private ArrayList<String> words = new ArrayList<String>();
public void main(String[] args) throws IOException {
ArrayListConstructor("Cities.txt");
System.out.println(words);
}
public void ArrayListConstructor(String filename) throws IOException {
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line != null) {
this.words.add(line);
line = br.readLine();
}
br.close();
}
}