1.复制文本文件
import java.io.*;
/**
* 复制文本文件 (为操作方便本测试throws)
* 条件:此项目下有一个text文件
*/
public class CopyText {
public static void main(String[] args) throws IOException{
// 分析可知,可采用高效字符流来复制文件
// 创建高效字符输入流对象
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
// 创建高效字符输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("copy.txt"));
// 定义字符串来接收字符输入流读到的每一行数据
String line = null;
// 只要line不为空,说明还能读到数据
while ((line = br.readLine()) != null) {
// 将读到的一行数据,用字符输出流对象写入到copy.txt中
bw.write(line);
// 由于readLine()不返回换行符,需要手动添加
bw.newLine();
// 把缓冲区数据写入文件中
bw.flush();
}
// 关闭 输入流和输出流对象
br.close();
bw.close();
}
}
2.复制图片
import java.io.*; /** * 复制图片 (为操作方便 throws 异常) * 条件:此项目下有:test.jp * 分析:用BufferedInputStream 和 BufferedOutputStream */ public class CopyImage { public static void main(String[] args) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.jpg")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.jpg")); // 一般采用字节数组来做 byte[] bytes = new byte[1024]; int length; while ((length = bis.read(bytes)) != -1) { bos.write(bytes, 0, length); } bos.close(); bis.close(); } }