Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查目录文件是否存在?_Java_Android_File - Fatal编程技术网

Java 如何检查目录文件是否存在?

Java 如何检查目录文件是否存在?,java,android,file,Java,Android,File,我正在开发一个将图像下载到用户手机上的应用程序。下载部分工作正常,图像存储在“/Android/data//files/”我首先检查文件是否存在,如果不存在,我想下载它。但是,当我运行应用程序时,它会不断抛出一个NullpointerException。这是因为“/Android/data//files/”在第一次运行时不存在吗?如果是,我如何解决这个问题 protected void onCreate(Bundle savedInstanceState) { super.onCreat

我正在开发一个将图像下载到用户手机上的应用程序。下载部分工作正常,图像存储在“/Android/data//files/”我首先检查文件是否存在,如果不存在,我想下载它。但是,当我运行应用程序时,它会不断抛出一个
NullpointerException
。这是因为“/Android/data//files/”在第一次运行时不存在吗?如果是,我如何解决这个问题

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testtv = (TextView) findViewById(R.id.testtv);
    String imagename = "/img11.png";
    File image = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath()
            + "/Android/data/com.id.imagedownloader/files" + imagename);
    // testtv.setText(image.toString());

    if (image.exists()) {
        testtv.setText("file exists");
    } else {
        Boolean result = isDownloadManagerAvailable(getApplicationContext());
        if (result) {
            downloadFile(imagename);
        }
    }

}

@SuppressLint("NewApi")
public void downloadFile(String imagename) {
    // TODO Auto-generated method stub
    String DownloadUrl = "http://testing16.comlu.com/images/" + imagename;
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(DownloadUrl));
    request.setDescription("sample file for testing"); // appears the same
                                                        // in Notification
                                                        // bar while
                                                        // downloading
    request.setTitle("Test Title");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    String fileName = DownloadUrl.substring(
            DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
    request.setDestinationInExternalFilesDir(getApplicationContext(), null,
            fileName);

    // get download service and enqueue file
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);

}

public static boolean isDownloadManagerAvailable(Context context) {
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName("com.android.providers.downloads.ui",
                "com.android.providers.downloads.ui.DownloadList");
        List<ResolveInfo> list = context.getPackageManager()
                .queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    } catch (Exception e) {
        return false;
    }
}

将下载文件的本地目标设置为应用程序外部文件目录中的路径

request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_DOWNLOADS,image);

如果父文件夹不存在,请不要忘记使用mkdirs()创建目录

setdestinationnexternalfilesdir
需要dirType参数。您应该像这样使用它:

request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS,
        fileName);

使用此函数,您可以从字节数组创建一个文件,并检查该文件是否存在。试着这样做:

/**
 * Create new file from byte array
 * @param path  
 * @param array source
 * @throws IOException  
 */
public static void writeFile(String path, byte[] array) throws IOException {
    File file = new File(path);
    if (!file.exists() && array != null) {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(array);
        bos.flush();
        bos.close();
    } else {
        // the file exists...

    }
}

希望它能帮助你

也许
try{…}catch(IOException e){…}
异常不是来自方法downloadFile吗?com.id.imagedownloader.MainActivity.downloadFile(MainActivity.java:63),因此,如果您在外部存储中设置了目标,请确保该文件夹存在,那么这应该可以工作(至少从我看到的情况来看)它不保证外部存储存在可能是您忘记获取访问外部存储的权限了吗<代码>@wns349我在测试下载功能时添加了该权限。我刚刚在运行CM11的GS3上测试了我的代码,它工作正常。它只在模拟器中崩溃。为什么?如果您尝试将文件保存在外部存储中,它可能会崩溃。您可以添加logcat跟踪吗?
/**
 * Create new file from byte array
 * @param path  
 * @param array source
 * @throws IOException  
 */
public static void writeFile(String path, byte[] array) throws IOException {
    File file = new File(path);
    if (!file.exists() && array != null) {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(array);
        bos.flush();
        bos.close();
    } else {
        // the file exists...

    }
}