【发布时间】:2015-11-08 14:00:48
【问题描述】:
我正在学习 Android 并将我的 Windows 应用程序移植到 Android 平台。我需要建议如何下载一个小文本文件并阅读该文件的内容。
我的 Windows 应用程序中有以下代码,我需要为 Android 应用程序重写它:
string contents = "file.txt";
string neturl = "http://www.example.com/file.txt";
HttpClient client = new HttpClient();
try {
HttpResponseMessage message = await client.GetAsync(neturl);
StorageFolder folderForFile = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile fileWithContent = await folderForFile.CreateFileAsync(channels, CreationCollisionOption.ReplaceExisting);
byte[] bytesToWrite = await message.Content.ReadAsByteArrayAsync();
await FileIO.WriteBytesAsync(fileWithContent, bytesToWrite);
var file = await folderForFile.GetFileAsync(contents);
var text = await FileIO.ReadLinesAsync(file);
foreach (var textItem in text)
{
string[] words = textItem.Split(',');
...
我在 Android 上找到了我需要为异步下载创建以下类的内容
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("file.txt");
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
在上面的代码中,我尝试下载文件并将其命名为“file.txt”,但出现异常“FileNotFoundException file.txt open failed: EROFS(只读文件系统)”,我需要在内部保存(我不想让用户在文件资源管理器中看到这个文件)并重写文件(如果存在)。 我尝试执行此任务并读取文件
void DownloadAndReadContent() {
new DownloadFileFromURL().execute("http://www.example.com/file.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput("file.txt")));
String str = "";
while ((str = br.readLine()) != null) {
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
下载文件并保存到 SD 卡上:stackoverflow.com/questions/25785609/…
-
'new FileOutputStream("file.txt");'。您应该使用完整路径。或者使用 openFileOutput()。
-
完整路径在 android 上的外观如何?
-
如果我使用“/data/data/packagename/files/file.txt”然后“IllegalArgumentException 文件包含路径分隔符”
标签: android