2015-03-31 46 views
0

在我的應用程序中,我將從網址下載圖像並將其寫入外部存儲器。它適用於我測試過的3個設備中的2個,並且在3日失敗。前兩個是LG和聯想設備(未根據),第三個是聯想(根源)。現在,當我使用下面的代碼保存所有文件工作正常,在第一次2級的設備,但拋出:無法在某些設備中保存文件(圖像)

IOException異常:打開失敗:EINVAL(無效參數)

創建文件。我的文件名中沒有任何非法字符,如下所示。

InputStream in = connection.getInputStream(); 
newPath = path + "/" + fileNameMobile; 
File outFile = new File(newPath); 

if(!outFile.exists()) { 
    outFile.createNewFile(); // fails here 
} 
OutputStream out = new FileOutputStream(outFile); 
ImageHandler.copyFile(in, out); 
out.flush(); 
out.close(); 
in.close(); 

和NEWPATH是

/storage/sdcard0/com.rahil.ecat/_5577d1b953e54351a4a7132252c11304.jpg 

我不能準確地找到失敗的原因1臺設備上,並適用於其他2個設備。任何人有任何想法?在此先感謝

編輯:這是我如何得到fileNameMoblie:

String fileNameMobile = _url.substring(_url.lastIndexOf('/') + 1); 

,並獲取路徑,並通過它來如下功能:

​​

和這裏的不過outFile的結果.getAbsolutePath():

/storage/sdcard0/com.rahil.ecat/_5577d1b953e54351a4a7132252c11304.jpg 

編輯2:下面是完整的代碼:

類ImageTask

public class ImageTask extends AsyncTask<Void, String, Void> { 

private Context _Context; 
private String _token; 
private ImageView _imageView; 
private ProgressBar _pbar; 
private String _url; 
private HttpRequestHandler _hrh; 
private ImageType _type; 
private RoundedImageView _rImageView; 

public ImageTask(Context context, String token, ImageView imageView, RoundedImageView rImageView, ImageType type) { 
    this._Context = context; 
    _token = token; 
    _imageView = imageView; 
    _type = type; 
    _rImageView = rImageView; 
} 

@Override 
protected Void doInBackground(Void... voids) { 
    if(!_token.isEmpty()) 
    { 
     File sdCardRoot = Environment.getExternalStorageDirectory(); 
     File yourDir = new File(sdCardRoot, _Context.getPackageName()); 
     boolean found = false; 
     String[] tokenParts = _token.split("\\."); 
     String realToken = _token; 
     if(tokenParts.length == 2) 
     { 
      realToken = tokenParts[0]; 
     } 
     for (File f : yourDir.listFiles()) { 
      if (f.isFile()) { 
       String name = f.getName(); 

       if(name.contains(realToken)) 
       { 
        found = true; 
        if(Util.isMobile(name)) 
        { 
         publishProgress(yourDir.getPath() + '/' + name, "NULL"); 
        } 
        else 
        { 
         if(Util.hasActiveInternetConnection(_Context)) { 
          getUrl(); 
          if(!_url.isEmpty()) { 
           _hrh = new HttpRequestHandler(_url, _Context); 
           String fileName = _hrh.downloadImage(yourDir.getPath(), _token, true); 
           if (!fileName.isEmpty()) { 
            if(fileName.contains("-mob")) { 
             f.delete(); 
            } 
            publishProgress(fileName, "NULL"); 
           } else { 
            publishProgress("", "DEFAULT"); 
           } 
          }else { 
           publishProgress("", "DEFAULT"); 
          } 
         } 
         else 
         { 
          publishProgress("", "DEFAULT"); 
         } 
        } 
       } 
      } 
     } 
     if(!found) 
     { 
      if(Util.hasActiveInternetConnection(_Context)) 
      { 
       getUrl(); 
       if(!_url.isEmpty()) { 
        _hrh = new HttpRequestHandler(_url, _Context); 
        String fileName = _hrh.downloadImage(yourDir.getPath(), _token, false); 
        if (!fileName.isEmpty()) { 
         publishProgress(fileName, "NULL"); 
        } else { 
         publishProgress("", "DEFAULT"); 
        } 
       }else { 
        publishProgress("", "DEFAULT"); 
       } 
      } 
      else 
      { 
       publishProgress("", "DEFAULT"); 
      } 
     } 
    } 
    else 
    { 
     loadDefaultImage(); 
    } 
    return null; 
} 

@Override 
protected void onProgressUpdate(String... values) { 

    if(values[1].equals("DEFAULT")) 
    { 
     loadDefaultImage(); 
    } 
    else 
    { 
     loadImage(values[0]); 
    } 
} 

@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
private void loadImage(String path) 
{ 
    try { 
     Bitmap image = BitmapFactory.decodeFile(path); 
     if (image != null) { 
      if(_imageView != null) { 
       StreamDrawable sd = null; 
       if(_type == ImageType.BLUR) 
       { 
        sd = new StreamDrawable(image, 10, 10); 
        _imageView.setBackground(sd); 
       } 
       else if(_type == ImageType.NO_EFFECT) 
       { 
        _imageView.setImageBitmap(image); 
       } 
      } 
      else if(_rImageView != null) { 
       _rImageView.setImageBitmap(image); 
      } 
     } 
    } 
    catch(Exception ex) 
    { 
     loadDefaultImage(); 
    } 
} 

private void getUrl() 
{ 
    WebService ws = new WebService(_Context); 
    _url = ws.getImageUrlForScreenTypeAndToken(
      _token, 
      Util.getScreenType(_Context).name()); 
} 

private void loadDefaultImage() 
{ 
    if(_imageView != null) { 
     _imageView.setBackgroundResource(R.drawable.noimage); 
    } 
    else if(_rImageView != null) { 
     _rImageView.setBackgroundResource(R.drawable.noimage); 
    } 
} 
} 

