【问题标题】:Download file from webserver and read content on android从网络服务器下载文件并在 android 上读取内容
【发布时间】: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


【解决方案1】:

所以正在下载到 SD 卡

protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            File SDCardRoot = Environment.getExternalStorageDirectory();
            SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
            SDCardRoot.mkdir();
            File file = new File(SDCardRoot,"settings.dat");
            FileOutputStream output = new FileOutputStream(file);
            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

和阅读:

    new DownloadFileFromURL().execute("http://www.example.com/file.txt");
                if (!Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Log.d(LOG_TAG, "SD n\a " + Environment.getExternalStorageState());
                    return;
                }
                File sdPath = Environment.getExternalStorageDirectory();
                sdPath = new File(sdPath.getAbsolutePath() + "/plus");
                File sdFile = new File(sdPath, "settings.dat");
                try {
                    BufferedReader br = new BufferedReader(new FileReader(sdFile));
                    String str = "";
                    while ((str = br.readLine()) != null) {
                        String[] words = str.split(",");
// do some work
                            }
                        }
                        Log.d(LOG_TAG, str);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2016-05-28
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多