1 javaIO流—-文件拷贝🖨️
💡 通过IO流实现文件拷贝的思路: ①读取源文件 ②把读到数据写入新文件
1.1 图文解析
🌰 java IO流拷贝文件案例(字节流实现)
需求:将指定目录下的文件拷贝到另一个目录下
public class FileCopy {public static void main(String[] args) {// 任务要求:完成文件拷贝// 将E盘aba目录下的a.txt文件拷贝到 abb目录下FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;//定义路径String path1 = "E:/aba/a.txt";String path2 = "E:/abb/b.txt";try {// 创建对象fileInputStream = new FileInputStream(path1);fileOutputStream = new FileOutputStream(path2);// 读取文件// 定义一个字节数组,提高读取效率byte buf []= new byte[8];int readLend = 0;while ((readLend=fileInputStream.read(buf)) != -1){// 读取到后就写入path2,通过fileOutputStream写fileOutputStream.write(buf,0,readLend);}} catch (IOException e) {e.printStackTrace();}finally {try {if (fileInputStream == null){// 关闭输入流资源fileInputStream.close();}if (fileOutputStream == null){// 关闭输出流资源fileOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}}
