IO小练习 ---- 文件拷贝

来源:互联网 发布:开源平台系统源码 编辑:程序博客网 时间:2024/04/30 05:24
功能要求:
使用文件输入输出字节进行文件拷贝
需求说明:
在项目中定义一个old.txt文件,然后加入一些数据
使用文件输入输出字节类将old.txt文件内容读取后写入 new.txt文件中




import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileCopy {public static void main(String[] args) throws IOException {String oldfile = "d:/old.txt"; // 旧文件路径String newfile = "d:/new.txt"; // 新文件路径// 创建一个file文件File file = new File(oldfile);// 通过文件路径创建FileOutputStream(字节文件输出流)FileOutputStream out = new FileOutputStream(file);// 然后将字符写入文件out.write('l');out.write('o');out.write('v');out.write('e');// 关闭字节文件输出流out.close();// 通过文件路径创建FileInputStream(字节文件输入流)FileInputStream in = new FileInputStream(file);// 循环读取文件中的内容for (int i = 0; i < file.length(); i++) {System.out.print((char)in.read());}// 通过新文件路径创建FileOutputStreamFileOutputStream fos = new FileOutputStream(newfile);// 定义byte数组byte[] b = new byte[1024 * 1024];int n = 0;// 循环读取 旧文件中的字节数据   到 byte数组里while ((n = in.read(b)) != -1) {fos.write(b, 0 ,n);// 然后写入此字节文件输出流}// 关闭流in.close();fos.close();}}



0 0