Damian Jäger
Damian Jäger

Reputation: 214

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 a server. But for testing I just create a file on the device and put the content into 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 for example try to copy a pdf file it is openable but just white.

Can anyone help me?

Thanks

Upvotes: 3

Views: 1739

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006554

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

PDF files are not text files. They are binary files.

Then I want to send it to a server

Your Android application has very limited heap space. It will be better if you did not read the whole file into memory, but rather streamed it in and sent it to the server a chunk 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 is because you are trying to treat a PDF file as a text file. Do not do this. Copy it as a binary file.

Upvotes: 3

Related Questions