2015-03-31 52 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

相关问题