0

I follow the video https://www.youtube.com/watch?v=MSgJJzhSI-A and try to create a Sheet, but no file are created, I notice that there is a Warning of createNewFile(): Result of File.createNewFIle() is ignored. How can I fix this?

private File filepath = new File(Environment.getExternalStorageDirectory()+"/AndroidExcelDemo/Demo.xls");

public void CreatSheet() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet hssfSheet = hssfWorkbook.createSheet();
        HSSFRow hssfRow = hssfSheet.createRow(0);
        HSSFCell hssfCell = hssfRow.createCell(0);
        hssfCell.setCellValue("Test1");
        try {
            if (!filepath.exists()) {
                filepath.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(filepath);
            hssfWorkbook.write(fileOutputStream);

            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){
                case R.id.menu_export:
                CreatSheet();
                return true;
}

I have

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" \>

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

in Manifest

Rob
  • 320
  • 1
  • 10
JuRuos
  • 1
  • 1
  • Static code inspection in your IDE might be complaining that createNewFile returns a boolean value which helps determine if the file is actually created or not. You've written`filepath.createNewFile();` and are not catching the response in any variable that's why IDE is giving you this warning. – Aman Apr 06 '22 at 09:25
  • A similar question was asked here specific to the problem you're facing with Android : https://stackoverflow.com/questions/62782648/android-11-scoped-storage-permissions – Aman Apr 06 '22 at 09:33
  • `if (!filepath.exists()) { if(! filepath.createNewFile()) return; }` Display a Toast too to inform the user when this happens. – blackapps Apr 06 '22 at 09:41
  • But.. you do not need to use createNewFile(). Remove that code. The new FileOutputStream will create the file. Put a Toast in that catch block so the user knows if there is a catch. – blackapps Apr 06 '22 at 09:44

0 Answers0