Android 从内部存储器读取txt文件会返回FIleNotFound,即使地址中存在该文件
我正在尝试从内部存储器读取文件。该文件位于给定位置的内部存储器中,代码可以访问该文件。。但当它试图打开文件时,抛出FileNotFound异常,这是由于应用程序无法打开文件进行读取。我了解到应用程序无法使用返回false的Android 从内部存储器读取txt文件会返回FIleNotFound,即使地址中存在该文件,android,file-handling,internal-storage,Android,File Handling,Internal Storage,我正在尝试从内部存储器读取文件。该文件位于给定位置的内部存储器中,代码可以访问该文件。。但当它试图打开文件时,抛出FileNotFound异常,这是由于应用程序无法打开文件进行读取。我了解到应用程序无法使用返回false的file.canRead()方法打开文件。有人能帮我弄清楚情况吗?这是我的密码 path = MainActivity.this.getFilesDir().getAbsolutePath(); try { File file = new File(path,
file.canRead()
方法打开文件。有人能帮我弄清楚情况吗?这是我的密码
path = MainActivity.this.getFilesDir().getAbsolutePath();
try {
File file = new File(path, "jamshaid.txt");
Context ctx = getApplicationContext();
FileInputStream fileInputStream = ctx.openFileInput(file.getName());
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineData = bufferedReader.readLine();
view1.setText(lineData);
} catch (Exception e) {
e.printStackTrace();
}
权限
我的设备的API版本是24
我想做什么?
我正在尝试解析文件/将文本文件数据设置为textView
更新1
更改后File directory=MainActivity.this.getFilesDir();
File File=新文件(目录“jamshaid.txt”)代码>
我得到以下错误
`09-25 14:45:16.413 21144-21144/com.example.root.testingvolley W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.root.testingvolley/files/jamshaid.txt (No such file or directory)`
您如何验证该文件是否存在?可能该文件不存在,在这种情况下,openFileInput()将抛出FileNotFoundException
您可以尝试在写入模式下打开文件,如果不存在这样的文件,将创建一个文件
FileOutputStream fileOutputStream = ctx.openFileOutput(file.getName(), ctx.MODE_PRIVATE);
在目录路径中尝试此操作
File directory = context.getFilesDir();
File file = new File(directory, filename);
或
确保您选中了要使用的权限(读、写等)File@MiladBahmanabadi我已将清单中的权限添加到问题中。请喝一杯look@Nancy,您会提到您的设备api版本吗?@MohammodHossain api版本为24@Nancy是,现在您添加了权限…该文件已存在于给定路径。它是从firebase下载并存储的storage@MohammodHossain你什么意思?我只是想看看。。。如何同时写入?我添加了stacktrace。请看一看
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
try {
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}