基本流程
- 创建File对象
- 创建FileInputStream或FileOutputStream对象
- 读取数据或写入数据
- 关闭流
注意
- 可以处理文本文件
- 读取中文时,一个中文可能占用多个字节,使用数组作为缓冲时,可能只有中文一部分读取到了数组中,另一部分还没有读取,打印时可能会乱码,复制不会出现问题
- 使用构造器
FileOutputStream(file)写出操作会覆盖原本的文件内容,需要使用FileOutputStream(file,true)才会在文件末尾追加
FileInputStream fis = null;
File file = null;
try {
file = new File("hello.txt");
fis = new FileInputStream(file);
byte [] buffer = new byte[4];
int len;
while((len = fis.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(fis!=null){
fis.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
/*
原文:hello好 new world
输出: hello�� new world
*/
复制图片
File file = null;
File file1 = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
file = new File("pic1.jpg");//原图片
file1 = new File("pic2.jpg");//目的图片,可以不存在
fis = new FileInputStream(file);
fos = new FileOutputStream(file1);
byte []bbuf = new byte[100];//每次读取100字节
int len;
while((len = fis.read(bbuf))!=-1){
fos.write(bbuf,0,len); //写入到目的文件中
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (fis!=null) {
System.out.println("关闭输入流");
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null){
System.out.println("关闭输出流");
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
复制文件函数
public void copyFile(String srcPath,String destPath){
File src = null;
File dest = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
src = new File(srcPath);
dest = new File(destPath);
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
byte [] buffer = new byte[1024];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
close(fis, fos);
}
}
static void close(FileInputStream fis, FileOutputStream fos) {
try {
if (fis!=null) {
System.out.println("关闭输入流");
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null){
System.out.println("关闭输出流");
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}