2017-01-25 8 views
0
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; 
     } 

をsubstringメソッドを使用するためにどのように私のparam変数が「http://ledeveloper.in/ep123BCA.pdf」であるURLリンクが含まれていますし、私は「ep123BCA.pdf」をしたいというurl..the希望の文字列をカットします。Javaで文字列配列を

しかし、私はこのコードを実行すると、部分文字列メソッドは常に私にその問題を解決する方法を別のサブ文字列を与えるでしょう。

事前に助けてください。

+1

分割メソッド 'String [] parts = url.split("/");' 3または4部分に分割します。最後はファイル名です。これは片方向です –

+0

は私のために働いていませんダウンロードしたファイルのガベージ名と同じものが表示されます。 : –

答えて

2

使用lastIndexOf URLからファイル名を取得します

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

あなたがこれを使用することができます。 (URLの最初の部分は変更されない場合)

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

別の解決策は、これは、文字列をこのように分割する必要があります

a.substring(22) 

です:

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

解決策ですが、十分に柔軟ではありません –

+0

これは確かに正しいです:) – Lagoni

+0

ファイルのガベージ名を指定します。 –

0
String url = "http://ledeveloper.in/ep123BCA.pdf"; 
     String file = url.substring(url.lastIndexOf('/')+1); 
0
filename = a.substring(a.lastIndexOf("/")+1); 

このあなたのコードに置き換えてください。