文件复制方法概述
流是一个有序的字节序列,可作为一个输入源,也可作为一个输出的目的地。 字节流以字节为单位输入输出,字节流类名含有stream,字符流以字符为
单位输入输出,字节流 类名含有reader或writer.为了通用性,java中字符是16位的unicode字符,所以8位的字节流必 须和16位的字符流进行转换。字节
流到字符流的转换使用InputStreamReader类:
public InputStreamReader(InputStream in);
public InputStreamReader(InputStream in,String encoding);
public OuputStreamWriter(OnputStream in);
public OnputStreamWriter(OnputStream in,String encoding);
Reader和Writer类允许用户在程序中无缝的支持国际字符集,如果要读区的文件是别国语言, 要使用字符流。
JavaI/O字节流与字符流就是java 实现输入/输出 数据 字节流是一个字节一个字节的输入/输出 数据 (两个字节组成一个汉字)所以在用字节流读一串汉
字时会出现乱码问题,
同样字符流是一个字符一个字符流(一个字符=两个字节)的输入/输出 数据 用字符流读一串汉字可以解决乱码问题. 字符流操作时使用了缓冲区,而 在
关闭字符流时会强制性地将缓冲区
中的内容进行输出,但是如果程序没有关闭,则缓冲区中的内容是无法输出的,所以得出结论:字符流使用了缓冲区,而字节流没有使用缓冲区。
四中代码实现
package it.cast1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFileDemo1 {
public static void main(String[] args) throws IOException {
// 创建文件输入流和文件输出流
FileInputStream stream = new FileInputStream("a.txt");
FileOutputStream stream2 = new FileOutputStream("E:\\b.txt");
//methed(stream, stream2);
//methed1(stream, stream2);
//methed2(stream, stream2);
//methed3(stream, stream2);
}
//高效字节流数字符数组读取
private static void methed3(FileInputStream stream, FileOutputStream stream2) throws IOException {
//高效字节流对象创建
BufferedInputStream bis=new BufferedInputStream(stream);
BufferedOutputStream bos= new BufferedOutputStream(stream2);
//新建数组放读取字节
byte [] arr = new byte [1024];
//读取文件放入字节数组
int read = 0;
while ((read=bis.read(arr))!=-1) {
//把字节数组写入复制的文件中
bos.write(arr, 0, read);
}
//关闭高效字节流
bis.close();
bos.close();
}
//字节数组读取复制文件
private static void methed2(FileInputStream stream, FileOutputStream stream2) throws IOException {
// 新建数组
int read = 0;
byte [] arr = new byte [1024];
//读取文件并把文件中每个字符存入数字
while ((read=stream.read(arr))!=-1) {
//把字节数组写入复制的文件中
stream2.write(arr, 0, read);
}
//关闭数据流
stream.close();
stream2.close();
}
//高效字節流复制文件
private static void methed1(FileInputStream stream, FileOutputStream stream2) throws IOException {
//创建高效字节输出流和输入流
BufferedInputStream bis=new BufferedInputStream(stream);
BufferedOutputStream bos= new BufferedOutputStream(stream2);
//读取
int read = 0;
while ((read = bis.read())!=-1) {
//写入复制
bos.write(read);
}
//关闭字节流
bis.close();
bos.close();
}
//字节流读取复制
public static void methed(FileInputStream stream, FileOutputStream stream2)
throws IOException {
// 读取文件
int read = 0;
while ((read = stream.read()) != -1) {
// 写去文件
stream2.write(read);
}
// 关闭数据流
stream.close();
stream2.close();
}
}