Java文件操作

 Java文件操作操作的代码网上多如牛毛,看人家的代码始终不如看自己的代码,所以本人亲自自己写了一个,为了以后可以简单的参考一下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @文件的操作
 * @author 陈罗志
 *
 */
public class FileTest {
	
	public FileTest(){
		
	}
	//字节流,按字节读取和写入,效率非常低,可以使用BufferedInputStream 封装
	private FileInputStream fileInputStream;
	private FileOutputStream fileOutputStream;
	
	private File file ;
	
	//对文件内容的操作(字符流),可以使用 BufferedReader进行封装
	private FileReader fileReader;
	private FileWriter fileWriter;

	/**
	 * @文件的拷贝(字节流)然后删除
	 */
	public void copyFile(){
		String path_in="c:\\t.exe";
		String path_out="c:\\000t.exe";
		try {
			fileInputStream = new FileInputStream(path_in);
			fileOutputStream = new FileOutputStream(path_out);
						
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//建立缓冲区,一次读取8k数据
		byte[] b = new byte[8192];
		try {
			int byteReaded =fileInputStream.read(b);
			int i =0;
			while(byteReaded!=-1){
				//把缓冲区数据写入文件
				
				fileOutputStream.write(b,0,byteReaded);
				System.out.println("第"+(i++)+"次写入,写入数据长度为:"+byteReaded);
				byteReaded = fileInputStream.read(b);
			}	
			fileInputStream.close();
			fileOutputStream.close();

			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	
//		file = new File(path_out);
//		if(file.exists()){
//			file.delete();
//		}
		
	}
	
	/**
	 * @对文件夹内容的操作
	 */
	public void operateFile(){
		String str ="";
		try {
			//遍历次文件
			fileReader = new FileReader("c:\\test.txt");
			int ch = fileReader.read();
			while(ch!=-1){
				str=str+String.valueOf((char)ch);
				ch=fileReader.read();
			}
			System.out.println(str);
			
			//在文件最末端加上一些内容
			fileWriter = new FileWriter("c:\\test.txt",true);
			fileWriter.write("\n我是大笨蛋!");
			//要刷新缓冲区才会写入新文件
			fileWriter.flush();
			
			
			fileReader.close();
			fileWriter.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		FileTest fileTest = new FileTest();
		fileTest.copyFile();
		//fileTest.operateFile();
		
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值