Android 将联机文件内容缓存为字符串而不是本地文件
我正在从example.com/test.txt下载一个文本文件,我只需要在我的应用程序运行时使用这些内容,它们不需要保存到静态文件中 到目前为止,我的代码是:Android 将联机文件内容缓存为字符串而不是本地文件,android,Android,我正在从example.com/test.txt下载一个文本文件,我只需要在我的应用程序运行时使用这些内容,它们不需要保存到静态文件中 到目前为止,我的代码是: InputStream input = new BufferedInputStream(getURL.openStream()); OutputStream output = new FileOutputStream(tempFile); byte data[]
InputStream input = new BufferedInputStream(getURL.openStream());
OutputStream output = new FileOutputStream(tempFile);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
如何将联机文件内容写入字符串,而不是将文件保存在本地?我曾尝试在while语句中向字符串追加数据
,但只得到了乱码文本(如预期的那样,但我不知道还能做什么)。是否将字节转换回字符串
谢谢你的帮助 使用ByteArrayOutput流代替FileOutputStream。然后可以调用toString将其转换为字符串
InputStream input = new BufferedInputStream(getURL.openStream());
OutputStream output = new ByteArrayOutputStream();
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
String result = output.toString();
您可以使用与上面描述的方法类似的方法 Java文档中的代码片段:
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
您只需将每一行附加到一个字符串,而不是将其发送到System.out。通过+运算符进行字符串连接并没有那么有效。你最好使用StringBuilder。