【问题标题】:Download a text file on Android [duplicate]在 Android 上下载文本文件 [重复]
【发布时间】:2013-06-08 14:39:19
【问题描述】:

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

编辑:“将其保存在内存中”意味着不将其写入文件。

你会怎么做?

谢谢!

【问题讨论】:

  • 这不是重复的!

标签: android android-asynctask


【解决方案1】:

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

这是一个使用活动context的简单文件R/W。

编辑:根据您最近更改的问题,我在这里发布:

试试这段代码:

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方式。您希望如何阅读它取决于您。
  • 抱歉,我可能不够清楚 - 我的意思是不保存到 SD 卡/本地内存。
  • 没关系,看我更新的答案。
  • 不幸的是,这不会删除 .mhtml 文件中的字符,例如:From: X-Snapshot-Version: 1.0
【解决方案2】:

试试:

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

【讨论】:

    【解决方案3】:

    我做到了。只需打开与您的服务器的连接(如果它是 FTP 服务器,只需使用 Apache commons 中的 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();
          }
    

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2012-03-08
      相关资源
      最近更新 更多