Android 文件到字符串

Android File to String

我想读出Android中的一个文件并获取字符串形式的内容。然后我想将它发送到服务器。但是为了测试,我只是在设备上创建一个文件并将内容放入其中:

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();

这适用于 txt 文件,但是当我尝试复制 pdf 文件时,它可以打开,但只是白色。

谁能帮帮我?

谢谢

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

PDF 文件不是 text files. They are binary files

Then I want to send it to a server

您的 Android 应用程序的堆 space 非常有限。如果您没有将整个文件读入内存,而是将其流式传输并一次一个块地发送到服务器会更好。

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

那是因为您试图将 PDF 文件视为文本文件。不要这样做。 Copy it as a binary file.