gpt4 book ai didi

java - Android 文件转字符串

转载 作者:可可西里 更新时间:2023-10-31 22:04:06 27 4
gpt4 key购买 nike

我想在 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 应用程序的堆空间非常有限。如果您不将整个文件读入内存,而是将其流式传输并一次一个 block 地发送到服务器,情况会更好。

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 - Android 文件转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196306/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com