在 Android 上下载文本文件 [英] Download a text file on Android
本文介绍了在 Android 上下载文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从服务器下载一个文本文件并将其保存在内存中.然后逐行阅读.更好 - 直接从服务器逐行读取.
I need to download a text file from a server and just save it in memory. Then go line by line and read it. Better off - read line by line directly from the server.
将其保存在内存中"意味着不将其写入文件.
'save it in memory' means without writing it to a file.
你会怎么做?
谢谢!
推荐答案
这有什么不可能
?试试这个代码:注意创建文件的 CONTEXT 可能是一个 Activity/ApplicationContext/等.
What's so impossible
about it ? Try this code: Notice that CONTEXT creating the file could be an Activity/ApplicationContext/etc.
public boolean downloadFile(final String path)
{
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/yourfile.png");
if (file.exists())
{
file.delete();
}
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
这是一个简单的文件读/写,使用活动 context
.
It's a simple file R/W with the usage of the activity context
.
根据您最近更改的问题,我在此处发布:
EDIT : As per your recently changed question, I am posting this here :
试试这段代码:
try {
// Create a URL for the desired page
URL url = new URL("ksite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
这应该有效
这篇关于在 Android 上下载文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文