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?
-
1you can use the usual java File reading method to read the file in android too.– RahulFeb 8, 2013 at 8: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);
}
-
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"/"
– milosmnsNov 30, 2014 at 21:33 -
-
4The correct function is
context.openFileInput("hello.txt")
. There's no second parameter. Aug 26, 2015 at 7:19 -
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.
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;
}
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();
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());
}
-
3
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) {}
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;
}
-
1No. The question which was asked concerns reading a file, while your code snippet only writes one. Apr 24, 2015 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.– DagWApr 27, 2015 at 7: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. Apr 27, 2015 at 14:46