读写SD卡上文件的步骤:
1.调用Environment的getExternalStorageState() 方法判断手机上是否插入了SD卡,并且应用程序具有读写权限
如:
//如果手机已插入SD卡,且应用程序具有读写SD卡的能力,下面语句返回true
Environment.getExternalstorageState().equals(Environment.MEDIA_MOUNTED)
2.调用Environment的getExternalStorageDirectory()方法来获取外部存储器,也就是SD卡的目录
3.判断要读写的文件所在目录是否存在,判断要读写的文件是否存在,若不存在则创建
4.使用FileInputStream,FileOutputStream,FileReader或FileWriter读,写SD卡里的文件
5.在 AndroidManifest.xml 中添加SD卡的读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
代码如下:
public class WriteReadFileAPI
{
public static void write(String directory, String fileName, String content)
{
try
{
//如果手机插入了SD卡,而且应用程序具有访问SD的权限
if(Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED))
{
//获取SD卡根目录
File sdCardDir = Environment.getExternalStorageDirectory();
String directory_full_path = sdCardDir.getCanonicalPath()+"/"+directory;
String file_full_path = sdCardDir.getCanonicalPath()+"/"+directory+"/"+fileName;
createDir(directory_full_path);
createFile(directory_full_path, fileName);
File targetFile = new File(file_full_path);
System.out.println(file_full_path);
//以指定文件创建RandomAccessFile对象
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
//将文件记录指针移动到最后
raf.seek(targetFile.length());
//输出文件内容
raf.write(content.getBytes());
raf.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static String read(String directory, String fileName )
{
try
{
//如果手机插入了SD卡,而且应用程序具有访问SD的权限
if(Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED))
{
//获取SD卡根目录
File sdCardDir = Environment.getExternalStorageDirectory();
String file_full_path = sdCardDir.getCanonicalPath()+"/"+directory+"/"+fileName;
System.out.println(file_full_path);
//获取指定文件对应的输入流
FileInputStream fis = new FileInputStream(file_full_path);
//将指定输入流包装成BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder("");
String line = null;
while((line = br.readLine()) != null)
{
sb.append(line);
}
return sb.toString();
}
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return null;
}
public static void createFile(String path,String filename) throws IOException
{
File file=new File(path+"/"+filename);
System.out.println(path);
System.out.println(filename);
System.out.println(path+"/"+filename);
if(!file.exists())
file.createNewFile();
}
public static void createDir(String path){
File dir=new File(path);
if(!dir.exists())
dir.mkdir();
}
}