无法在某些设备中保存文件(图像)

时间:2015-03-31 17:27:42

标签: android ioexception android-file

在我的应用程序中,我将从网址下载图像并将其写入外部存储。它适用于我测试过的3台设备中的2台,并且在第3台设备上发生故障。前两个是LG和联想设备(无根),第三个是联想(根)。现在,当我使用下面的代码保存文件时,前两个设备上的一切正常,但抛出:

IOException:open failed: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);

并获取路径并将其传递给以下功能:

File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, _Context.getPackageName());

这里是outFile.getAbsolutePath()的结果:

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

编辑2:以下是完整的代码:

Class 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);
    }
}
}

Class 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;
}
}

1 个答案:

答案 0 :(得分: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();
}