[英]Trying to read a .txt file and store it into a private arraylist
我正在尝试读取文件并将其存储到私有类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();
}
}
任何帮助将不胜感激。 谢谢。
向main
添加throws IOException
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);
}
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();
}
}
您在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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.