import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
public class WordList {
private static Random r = new Random();
private static ArrayList<String> words = new ArrayList<String>();
String filename = "Cities.txt";
public static void main(String[] args) throws IOException {
WordList wl = new WordList();
buffR(wl.filename);
System.out.println(words);
System.out.println(getRandomWord());
}
public static ArrayList buffR(String filename) throws IOException {
words.clear();
String line = null;
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
return words;
}
public static String getRandomWord() {
WordList wl = new WordList();
String randomWord;
if (words.size() > 0) {
int index = r.nextInt(words.size());
randomWord = words.get(index);
} else {
randomWord = wl.filename + " is missing";
}
return randomWord;
}
}
当我运行此代码时,我有一个java.io.FileNotFoundException(关于我的BufferedReader方法)(我故意放了一个没有现成的文件)。但是,我已经在我的方法头中抛出了IOException。我该怎么办才能再次遇到这个错误?
答案 0 :(得分:3)
添加throws
的所有内容都表示该方法可以抛出Exception
,如果抛出它,您希望处理Exception
。要做到这一点,你可以包装代码块是一个try-catch块。如果它应该被抛出,则无法阻止Exception
被抛出,但是try-catch块会使它不会崩溃。 Oracle Tutorial非常有帮助。
对于此示例,您可以执行以下操作:
try
{
//This already throws FileNotFoundException
br = new BufferedReader(new FileReader(filename));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
答案 1 :(得分:1)
这种做法怎么样?我改变了一些事情,但我在下面记录了它。
// static, pass in the initial words lits.
public static List<String> buffR(List<String> words,
String filename) throws IOException {
words.clear(); // If you want to reuse it.
String line = null;
BufferedReader br = null;
File file = null; // A file to read.
try {
file = new File(filename); // Create a File object.
if (! file.exists()) { // It's not there!
throw new FileNotFoundException("Could not find file: " + filename);
}
// Proceed as before...
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
words.add(line);
}
} finally {
br.close(); // Let's try to not leak any resources.
}
return words;
}