Java练习 通过IO流完成文件的移动和删除

Java练习 通过IO流完成文件的移动和删除
要求:通过文件的输出和输出(io流)进行文件的复制和剪切的过程
package com.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; //作业:定义一个工具类,可以实现文件的复制或移动(复制后删除)。 public class Test { public void copy(File file, File fileNew) { // 输出流 OutputStream os = null; // 输入流 InputStream is = null; try { // 创建新文件 fileNew.createNewFile(); // 输出流创建对象 os = new FileOutputStream(fileNew); // 输入流创建对象 is = new FileInputStream(file); // 读取的过程 byte[] b = new byte[1024]; int len = 0; while ((len = is.read(b)) > 0) { // 写的过程 os.write(b, 0, len); } // 清空流 os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } public void paste(File file, File fileNew) { copy(file, fileNew); //判断是都移动成功 if(fileNew !=null) { file.delete(); System.out.println("移动成功"); }else { System.out.println("移动没有成功"); } } }
本文作者:刘广法,转载注明出处。