代码:
package com.example.sd;
import java.io.File;import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.example.sd.R;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button create;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private void setListener() {
create.setOnClickListener(this);
}
private void initView() {
create = (Button) findViewById(R.id.create);
}
@SuppressLint("SimpleDateFormat")
@Override
public void onClick(View v) {
if(v==create){
// 在SD卡上创建一个以当天日期命名的文件夹
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// 创建一个文件夹对象,赋值为外部存储器的目录
Calendar date=Calendar.getInstance();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
String name=format.format(date.getTime());
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + name;
File file = new File(path);
if (!file.exists()) {
// 若不存在,创建目录,可以在应用启动的时候创建
file.mkdirs();
Toast.makeText(this, "文件夹创建成功!",Toast.LENGTH_LONG).show();
System.out.println("path ok,path:" + path);
}
else {
Toast.makeText(this, "文件夹已经存在",Toast.LENGTH_LONG).show();
}
}
}
}
}
xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/create"
></ListView>
<Button
android:id="@+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/list"
android:text="创建文件夹" />
</RelativeLayout>
主配置清单中权限
<uses-permission
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />