在Android上下载文本文件

时间:2013-06-12 13:04:09

标签: android android-asynctask

我需要从服务器下载文本文件,然后将其保存在内存中。然后一行一行地阅读。 更好的关闭 - 直接从服务器逐行读取。

编辑:'将其保存在内存中'表示不将其写入文件。

你会怎么做?

谢谢!

3 个答案:

答案 0 :(得分:7)

关于它的情况如何impossible?试试这段代码:请注意,创建文件的CONTEXT可以是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;
    }

这是一个简单的文件R / W,其中包含活动context

编辑:根据您最近更改的问题,我在此处发布此内容:

试试这段代码:

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) {
}

这应该有效

答案 1 :(得分:1)

尝试:

      String line;
      URL url = new URL("myserver.com/myfile.txt");    
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));    
      while ((line = in.readLine()) != null) {
          // do something with line
      }
      in.close();

答案 2 :(得分:0)

我这样做了。只需打开与服务器的连接(如果它是FTP服务器,只需使用Apache公共中的FTPClient)。将此连接设置为新的AsyncTask<...,...,...>,并将连接代码放入doInBackground(...)。 编辑:我是这样做的:

      FileOutputStream fos = activity.openFileOutput("temp.tmp", Context.MODE_PRIVATE);
      System.out.println(activity.getFilesDir().getAbsolutePath());
      client.enterLocalPassiveMode();
      client.changeToParentDirectory();
      client.changeWorkingDirectory("/dsct2c/" + username);
      client.retrieveFile(filename, fos);
      fos.close();
      publishProgress(activity.getString(R.string.toast_file_saved) + " " + filename);



      FileInputStream fis = activity.openFileInput("temp.tmp");
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader br = new BufferedReader(isr);

      String line = br.readLine();
      while(line != null)
      {
        publishProgress(line);
        System.out.println(line);
        line = br.readLine();
      }