我需要在根目录中创建 CAT_IMG 文件夹,并在列表视图中检索它。但是CAT_IMG文件夹没有在根目录中创建。我在清单文件中添加了权限。请帮我在根目录下创建一个文件夹。
private void createDirectoryAndSaveFile(Bitmap imageToSave) {
File direct = new File(getApplicationContext().getFilesDir() + "/CAT_IMG");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String fileName = "fav" + timeStamp + ".JPG";
if (!direct.exists()) {
File wallpaperDirectory = new File("/CAT_IMG");
wallpaperDirectory.mkdir();
}
File file = new File(new File("/CAT_IMG"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
createDirectoryAndSaveFile(photo);
Log.e("URI", data.getExtras().get("data") + "");
}
}
在列表视图中检索它的代码:
private void getImages() {
String[] filenames = new String[0];
File path = new File(getApplicationContext().getFilesDir() + "/CAT_IMG");// add here your folder name
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
photos.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", photos.get(i));
Name.add(filenames[i]);
//Sno.add(i); }
}
}
答案 0 :(得分:-1)
我在根目录中创建了一个文件夹,在上面的代码中做了很小的改动 `
private void createDirectoryAndSaveFile(Bitmap imageToSave) {
File direct = new File(getFilesDir() + "/CAT_IMG/");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String fileName = "fav" + timeStamp + ".JPG";
if (!direct.exists()) {
// File wallpaperDirectory = new File("/CAT_IMG");
direct.mkdir();
}
File file = new File(direct, fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
createDirectoryAndSaveFile(photo);
Log.e("URI", data.getExtras().get("data") + "");
}
}`