“File.mkdirs()”的结果被忽略

2022-09-03 10:06:56

这是我的代码,其中的代码向我显示结果的警告被忽略。myDir.mkdirs();File.mkdirs()

我试图修复此警告,但我失败了。

   private void saveGIF() {
            Toast.makeText(getApplicationContext(), "Gif Save", Toast.LENGTH_LONG).show();
            String filepath123 = BuildConfig.VERSION_NAME;
            try {
                File myDir = new File(String.valueOf(Environment.getExternalStorageDirectory().toString()) + "/" + "NewyearGIF");enter code here

    //My Statement Code This Line Show Me that Warning

 myDir.mkdirs();

                File file = new File(myDir, "NewyearGif_" + System.currentTimeMillis() + ".gif");
                filepath123 = file.getPath();
                InputStream is = getResources().openRawResource(this.ivDrawable);
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] img = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
                while (true) {
                    int current = bis.read();
                    if (current == -1) {
                        break;
                    }
                    baos.write(current);
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
            mediaScanIntent.setData(Uri.fromFile(new File(filepath123)));
            sendBroadcast(mediaScanIntent);
        }

答案 1

该方法具有未使用的返回值。mkdirsboolean

 boolean wasSuccessful = myDir.mkdirs();

创建操作返回一个值,该值指示目录的创建是否成功。例如,结果值可用于在错误为 false 时显示错误。wasSuccessful

if (!wasSuccessful) { 
    System.out.println("was not successful."); 
}

来自 Java 文档中有关返回值的信息:boolean

当且仅当创建了目录以及所有必需的父目录时,才为 true;否则为假


答案 2
File CDir = new File(Environment.getExternalStorageDirectory(), IMPORT_DIRECTORY);
if (!CDir.exists()) {
    boolean mkdir = CDir.mkdir();
    if (!mkdir) {
        Log.e(TAG, "Directory creation failed.");
    }
}

mkdir 返回一个布尔值。我们需要从 mkdir 捕获返回值。将代码替换为此代码并检查(忽略 File.mkdirs() 结果的警告)将消失。


推荐