我在尝试读取内部存储中的文件时遇到了文件错误;我非常确定该文件存在于我期望的位置并具有适当的权限
我正在创建一个Android应用程序,我将字符串数组列表保存到应用程序内部存储中的文件中,然后尝试从文件中随机访问各行。我正在编写文件并在同一个类中读取文件,因此我觉得我不应该遇到类似文件路径和命名约定的问题。
我已经验证或尝试过的事情:
我觉得我可能会在路径上硬编码,但这听起来像是一个糟糕的计划而且不应该是必要的
无论如何这里是奇妙的墙(或者更确切地说是我的代码,但只有相似的代码部分)
final List<String> affirmList = copyFilesToList("affirmation_file.txt");
final List<String> suggestList = copyFilesToList("suggestion_file.txt");
//copyFilesToList tries to open the file via selectSuggestion, if it is empty or fails, it goes into the create method
//opens both files and unpacks them into array list, feeds to unpack mehtods
private List<String> copyFilesToList(String fileName) {
String line="";
List<String> arr = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while ((line = bufferedReader.readLine()) != null) {
arr.add(line);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
arr.add("IO exception");
} finally {
//close stream
}
//test if arr contains something
//if not send to addDefaultLines
if (arr.isEmpty()){
arr = addDefaultLines(fileName);
}
return arr;
}
//
private List<String> addDefaultLines(String fileName){
List<String> arr = new ArrayList<String>(); //create arraylist
if (fileName=="affirmation_file.txt") {
//load affirmation values into arraylist
arr.add("affirmation 1");
arr.add("affirmation 2");
}
if (fileName=="suggestion_file.txt"){
//load suggestion values into arraylist
arr.add("suggestion 1");
arr.add("suggestion 2");
}
//sync arraylist with file
try{
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
String list = "";
int sz=arr.size();
//put the arraylist into a single string, for clarity
for (int i = 0; i < sz; i++) {
list += arr.get(i) + "\n"; //append with line breaks between
}
fos.write(list.getBytes());
}
catch (java.io.IOException e) {
e.printStackTrace();
}
return arr;
}