java-Android文件到字符串

我想在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.它们是binary files.

Then I want to send it to a server

您的Android应用程序的堆空间非常有限.如果您不将整个文件读入内存,而是一次将其流式传输并一次发送给服务器,那将更好.

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.

上一篇:为什么Java Scanner无法读取所有行?


下一篇:Java Sound : audio inputstream from pcm amplitude array