Home > Back-end >  java.io.FileNotFoundException: when trying to read excel file
java.io.FileNotFoundException: when trying to read excel file

Time:06-22

Hello I am trying to read and print all the cell values of an excel file using Apache POI library. This is my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button btn;
    String name = null;
    Uri uri = null;
    private static final int STORAGE_PERMISSION_CODE = 101;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                data.setType("*/*");
                data = Intent.createChooser(data, "Choose a file");
                launch_activity.launch(data);
            }
        });
    }

    ActivityResultLauncher<Intent> launch_activity = registerForActivityResult
            (new ActivityResultContracts.StartActivityForResult(),
                    new ActivityResultCallback<ActivityResult>() {
                        @Override
                        public void onActivityResult(ActivityResult result) {
                            if (result.getResultCode() == Activity.RESULT_OK) {
                                Intent data = result.getData();
                                Uri uri = null;
                                if (data != null) {
                                    uri = data.getData();
                                }
                                if (uri != null && uri.getScheme().equals("content")) {
                                    try (Cursor returnCursor = getContentResolver().query(uri, null, null, null, null)) {
                                        if (returnCursor != null && returnCursor.moveToFirst()) {
                                            name = returnCursor.getString(returnCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
                                        }
                                    }
                                }
                                if(name == null){
                                    if (uri != null) {
                                        name = uri.getPath();
                                    }
                                    int cut = 0;
                                    if (name != null) {
                                        cut = name.lastIndexOf('/');
                                    }
                                    if(cut != 1){
                                        if (name != null) {
                                            name = name.substring(cut   1);
                                        }
                                    }
                                }
                                String[] extension = null;
                                if (name != null) {
                                    extension = name.split("\\.");
                                }
                                if (extension != null && (extension[extension.length - 1].equals("xls") || extension[extension.length - 1].equals("xlsx")))
                                    checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
                                else if (extension != null) {
                                    Toast.makeText(MainActivity.this,extension[extension.length - 1] " file is not supported",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

    public static void readExcelFromStorage(Context context, String fileName) {
        InputStream fileInputStream = null;    
        try {
            try {
                fileInputStream = getContentResolver().openInputStream(uri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            // Create instance having reference to .xls/.xlsx file
            Workbook workbook = null;
            try {
                if (fileInputStream != null) {
                    workbook = new HSSFWorkbook(fileInputStream);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Fetch sheet at position 'i' from the workbook
            Sheet sheet = null;
            if (workbook != null) {
                sheet = workbook.getSheetAt(0);
            }

            // Iterate through each row
            if (sheet != null) {
                for (Row row : sheet) {
                    if (row.getRowNum() > 0) {
                        // Iterate through all the cells in a row (Excluding header row)
                        Iterator<Cell> cellIterator = row.cellIterator();

                        while (cellIterator.hasNext()) {
                            Cell cell = cellIterator.next();

                            // Check cell type and format accordingly
                            switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    Toast.makeText(context.getApplicationContext(), String.valueOf(cell.getNumericCellValue()),Toast.LENGTH_SHORT).show();
                                    break;

                                case Cell.CELL_TYPE_STRING:
                                       Toast.makeText(context.getApplicationContext(), cell.getStringCellValue(),Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        }
                    }
                }
            }
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    public void checkPermission(String permission, int requestCode)
    {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) {

            // Requesting the permission
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode);
        }
        else {
            Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode,
                permissions,
                grantResults);

         if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show();
                readExcelFromStorage(MainActivity.this, uri);
            } else {
                Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

AndroidManifest.xml

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

When I execute my code, I choose my desired excel file (which is inside my internal storage) and then I keep getting this error:

java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.example.uploadipaselectricdata/files/employee_details.xlsx: open failed: ENOENT (No such file or directory)

How do I fix this error? Please help.

I am testing this app on an actual android device

CodePudding user response:

If you are sure the path to the file is correct but still get such an exception, check whether the app has enough permissions to access that location. After all the OS claims that there is no such file, and you won't be able to fix that inside your application code.

CodePudding user response:

I'm not entirely sure what Excel's workbook wants, specifically FileInputStream or just InputStream, you can try opening using the URI the system returned with getContentResolver().openInputStream(uri) and try passing it instead (this is the data returned via Intent.getData().) That should work on API 30 and above as well.

  • Related