【问题标题】:How to use a SubString method with string array in java [duplicate]如何在java中使用带有字符串数组的SubString方法[重复]
【发布时间】:2017-06-10 13:27:44
【问题描述】:
class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            int count;
            String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" ;


            String[] fileName = params;
            String a = fileName.toString();
            String b = a.substring(20,25);
            destination+=b;


            try {

                URL url = new URL(params[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lengthofFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Length of file: " + lengthofFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(destination);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lengthofFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            return null;
        }

我的参数变量将包含 url 链接,即“http://ledeveloper.in/ep123BCA.pdf”,我想剪切那个 url..我想要“ep123BCA.pdf”的期望字符串。

但是当我运行这段代码时,子字符串方法总是会给我一个不同的子字符串来解决这个问题。

请提前帮助和thanx。

【问题讨论】:

  • 使用split方法String[] parts= url.split("/");将url分成3或4部分,最后一个是文件名,这是一种方式
  • 不适合我,因为它给了我下载文件的相同垃圾名称。 :(

标签: java android


【解决方案1】:

使用lastIndexOf 从 URL 中获取文件名:

String b = a.substring(a.lastIndexOf('/') + 1);

【讨论】:

    【解决方案2】:

    你可以用这个。

    fileName=a.substring(a.lastIndexOf("/")+1);
    

    【讨论】:

      【解决方案3】:

      另一种解决方案是(如果 url 的第一部分永远不会改变)

      a.substring(22)
      

      这应该以这种方式拆分字符串:

      the part cut out = http://ledeveloper.in/
      a = ep123BCA.pdf
      

      【讨论】:

      • 是一种解决方案,但不够灵活。
      • 那肯定是正确的:)
      • 给出文件的垃圾名称。
      【解决方案4】:
      String url = "http://ledeveloper.in/ep123BCA.pdf";
               String file = url.substring(url.lastIndexOf('/')+1);
      

      【讨论】:

        【解决方案5】:
        filename = a.substring(a.lastIndexOf("/")+1);
        

        此行替换为您的代码。

        【讨论】:

          猜你喜欢
          • 2016-06-15
          • 1970-01-01
          • 1970-01-01
          • 2013-05-21
          • 1970-01-01
          • 2018-03-29
          • 1970-01-01
          • 1970-01-01
          • 2014-11-04
          相关资源
          最近更新 更多