Reputation:
i am trying to read file from internal storage. the file is available in internal storage at given location and the code is able to access it.. but when it tries to open the file , it throws FileNotFound Exception which is due to the app can't open the file to read. I came to know about the app can't open the file by using file.canRead()
method which is returning false. can anybody help me to figure the situation out? Here is my code
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();
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
API Version of my device is 24
i am trying to parsethe file/set text file data to textView
after changing
File directory = MainActivity.this.getFilesDir();
File file = new File(directory, "jamshaid.txt");
i am getting the following error
`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)`
Upvotes: 0
Views: 514
Reputation: 4114
Try this for directory path
File directory = context.getFilesDir();
File file = new File(directory, filename);
Or
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();
}
Upvotes: 1
Reputation: 2673
How are you verifying that the file exists? Perhaps the file does not exist, in which case openFileInput() will throw FileNotFoundException.
You can try opening the file in write-mode which will create a file if no such file exists.
FileOutputStream fileOutputStream = ctx.openFileOutput(file.getName(), ctx.MODE_PRIVATE);
Upvotes: 0