Java – Android file to string

Android file to string… here is a solution to the problem.

Android file to string

I want to read out a file in Android and get the content as a string. Then I want to send it to the server. But for testing, I just created a file on the device and put the content in it :

InputStream stream = getContentResolver().openInputStream(fileUri);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

File dir = new File (Environment.getExternalStorageDirectory() + "/Android/data/" + getPackageName());
File file = new File(dir, "output." +format);  format is "txt", "png" or sth like that


BufferedWriter writer = null;
writer = new BufferedWriter(new FileWriter(file));

String line = reader.readLine();

while (line != null)
    line = reader.readLine();
    if(line != null)

This works for txt files, but when I try to copy a pdf file, it opens, but just white.

Can anyone help me?



I want to read out a file in Android and get the content as a string.

PDF files are not <a href=”” rel=”noreferrer noopener nofollow”>text files.They are binary files .

Then I want to send it to a server

Your Android application’s heap space is very limited. It would be better if you didn’t read the entire file into memory, but instead streamed it and sent it to the server one block at a time.

This works for txt files but when I for example try to copy a pdf file it is openable but just white.

That’s because you’re trying to treat a PDF file as a text file. Don’t do it. Copy it as a binary file .

Related Problems and Solutions