Java – FileNotFoundException failed to open : ENOENT (No such file or directory)

FileNotFoundException failed to open : ENOENT (No such file or directory)… here is a solution to the problem.

FileNotFoundException failed to open : ENOENT (No such file or directory)

I have a file called “and.doc” which contains a large number of records, each with this shape

Expression : defense ;

So I think

  • Read the file with a scanner
  • Use; as a separator
  • Find a way to separate the expression from the definition
  • And somehow add them to my Sqlite database (great if anyone knows how to do this).

I’m using this code

    try {

mf =new File("/home/agh/AndroidStudioProjects/Dicod/app/src/main/res/raw/and.doc");
        inputFile = new Scanner(mf);
        inputFile.useDelimiter(";" );
        while (inputFile.hasNext())
        {
            String x = inputFile.next();
            Toast.makeText(getApplicationContext(),x,Toast.LENGTH_LONG).show();

Splitting and adding to the databse

}

}

catch(FileNotFoundException e) {
        e.printStackTrace();
    }`

But I keep getting this error

06-23 04:38:28.771 23620-23620/? W/System.err: java.io.FileNotFoundException: /home/agh/AndroidStudioProjects/Dicod/app/src/main/res/raw/and.txt: open failed: ENOENT (No such file or directory)
06-23 04:38:28.771 23620-23620/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:465)
06-23 04:38:28.771 23620-23620/? W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)
06-23 04:38:28.771 23620-23620/? W/System.err:     at java.util.Scanner.<init>(Scanner.java:158)
06-23 04:38:28.772 23620-23620/? W/System.err:     at java.util.Scanner.<init>(Scanner.java:138)
06-23 04:38:28.772 23620-23620/? W/System.err:     at com.example.agh.dicod.MainActivity.onCreate(MainActivity.java:28)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.Activity.performCreate(Activity.java:5990)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.ActivityThread.access$800(ActivityThread.java:156)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.os.Looper.loop(Looper.java:211)
06-23 04:38:28.772 23620-23620/? W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5389)
06-23 04:38:28.772 23620-23620/? W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-23 04:38:28.772 23620-23620/? W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
06-23 04:38:28.772 23620-23620/? W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
06-23 04:38:28.772 23620-23620/? W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
06-23 04:38:28.772 23620-23620/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
06-23 04:38:28.773 23620-23620/? W/System.err:     at libcore.io.Posix.open(Native Method)
06-23 04:38:28.773 23620-23620/? W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
06-23 04:38:28.773 23620-23620/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:451)
06-23 04:38:28.773 23620-23620/? W/System.err:  ... 17 more

Solution

The file may not exist in the selected directory or READ_EXTERNAL_STORAGE permissions may not be granted.

Note that if you target API 23, you must request permissions at runtime, not just in a list.

http://developer.android.com/training/permissions/requesting.html

Related Problems and Solutions

Java – FileNotFoundException failed to open : ENOENT (No such file or directory) while uploading any type of file by Samsung devices

FileNotFoundException failed to open : ENOENT (No such file or directory) while uploading any type of file by Samsung devices… here is a solution to the problem.

FileNotFoundException failed to open : ENOENT (No such file or directory) while uploading any type of file by Samsung devices

I

wanted to upload a file to the server by selecting it from the file manager, so I opened the file manager with a click button using this code

 button_upload_attachment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String[] galleryPermissions = {android. Manifest.permission.READ_EXTERNAL_STORAGE, android. Manifest.permission.WRITE_EXTERNAL_STORAGE};

if (EasyPermissions.hasPermissions(CIBILCaptureandUPLOAD.this, galleryPermissions)) {

Intent intent = new Intent();
                intent.setType("*/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);
        } else {
                EasyPermissions.requestPermissions(this, "Access for storage",
                        101, galleryPermissions);
            }
        }
    });

With the onActivityResult method, I did something similar to get the path to the file and make the UploadToserver function available for upload

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    ImagesData = data;
    try {
         When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {

Uri contentUri=data.getData();
            Log.e("bbbbbbbbbbbbbb", contentUri.toString());

if(contentUri.toString().endsWith(".png")|| contentUri.toString().endsWith("jpg") ||
                    contentUri.toString().endsWith(".pdf")){

photoFile= new File(contentUri.getPath());

if (photoFile.exists()) {

Log.e("photoFile", "File Exists");
                }
                if (photoFile != null) {
                    new AsyncTask<String, String, File>() {
                        ProgressDialog pd;

@Override
                        protected void onPreExecute() {
                            pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
                            Log.e("PreExecute", "Compressing");
                        }

@Override
                        protected File doInBackground(String[] params) {
                            return photoFile;
                        }

@Override
                        protected void onPostExecute(File result) {
                            pd.dismiss();
                            if (result != null) {
                                new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
                            }
                        }
                    }.execute("");
                }

}else {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(contentUri,
                        filePathColumn, null, null, null);
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = "";
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(columnIndex);
                }
                Log.e("PATH", filePath);

photoFile = new File(filePath);

if (photoFile.exists()) {

Log.e("photoFile", "File Exists");
                }
                if (photoFile != null) {
                    new AsyncTask<String, String, File>() {
                        ProgressDialog pd;

@Override
                        protected void onPreExecute() {
                            pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
                            Log.e("PreExecute", "Compressing");
                        }

@Override
                        protected File doInBackground(String[] params) {
                            return photoFile;
                        }

@Override
                        protected void onPostExecute(File result) {
                            pd.dismiss();
                            if (result != null) {
                                new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
                            }
                        }
                    }.execute("");
                }
            }
        }

It works well

on other devices but works well on my Samsung device

 java.io.FileNotFoundException: /document/primary:Xender/other/When Strangers Meet_ 3 in 1 Box - John Harker.pdf: open failed: ENOENT (No such file or directory)

My upload code is

Private class UploadFileToServer extension AsyncTask {
private static final String TAG = “UploadFileToServer”;

    // private ProgressBar progressBar;
     private String filePath = null;
     private TextView txtPercentage;

private ProgressDialog pd;
    long totalSize = 0;

@Override
    protected void onPreExecute() {
         setting progress bar to zero
         progressBar.setProgress(0);
        pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Loading...");
        super.onPreExecute();
    }

@Override
    protected void onProgressUpdate(Integer... progress) {
         Making progress bar visible
         progressBar.setVisibility(View.VISIBLE);
         updating progress bar value
        pd.setMessage("Loading..." + progress[0]);
         progressBar.setProgress(progress[0]);
         updating percentage value
         txtPercentage.setText(String.valueOf(progress[0]) + "%");
    }

@Override
    protected String doInBackground(File... params) {
        return uploadFile1(params[0]);
    }

@SuppressWarnings("deprecation")
    private String uploadFile1(File file) {
        String responseString = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(AppUtill.URL_CIBIL_imageupload);
        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

@Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });
            File sourceFile = file;// new File(filePath);
            entity.addPart("image", new FileBody(sourceFile));
            entity.addPart("mid", new StringBody(memberid));
            entity.addPart("did", new StringBody("0"));
            entity.addPart("fid", new StringBody(formtypeid));

if (app_loadid == null) {
                SharedPreferences sharedPreferences = getSharedPreferences("LID", MODE_PRIVATE);
                app_loadid = sharedPreferences.getString("lid", "");
                entity.addPart("lid", new StringBody(app_loadid));
            } else {
                entity.addPart("lid", new StringBody(app_loadid));
            }

totalSize = entity.getContentLength();
            httppost.setEntity(entity);
             Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode +statusCode");
            if (statusCode == 200) {
                 Server response
                System.out.println("statusCode +statusCode");
                responseString = EntityUtils.toString(r_entity);
                String success = String.valueOf(responseString.contains("1"));

if (success.matches("true")) {
                    uploadedFileCount++;
                } else {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getApplicationContext(), "File not uploaded. Please upload again...", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } else {
                responseString = "Error occurred! Http Status Code: " + statusCode;
            }
        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }
        return responseString;
    }

@Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "Response from server: " + result);
        pd.dismiss();

if (uploadedFileCount == MAX_COUNT) {
            AlertDialog.Builder alert = new AlertDialog.Builder(CIBILCaptureandUPLOAD.this);
            alert.setTitle(R.string.app_name);
            alert.setMessage("Reach to max upload limit");
            alert.setCancelable(false);
            alert.setPositiveButton("OK", null);
            alert.create().show();
        }
         showing the server response in an alert dialog
        showAlert(result);
        AppUtill.deleteFolderAndAllFile(CIBILCaptureandUPLOAD.this);

super.onPostExecute(result);
    }
}

Solution

photoFile= new File(contentUri.getPath());

Looking at the value of contentUri.getPath(), it is not a valid file system path.

Instead, you should open an InputStream for the obtained uri and read the file contents from the stream.

InputStream is = getContentResolver().openInputStream(contentUri);

Related Problems and Solutions