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());
if(!dir.exists())
    dir.mkdirs();
File file = new File(dir, "output." +format);  format is "txt", "png" or sth like that

if(!file.exists())
    file.createNewFile();

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

String line = reader.readLine();

while (line != null)
{
    writer.write(line);
    line = reader.readLine();
    if(line != null)
        writer.write("\n");
}
writer.flush();
writer.close();
stream.close();

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

Can anyone help me?

Thanks

Solution

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

PDF files are not <a href=”http://en.wikipedia.org/wiki/Text_file” 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