在Android中进行文件读写操作可以使用FileInputStream和FileOutputStream。
Android中文件读写的原理:
(1)所有文件的存储都是以字节的方式存储。
(2)磁盘中存储的并不是文件的字符,而是将字符编码成字节,再存储到磁盘。
(3)在读取文件时,是一个字节一个字节的读取以形成字节序列。
文件读写的步骤:
(1)建立通道。
(2)定义存储空间。
(3)读写数据。
(4)先执行flush()方法,然后关闭流。
输入流与输出流:
(1)程序从输入流读取数据。
(2)程序向输出流写数据。
实例代码:
//建立通道对象
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
Log.d(TAG, "readUDiskDevsList: "+temp.getName()+"复制成功");
//定义存储空间
byte[] b = new byte[1024 * 5];
//开始读文件
int len;
while ((len = input.read(b)) != -1) {
//将b中的数据写入到FileOutputStream对象中
output.write(b, 0, len);
}
//关闭流
output.flush();
output.close();
input.close();
实现将文件夹中的文件复制到另一个路径,oldPath->newPath
private void readUDiskDevsList(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
//读取文件夹中的文件,以字节流的方式
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
//建立通道对象
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
Log.d(TAG, "readUDiskDevsList: "+temp.getName()+"复制成功");
//定义存储空间
byte[] b = new byte[1024 * 5];
//开始读文件
int len;
while ((len = input.read(b)) != -1) {
//将b中的数据写入到FileOutputStream对象中
output.write(b, 0, len);
}
//关闭流
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {//如果是子文件夹
readUDiskDevsList(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
Toast.makeText(this, "copy完成,请拔出U盘", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}