如果我们用字节流处理查看文本可能会出现乱码,而复制文本不会因为我们汉字是3个字节,我们byte容量不一定是3的倍数
import java.io.*;
public class TestInputOutput {
public static void main(String[] args) {
//跟字符流操作的步骤一样
TestInputOutput t=new TestInputOutput();
long st=System.currentTimeMillis();
t.test("D:\\mycode\\src\\千玺.jpeg","D:\\mycode\\src\\千玺2.jpeg");
long et=System.currentTimeMillis();
System.out.println("复制时间"+(et-st));//555
}
public void test(String p1,String p2){
//创建文件流
File srcF = new File(p1);
File desF = new File(p2);
//2.创建字节流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcF);
fos = new FileOutputStream(desF);
//复制过程
byte[] buf = new byte[5];//如果文件或者视频比较大的话我们可以调节数组大小
int tem;
while ((tem = fis.read(buf)) != -1) {
fos.write(buf, 0, tem);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
缓冲流最大的作用就是加快我们处理的速度
import java.io.*;
public class TestIo02 {
public static void main(String[] args) {
//字节缓冲流与字符流对比
TestIo02 t=new TestIo02();
long st=System.currentTimeMillis();
t.test("D:\\mycode\\src\\千玺.jpeg","D:\\mycode\\src\\千玺3.jpeg");
long et=System.currentTimeMillis();
System.out.println("复制时间"+(et-st));//10
}
public void test(String p1,String p2){
//创建文件流
File srcF = new File(p1);
File desF = new File(p2);
//2.创建字节流
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
fis = new FileInputStream(srcF);
fos = new FileOutputStream(desF);
//创建缓存流
bis=new BufferedInputStream(fis);
bos=new BufferedOutputStream(fos);
//复制过程
byte[] buf = new byte[5];//如果文件或者视频比较大的话我们可以调节数组大小
int tem;
while ((tem = bis.read(buf)) != -1) {
bos.write(buf, 0, tem);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//我们虽然打开了4个流但是我们外层的缓冲流关闭后内部文件流也关闭了
// 所以我们只需要关闭缓冲流就好
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
缓冲流中字符流就不写了都差不多
读写操作细节说一下
我们字符流用char一般长文本都填1024或者8192