ITeye博客

文件的创建,删除,拷贝

china34420 · 2011-04-02 12:04 · Java · 编程语言 · Markdown

学到了就留个笔记吧。。。。。

package com.zkl.file;
/**
 * 示例
 * 文件的创建,删除,拷贝
 * @author zhuangkunliang
 * 
 */
import java.io.*;
public class FileAndFolderOperate {

	static FileAndFolderOperate ffo;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ffo = new FileAndFolderOperate();
		ffo.createNewFile("f_obj2.txt");
		ffo.deleteFile("f_obj2");
		
		String[] s = {"c:\\yd.exe","d:\\yd2.exe"};
		ffo.copyFile(s);
	}
	


	/**
	 * 创建文件
	 * @param fileName
	 * @return
	 */
	public boolean createNewFile(String fileName){
		if(fileName!=null){
			File f_obj = new File(fileName);
			try {
				if(f_obj.createNewFile()){
					return true;
				}else{
					System.out.println("文件已经存在");
					return false;
				}
			} catch (Exception e) {
				// TODO: handle exception
				return false;
			}
		}else{
			System.out.println("请输入需要删除的文件路径!");
		}
		return false;
	}//end createNewFile()
	
	/**
	 * 删除文件
	 * 删除文件夹时,文件夹必须为空的文件夹
	 * @param fileName
	 * @return
	 */
	public boolean deleteFile(String fileName){
		if(fileName != null){
			File f_obj = new File(fileName);
			try {
				if(f_obj.delete()){
					return true;
				}else{
					System.out.println("文件不存在");
					return false;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return false;
	}//end deleteFile()
	
	/**
	 * 拷贝文件
	 * @param args
	 */
	public void copyFile(String[] args){
		if(args.length!=2){
			System.out.println("请输入拷贝的源文件和目标文件路径");
		}else{
			try {
				File f_obj1 = new File(args[0]);
				File f_obj2 = new File(args[1]);
				if(!f_obj1.isFile()){
					System.out.println(args[0] + "文件不存在,无法拷贝");
				}else{
					FileInputStream fis = new FileInputStream(f_obj1);
					BufferedInputStream bis = new BufferedInputStream(fis);
					FileOutputStream fos = new FileOutputStream(f_obj2);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					int f_data;
					do{
						f_data = bis.read();
						if(f_data!=-1){
							bos.write(f_data);
						}
					}while(f_data!=-1);
					bis.close();
					bos.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("文件IO出错");
			}
		}
	}
	
	

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。