gpt4 book ai didi

java - Android Studio : Can't write to external storage?

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:10 25 4
gpt4 key购买 nike

我知道,这个问题已经被问过一千次了,但没有一个解决方案对我有用......我只是想将数据保存到 SD 卡上的文件中。但首先,这是我的代码:

private static final String TAG="Logmessage";

public void save(){
String state=Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File dir=new File(Environment.getExternalStorageDirectory() + "/NewFolder");
if(!dir.exists()){
if (dir.mkdirs()){
Log.i(TAG,"Dir made");
}else{
Log.i(TAG,"Error: Dir not made");
}
}else{
Log.i(TAG,"Dir already exists");
}
File file=new File(dir,"file.txt");
try {
BufferedWriter bWriter = new BufferedWriter(new FileWriter(file));
bWriter.write("Hello World!");
bWriter.close();
}catch (IOException e){
Log.e("Exception","BufferedWriter");
}
}else{
Log.i(TAG,"External Drive not available");
}
}

当然我添加了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />在 list 文件中,但是当我运行应用程序时,日志消息始终为:Logmessage: Dir not madeException: BufferedWriter 。所以我想, list 文件中的条目没有“工作”,因为它甚至无法创建目录?

最佳答案

这段代码非常适合我:

String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
//then write file
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
//then write file
}

您可以使用File.separator代替“/”

如果外部不可用,此代码将默认在内部存储中创建相同的文件夹

关于java - Android Studio : Can't write to external storage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com