所以我似乎在这个函数中有一个错误,因为它找不到位于项目文件夹中的文件。 (wordsEn.txt)我正在制作一个刽子手游戏,我需要将该文件中的每一行作为一个字符串,并放入一个名为:worldLineArray的数组中。我已经这样做了,但由于某些原因它不起作用:
public String readFromFile() {
String words = "";
// Array List That Words being added to
ArrayList<String> wordLineArray = new ArrayList<String>();
try {
FileInputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
// wordLineArray defined and filled. **Array**
wordLineArray.add(receiveString);
stringBuilder.append(receiveString);
}
inputstream.close();
// Possible pointless code below
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
//R Generator for Strings in wordLineArray
String secretWord = wordLineArray.get(getRandomNumber(0, wordLineArray.size()));
// secretWord = secretWordString.toCharArray();
// Put displayedWord up here. Needed to be defined in order to run readFromFile() Below.
displayedWord = new char[secretWord.length()];
for (int i = 0; i < secretWord.length(); i++) {
displayedWord[i] = '-';
}
return words;
}
我还附加了堆栈跟踪。 93和36处的错误是由于readFromFile()中的错误。
03-04 08:18:12.812: E/login activity(3443): File not found: java.io.FileNotFoundException: /data/data/org.concordacademy.hangman/files/wordsEn.txt: open failed: ENOENT (No such file or directory)
03-04 08:18:12.890: E/AndroidRuntime(3443): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.concordacademy.hangman/org.concordacademy.hangman.PlayScreen}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-04 08:18:12.890: E/AndroidRuntime(3443): at org.concordacademy.hangman.PlayScreen.readFromFile(PlayScreen.java:71)
03-04 08:18:12.890: E/AndroidRuntime(3443): at org.concordacademy.hangman.PlayScreen.startGame(PlayScreen.java:92)
03-04 08:18:12.890: E/AndroidRuntime(3443): at org.concordacademy.hangman.PlayScreen.onCreate(PlayScreen.java:36)