从webserver下载文件并阅读android上的内容

时间:2015-11-08 14:00:49

标签: android

我正在学习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;
    }

在上面的代码中,我尝试下载文件并将其命名为&#34; file.txt&#34;,但得到异常&#39; FileNotFoundException file.txt打开失败:EROFS(只读文件系统)& #34;,我需要在内部保存它(我不想让用户在文件浏览器中看到这个文件)并重写文件(如果存在)。 我尝试执行此任务并读取文件

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();
    }
}

1 个答案:

答案 0 :(得分:3)

所以下载到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();
                }