I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
- 1,973
- 23
- 53
- 1,041
- 1
- 11
- 35
-
1you can use the usual java **File** reading method to read the file in android too. – Rahul Feb 08 '13 at 08:13
7 Answers
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
- 3,713
- 8
- 32
- 47
- 13,467
- 8
- 68
- 76
-
1
-
4Note sure where this is applicable, but there is a separator string in the File class. I guess you should use then `File.separator` instead of `"/"` – milosmns Nov 30 '14 at 21:33
-
-
4The correct function is `context.openFileInput("hello.txt")`. There's no second parameter. – Nj Subedi Aug 26 '15 at 07:19
-
-
I get error: java.lang.IllegalArgumentException: File /data/data/com.example.main/cache/test.conf contains a path separator – Dr.jacky Oct 03 '15 at 07:42
-
The code seems to be outdated. Please see http://stackoverflow.com/questions/41622006/how-to-fic-android-error-method-openfileinput-in-class-context-cannot-be-applie – Alex Jan 12 '17 at 20:12
-
There is also this constructor : `new File(context.getFilesDir(), filename)` – Omar Aflak Feb 25 '17 at 10:45
-
-
I'm getting an error in Android Studio on the words "File" and "context" what is the declarations or sources of these for your snippet please ? – mist42nz Jun 08 '21 at 21:22
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
- 2,069
- 2
- 17
- 20
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath){
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
StringBuilder sb;
while(fileInputStream.available() > 0) {
if(null== sb) sb = new StringBuilder();
sb.append((char)fileInputStream.read());
}
String fileContent;
if(null!=sb){
fileContent= sb.toString();
// This is your fileContent in String.
}
try {
fileInputStream.close();
}
catch(Exception e){
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
return fileContent;
}
- 7,819
- 4
- 43
- 61
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
code::
StringBuilder sb = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om){
om.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
String result = sb.toString();
- 6,287
- 2
- 51
- 90
-
1Iam getting an error on the line: File yourFile = context.getFilesDir() + "/" + "hello.txt"; Error :context cannot be resolved – Shan Feb 08 '13 at 09:51
-
You can get the context by calling getApplicationContext() within your activity. – BVB Jun 04 '13 at 18:05
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
- 208
- 1
- 3
- 12
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
- 7,523
- 4
- 40
- 57
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
- 1,075
- 1
- 15
- 28
-
1No. The question which was asked concerns *reading* a file, while your code snippet only writes one. – Chris Stratton Apr 24 '15 at 16:03
-
Hey.. The answer is regarding to the mode the file was written in, if its not world readable he will not be able to read it. – DagW Apr 27 '15 at 07:35
-
No, the app which owns the file can of course read it when it is private. It is only other things which won't be able to. – Chris Stratton Apr 27 '15 at 14:46