分享一个自己利用学的IO流操作封装了一个小工具进行文件复制剪切和删除功能

利用最近学的I/O流的知识做的这个工具。

本人学JAVA一个月了,肯定代码里有缺陷不足,希望高手能指点指点,共同进步。代码如下:

package com.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileManager {
	/**
	 * 复制一个文件
	 * @param f 传入要复制的文件对象
	 */
	public void copyNewFile(File f){
		
		this.mkDir(f);
		this.mkFile(f);
	}
	/**
	 * 剪切一个文件
	 * @param f 传入要剪切的文件对象
	 */
	public void cutFile(File f){
		this.copyNewFile(f);
		this.delFile(f);
	}
	/**
	 * 删除文件 
	 * @param f 传入要删除的文件对象
	 */
	public void delFile(File f){
		if(f.isDirectory()){
			File[] fs=f.listFiles();
			for (int i = 0; i < fs.length; i++) {
				this.delFile(fs[i]);
			}
		}
		f.delete();
	}
	/**
	 * 创建复制文件的目录
	 * @param f 传入要复制的文件对象
	 */
	private void mkDir(File f){
		if(f.isDirectory()){
			String path=f.getPath();
			File nf=new File("e"+path.substring(f.getPath().indexOf(":")));
			
			File[] list=f.listFiles();
			for (int i = 0; i < list.length; i++) {
				this.mkDir(list[i]);
			}
			nf.mkdirs();
		}
	}
	/**
	 * 创建复制文件的所有文件
	 * @param f 传入要复制的文件对象
	 */
	private void mkFile(File f){
		if(f.isFile()){
			String path=f.getPath();
			File nf=new File("e"+path.substring(f.getPath().indexOf(":")));
			
			this.copyFile(f, nf);
		}else{
			File[] fs=f.listFiles();
			for (int i = 0; i < fs.length; i++) {
				this.mkFile(fs[i]);
			}
			
		}
	}
	/**
	 * 复制指定的文件
	 * @param oldFile 复制原文件对象
	 * @param newFile 复制后的新文件对象
	 */
	private void copyFile(File oldFile,File newFile){
		DataInputStream din=null;
		DataOutputStream dout=null;
		try {
			din=new DataInputStream(new BufferedInputStream(new FileInputStream(oldFile)));
			
			dout=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
			
			byte[] bt=new byte[1024];
			int len=0;
			try {
				while((len=din.read(bt, 0, bt.length))!=-1){
					
					dout.write(bt, 0,len );
					dout.flush();
					
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				din.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				dout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值