android 自动 创建文件夹,android - 如何在SD卡上自动创建目录
android - 如何在SD卡上自动创建目录
我正在尝试将文件保存到以下位置
directory and sub-directory但是我得到了例外java.io.FileNotFoundException
但是,当我把路径作为"/sdcard/"时,它的工作原理。
现在我假设我无法以这种方式自动创建目录。
有人可以建议如何使用代码创建directory and sub-directory吗?
15个解决方案
433 votes
如果您创建一个包装顶级目录的File对象,您可以调用它的mkdirs()方法来构建所有需要的目录。 就像是:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
注意:使用Environment.getExternalStorageDirectory()来获取“SD卡”目录可能是明智之举,因为如果手机出现了除SD卡以外的其他东西(例如内置闪存,则可能会更改) 苹果手机)。 无论哪种方式,您都应该记住,您需要检查以确保它实际存在,因为可能会移除SD卡。
更新:自API级别4(1.6)起,您还必须请求许可。 这样的事情(在清单中)应该有效:
Jeremy Logan answered 2019-04-03T13:02:01Z
57 votes
有同样的问题,只想添加AndroidManifest.xml也需要此权限:
Daniel answered 2019-04-03T13:02:34Z
39 votes
这对我有用。
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
在你的清单和下面的代码中
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Vijay Kumar A B answered 2019-04-03T13:03:14Z
22 votes
实际上我使用了部分@fiXedd的答案,它对我有用:
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it Image2.PNG
File file = new File(extStorageDirectory, "Image2.PNG");
确保使用mkdirs()而不是mkdir()来创建完整路径
Amt87 answered 2019-04-03T13:03:55Z
12 votes
使用API 8及更高版本,SD卡的位置已更改。 @ fiXedd的答案很好,但是为了更安全的代码,你应该使用Environment.getExternalStorageState()来检查媒体是否可用。 然后,您可以使用getExternalFilesDir()导航到所需的目录(假设您使用的是API 8或更高版本)。
您可以在SDK文档中内容。
Nick Ruiz answered 2019-04-03T13:04:34Z
8 votes
确保存在外部存储:[http://developer.android.com/guide/topics/data/data-storage.html#filesExternal]
private boolean isExternalStoragePresent() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
.show();
}
return (mExternalStorageAvailable) && (mExternalStorageWriteable);
}
Parth mehta answered 2019-04-03T13:05:02Z
6 votes
我遇到了同样的问题。 Android中有两种类型的权限:
危险(访问联系人,写入外部存储...)
正常(Android会自动批准普通权限,而Android用户需要批准危险权限。)
以下是在Android 6.0中获取危险权限的策略
检查您是否已获得许可
如果您的应用已获得许可,请继续正常运行。
如果您的应用尚未获得许可,请要求用户批准
在onRequestPermissionsResult中收听用户批准
这是我的情况:我需要写入外部存储。
首先,我检查一下我是否有权限:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
然后检查用户的批准:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
Syed Abdul Basit answered 2019-04-03T13:06:51Z
5 votes
我遇到了同样的问题,无法在Galaxy S上创建目录,但能够在Nexus和Samsung Droid上成功创建目录。 我如何修复它是通过添加以下代码行:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
Garima Srivastava answered 2019-04-03T13:07:18Z
5 votes
不要忘记确保文件/文件夹名称中没有特殊字符。 当我使用变量设置文件夹名称时,用“:”发生在我身上
不允许文件/文件夹名称中的字符
“* /:<>?\ |
你可能会发现这个代码在这种情况下很有帮助。
下面的代码删除所有“:”并用“ - ”替换它们
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
Praveen answered 2019-04-03T13:08:18Z
5 votes
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
这将在你的SD卡中创建一个名为dor的文件夹。然后获取eg- filename.json的文件,手动插入dor文件夹。 喜欢:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
&LT; uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/&gt;
并且不要忘记在清单中添加代码
jayant singh answered 2019-04-03T13:09:03Z
4 votes
//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
vikseln answered 2019-04-03T13:09:22Z
3 votes
刚刚完成Vijay的帖子......
表现
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
功能
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
用法
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
你可以检查错误
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
Ismael Di Vita answered 2019-04-03T13:10:05Z
3 votes
这将使sdcard中的文件夹具有您提供的文件夹名称。
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}
Shweta Chauhan answered 2019-04-03T13:10:34Z
1 votes
您可以使用/ sdcard /而不是Environment.getExternalStorageDirectory()
private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/";
File dbdir = new File(DB_PATH);
dbdir.mkdirs();
Peter Drinnan answered 2019-04-03T13:11:05Z
1 votes
ivmage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`
Vishnu Namboodiri answered 2019-04-03T13:11:27Z
android 自动 创建文件夹,android - 如何在SD卡上自动创建目录相关推荐
- android 7 创建文件夹,Android 在 res/layout 文件夹 下创建一个 子文件夹实例
Android 资源文件夹 Layout 文件夹 Layout 文件是存放Android的布局文件的资源文件夹,但是如果你想要在里面创建子文件夹,你会发现xml文件报错. 如何在Layout文件夹下方 ...
- android下创建文件夹和修改其权限的方法
原文:http://www.cnblogs.com/wanqieddy/archive/2011/12/28/2304906.html 由于工作的需要,今天研究了在android下创建文件夹和修改其权 ...
- 在Android下创建文件夹
<!-- @page { margin: 2cm } PRE { font-family: "DejaVu Sans" } P { margin-bottom: 0.21cm ...
- 【Unity3D小功能】Unity3D中在创建完项目后自动创建文件夹列表
推荐阅读 CSDN主页 GitHub开源地址 Unity3D插件分享 简书地址 我的个人博客 大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦. 一.前言 ...
- android手机内存创建文件夹,Android在内存问题中创建文件夹
我在内部存储器中为我的应用程序创建文件夹时遇到了一些问题.我正在使用这段代码: public static void createFoldersInInternalStorage(Context co ...
- java 当文件夹不存在时,自动创建文件夹
public static void main(String[] args) {// 可以是任意格式的文件String pathName = "D:\\img\\immm\\test2.tx ...
- android 恢复出厂 自动恢复文件夹,Android恢复出厂设置
恢复出厂设置核心代码:sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR")); 即发送一个广播,需要在And ...
- android air创建文件夹,安卓版Airdrop将上线:无需安装APP,轻松实现文件隔空投送...
iOS用户忠诚度高于Android,其中一个影响因素是苹果强大的生态环境.而在苹果生态圈中,用于文件无线传输的Airdrop必然占有重要的地位.相比之下,Android系统在这方面的体验就十分匮乏.为 ...
- linux 根据文件路径自动创建文件夹
[root@hadoop henhao]# file="hongrao/expedia/egencia/accountdim.txt" [root@hadoop henhao]# ...
- C++写日志源代码分析,可实现根据日期自动创建文件夹、日志分类、文件大小控制等
最近在做一个项目,使用C++写一个动态链接库(dll),里面需要有日志功能,于是参考网上的资料实现了C++写日志的功能.日志可以指定路径保存,也可以默认保存在当前可执行程序(exe)所在的文件夹.现在 ...
最新文章
- Plant Com:中科院遗传发育所白洋组开发定量检测宿主微生物组的HA-QAP技术(王二涛点评)...
- java动物园管理员_zookeeper动物园管理员学习笔记
- php 图片处理类,分享php多功能图片处理类
- win10安装misql8_Win10下免安装版MySQL8.0.16的安装和配置教程图解
- 4/7 SELECT语句:过滤(组合WHERE子句)
- DNN:DL讨论与DNN经典论文汇总
- 如何选择 WebClient HttpWebRequest HttpClient ?
- 【OpenCV 例程200篇】59. 非线性滤波—双边滤波
- Node.js 爬虫初探
- 模块化日常:开源库与私有库重名
- 2022危险化学品经营单位安全管理人员特种作业证考试题库及在线模拟考试
- 【SpringBoot】MultipartResolver文件解析器
- 夏雨老师:告诉你初学习平面设计需要什么条件
- 面对对象之差异化的网络数据交互方式--单机游戏开发之无缝切换到C/S模式
- SCDM 实例教程:基本几何建模
- 充分利用居室空间 让阳台尽显万种风情
- 新版本游戏试玩APP搭建教程,附上试玩APP源码
- b2g process 和nuwa process 通信
- 深度学习中Concat层和Flatten层作用
- 蓝桥杯单片机第十届省赛题程序实现