類HttpRequestHandler

public class HttpRequestHandler { 

private String _url; 
private Context _Context; 
private ProgressDialog _dialog; 

public HttpRequestHandler(String url, Context context) { 
    _url = url; 
    _Context = context; 
} 

public String init_post(List<NameValuePair> nameValuePairs) { 
    String data = null ; 
    BufferedReader in = null; 
    try { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     HttpParams params = new BasicHttpParams(); 
     params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
     HttpConnectionParams.setConnectionTimeout(params, 10000); 
     HttpConnectionParams.setSoTimeout(params, 5000); 
     HttpClient httpclient = new DefaultHttpClient(params); 
     HttpPost httppost = new HttpPost(_url); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); 
     HttpResponse response = httpclient.execute(httppost); 
     data = parser(response.getEntity()); 

    } catch (Exception e) { 

    } 
    return data; 
} 

public String init() { 
    String data = null ; 
    BufferedReader in = null; 
    try { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     HttpParams params = new BasicHttpParams(); 
     params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
     HttpConnectionParams.setConnectionTimeout(params, 10000); 
     HttpConnectionParams.setSoTimeout(params, 5000); 
     HttpClient httpclient = new DefaultHttpClient(params); 
     HttpGet request = new HttpGet(); 
     URI website = new URI(_url); 
     request.setURI(website); 
     HttpResponse response = httpclient.execute(request); 
     data = parser(response.getEntity()); 
    } catch (Exception t) { 

     if(true) 
     { 
      String s = "asd"; 
     } 
    } 
    return data; 
} 

private String parser(HttpEntity entity){ 
    InputStream is = null; 
    String jsonParse = ""; 
    try { 
     is = entity.getContent(); 
     //BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     jsonParse = sb.toString(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return jsonParse; 
} 

public String downloadImage(String path, String token, boolean check) { 
    String newPath = ""; 
    try { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
       .permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     String fileNameMobile = _url.substring(_url.lastIndexOf('/') + 1); 
     if(check && token.equals(fileNameMobile)) 
     { 
      return newPath; 
     } 
     URL urlConnection = new URL(_url); 
     URLConnection connection = urlConnection.openConnection(); 

     InputStream in = connection.getInputStream(); 
     newPath = path + "/" + fileNameMobile; 
     File outFile = new File(newPath); 
     OutputStream out = new FileOutputStream(outFile); 

     ImageHandler.copyFile(in, out); 
     out.flush(); 
     out.close(); 
     in.close(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return newPath; 
} 
} 
+0

它看起來像文件名問題,即使你說不是。在再次創建文件之前請仔細檢查文件名。登錄 – Xjasz 2015-03-31 17:41:01

+0

@Xjasz這就是我所做的,我把它粘貼在我的日誌裏。這是完整的路徑,我看不到任何非法路徑,即使名稱有任何問題,爲什麼它只會在第三個設備上拋出錯誤? – 2015-03-31 17:45:59

+0

你最近怎麼樣?存儲位置是特定於設備的,所以如果你硬編碼/存儲/ sdcard0這可能是問題。 – GreyBeardedGeek 2015-03-31 17:51:08

回答

0

此權限。

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> 

此代碼。

InputStream in = connection.getInputStream(); 
String filepath = getFilesDir().toString() + "/MyCustomFolder/"; 
File imagesFolder = new File(filepath); 
if(!imagesFolder.exists()) 
    imagesFolder.mkdirs(); 
File outFile = new File(filepath + "FileName.jpg"); 
if(!outFile.exists()){ 
    OutputStream out = new FileOutputStream(outFile); 
    ImageHandler.copyFile(in, out); 
    out.flush(); 
    out.close(); 
    in.close(); 
}else{ 
    in.close(); 
} 
+0

在發佈之前已經做過,路徑已經存在。 – 2015-03-31 18:19:52

+0

然後我失去了什麼是這個設備?你想保存到SD卡嗎?刪除下劃線並縮短文件名稱。我知道你可以使用255個字符,但顯然抱怨。你應該嘗試保存一個名爲image.jpg的文件,如果這個文件不應該啓動該錯誤。 – Xjasz 2015-03-31 18:26:52

+0

這是聯想A516,它有4 GB的內置存儲,不允許保存任何東西,所以我不得不插入一個SD卡,以保存圖像在其他應用程序,如Viber等......這可能是它的原因? – 2015-03-31 18:37:15

相關問題