Android file for string

I want to read 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 create 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, for example, try to copy a PDF file, it can be opened, but just white.

Can anyone help me?

thank

+3


source to share


1 answer


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

PDF files are not text files . They are binaries .

Then I want to send it to the server



There is very little heap space in your android app. It would be better if you didn't read the entire file in memory, but rather drowned it 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 can be opened, but just white.

This is because you are trying to treat the PDF as a text file. Do not do it. Copy it as a binary file .

+3


source







All Articles