2016-04-14 2 views
0

私のコードはうまく動作し、イメージをsdカードにダウンロードしますが、私は自分のsdカードパスを定義したこの警告を受け取ります「ハードコードしないでください/ Environment.getExternalStorageDirectory()。ある、getPath()の代わりに.TEMP」「アンドロイド対ハードコードされたパスでsdカードパスを取得

@Override 
    protected String doInBackground(String... aurl) { 
     int count; 
     try { 
      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 
      int lenghtOfFile = conexion.getContentLength(); 
      Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/.temp");//.temp is the image file name 
      byte data[] = new byte[1024]; 
      long total = 0; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 
    } 

    protected void onProgressUpdate(String... progress) { 
     Log.d("ANDRO_ASYNC", progress[0]); 
    } 

問題は、私が提案された解決策を使用する場合、私は(私のダウンロードしたファイルの新しい名前を与えることはできません、です」 )

+0

OutputStreamの出力=新しいのFileOutputStream(新しいファイル(Environment.getExternalStorageDirectory()、 ".TEMP")は、getAbsolutePath()) – dex

答えて

1

ファイルとディレクトリを操作する場合は、文字列ではなくFileオブジェクトを使用する方が適切です。

File dir = Environment.getExternalStorageDirectory(); 
File tmpFile = new File(dir, ".temp"); 
OutputStream output = new FileOutputStream(tmpFile); 

環境の外部ストレージディレクトリに".temp"という名前のファイルを指すFileオブジェクトを作成します。ここでは、あなたが警告に対処できる方法です。次に、FileOutputStreamクラスの別のコンストラクタを使用して書き込み用に開きます。

あなたは(印刷用たとえば、)の代わりに文字列としてファイルのパスが必要な場合は、行うことができますあまりにも:

String tmpFileString = tmpFile.getPath(); 

それとも、将来的にjava.nio APIを使用することを決定し、Pathが必要な場合対象:

Path tmpFilePath = tmpFile.toPath(); 
+0

文字とパスの違いは何ですか? – abbie

+0

@abbie - 'String'は単なるテキストです。 'Path'オブジェクトは' java.nio' APIの一部です。あなたの目的のためには、おそらく 'File'が使うのが一番良いでしょう。引数として 'File'を渡す' FileOutputStream'を作成することができ、それはうまく動作します。 –

+0

私は "OutputStream output = new FileOutputStream("/sdcard/.temp ");" ** with ** "String tmpFile = new File(dir、" .temp ")。getPath();" – abbie

関連する問題