我在评论中使用代码将文件保存在目录文件夹中。此代码适用于带有SD卡的手机。
但是,如果我使用没有SD卡的手机,它会给IO例外。 如何在设备存储根目录中创建类似whatsapp的文件夹以保存图像等,但我想要一个应用程序名称文件夹,以便在我的设备存储根目录中保存.csv文件。
答案 0 :(得分:1)
首先确保在Manifest中添加了“存储权限”
public class SettingsActivity extends AppCompatActivity {
public static final String PHONE_NUMBER_KEY = "PHONE_NUMBER";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = ((Toolbar) findViewById(R.id.toolbar_settings));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.settings_title);
}
}
如果要在 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
ExternalDirectory
如果要在内部存储中创建文件
File f = new File(Environment.getExternalStorageDirectory()+"/foldername");
if(!f.exists()) f.mkdir();
答案 1 :(得分:0)
您可以在内部存储和外部存储中创建目录,如下所示。
//check whether Sdcard present or not
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
// yes SD-card is present
String directory = "/your Directory name or app name ";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + directory;
File dir = new File(path);
if(!dir.exists()) //check if not created then create the firectory
dir.mkdirs();
//add your files in directory as follows
File file = new File(dir, filename);
}
else
{
// create folder in internal memory
File mydir = context.getDir(directory, Context.MODE_PRIVATE); //Creating an internal directry
if(!mydir.exists()) //check if not created then create the firectory
mydir.mkdirs();
//add your files in directory as follows
File file = new File(mydir, filename);
我希望它对你有用