Hey guys I am really struggling with a problem when trying to read a text file in android java.
public String readFromFile(String filename)
{
String content = "";
try
{
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/MyApplication");
File file = new File(dir, filename);
Scanner scanner = new Scanner(file);
String line = "";
while(scanner.hasNextLine())
{
line = scanner.nextLine();
content += line + "\n";
}
scanner.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content;
}
I tried extracting the content by using a scanner as well as a buffered reader
public List<String> readFromFile(String filename)
{
List<String> lines = new ArrayList<String>();
FileReader fileReader;
BufferedReader bufferedReader;
try
{
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "MyApplication");
File file = new File(dir, filename);
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
while(line != null)
{
lines.add(line);
bufferedReader.readLine();
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return lines;
}
But none of them seems to work. The functions return just zero, as if the file was empty. Also I get no error messages and I double checked the path. Usually those functions work perfectly fine for me, but I couldn't resolve this one.
I appreciate any help :)
EDIT: If found the problem. Everything is fine with the permissions or the location of the file, the problem was simply that I put
FileOutputStream fileOutputStream = new FileOutputStream(file)
in the code before I called the readFromFile() method. I think because of that the readFromFile() method returned that the file was empty. Thank you for your answers!