我对内部存储没有问题,但我想在外部SD卡上创建一个目录,其中包含KitKat之前的版本File.mkdirs()
。
我的部分代码是:
//external sd card
DocumentFile.fromFile(new File("/storage/sdcard1/")).exists(); //returns true
DocumentFile.fromFile(new File("/storage/sdcard1/")).canRead(); //returns true
DocumentFile.fromFile(new File("/storage/sdcard1/")).canWrite(); //returns true
DocumentFile.fromFile(new File("/storage/sdcard1/test")).exists(); //returns false
DocumentFile.fromFile(new File("/storage/sdcard1/")).createDirectory("test"); //returns null
//internal storage
DocumentFile.fromFile(new File("/storage/emulated/0/")).exists(); //returns true
DocumentFile.fromFile(new File("/storage/emulated/0/test")).exists(); //returns false
DocumentFile.fromFile(new File("/storage/emulated/0/")).createDirectory("test"); //it works
DocumentFile.fromFile(new File("/storage/emulated/0/test")).exists(); //returns true
DocumentFile.fromFile(new File("/storage/emulated/0/test")).createFile("text", "file.txt"); //it works
//external sd card
(new File("/storage/sdcard1/test2/subfolder")).exists(); //returns false
(new File("/storage/sdcard1/test2/subfolder")).mkdirs(); //returns false
//internal storage
(new File("/storage/emulated/0/test2/subfolder")).exists(); //returns false
(new File("/storage/emulated/0/test2/subfolder")).mkdirs(); //returns true
在AndroidManifest.xml中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用BQ Aquaris e4,Android Lollipop 5.0和1GB micro SD卡进行测试。
更新:这是我获取卷列表的方式:
private static ArrayList<StorageInfo> listAvaliableStorage(Context context) {
ArrayList<StorageInfo> storagges = new ArrayList<>();
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
Class<?>[] paramClasses = {};
Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses);
getVolumeList.setAccessible(true);
Object[] params = {};
Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params);
if (invokes != null) {
StorageInfo info;
for (Object obj : invokes) {
Method getPath = obj.getClass().getMethod("getPath");
String path = (String) getPath.invoke(obj);
info = new StorageInfo(path);
File file = new File(info.getPath());
if ((file.exists()) && (file.isDirectory())
//&& (file.canWrite())
) {
info.setTotalStorage(file.getTotalSpace());
info.setFreeStorage(file.getUsableSpace());
Method isRemovable = obj.getClass().getMethod("isRemovable");
String state;
try {
Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
state = (String) getVolumeState.invoke(storageManager, info.getPath());
info.setState(state);
info.setRemovable((Boolean) isRemovable.invoke(obj));
} catch (Exception e) {
e.printStackTrace();
}
storagges.add(info);
}
}
}
} catch (NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
storagges.trimToSize();
return storagges;
}
硬编码路径仅适用于此示例
更新2: 我已经在SD卡中使用文件浏览器创建了目录:“test”。当我执行此代码时:
File file = new File("/storage/sdcard1/test/", "file.txt");
fileOutput = new FileOutputStream(file);
第二行抛出FileNotFoundException: /storage/sdcard1/test/file.txt: open failed: EACCES (Permission denied)
我做错了什么?
答案 0 :(得分:2)
这是由于Android Lollipop的设计。
Environment.getExternalStorageDirectory()
将仅返回模拟外部存储的路径。
Android不公开任何能为您提供SD卡路径的API。
此外,在Lollipop中,除非通过Storage Access Framework获得用户权限,否则应用程序无法写入sdcard中自己目录之外的位置。
试试context.getExternalFilesDirs()
。这会为您提供应用可以将数据写入的路径列表。其中一个将在SD卡中,并将像/ storage / sdcardname / Android / data / yourAppName / files
答案 1 :(得分:0)
你必须明确定义位置,这里是我创建文件夹和文件夹内的文件夹的短脚本,希望这有帮助
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DirectoryPicker extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooser_list);//your xml layout file name
}
@Override
public void onStart() {
super.onStart();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) { // **Check that we have access to create the folder(s)**
File Root = Environment.getExternalStorageDirectory(); //**Get the path and hold it**
//**Alternativly you can select a certain directory with**
//File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File folder = new File(Root.getAbsolutePath() + "/main_folder_to_add/second_folder/");//**This puts everything together CORRECTLY**
folder.mkdirs();//**Makes the directory folders, make sure to use mkdirs not mkdir**
if (!folder.exists()) {
folder.mkdirs();
}
Context context = getApplicationContext();//**Prove we were successful**
String msg = folder.toString();
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
return;
}
}
public void onBackPressed() {
finish();
}
}