java中对文件的读写操作

public class Demo {
	public static void main(String[] args) throws IOException{
		Demo demo = new Demo();
		String path1 = "D:/1.txt";
		String path2 = "D:/2.txt";
		demo.useZiJie(path1,path2);
//		demo.useZiJie_bf(path1,path2);
//		demo.useZiFu(path1,path2);
//		demo.useZiFu_bf(path1,path2);
	}
	
	
	
	//用字节流中的FileInputStream和FileOutputStream对文件进行读写
	public void useZiJie(String path1,String path2) throws IOException{
		FileInputStream  fis = new FileInputStream(path1);
		FileOutputStream fos = new FileOutputStream(path2);
		byte[] b = new byte[100];    //用来存取每次读入的数据,如果知道文件大小,直接将100改为文件的大小
		int len = 0;
		while((len=fis.read(b))!=-1){ //read(byte[])每次返回读入的个数,如果已经达到流的结尾,则为-1
			fos.write(b, 0, len);     //0: 从中开始编写字符的偏移量      len:要写入的字符个数
		}
		fos.close();                 //必须关闭,否则无法读写
		fis.close();
		System.out.println("OK!");
		
	}
	
	
	//用字节流中的BufferedInputStream和BufferedOutputStream对文件进行读写
	public void useZiJie_bf(String path1,String path2) throws IOException{
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path1));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path2));
		byte[] b = new byte[100];   //用来存取每次读入的数据,如果知道文件大小,直接将100改为文件的大小
		int len=0;
		while((len=bis.read(b))!=-1){//read(byte[])每次返回读入的个数,如果已经达到流的结尾,则为-1
			bos.write(b, 0, len);     //0: 从中开始编写字符的偏移量      len:要写入的字符个数
		}
		bis.close();                 //只要关闭最外层的流
		bos.close();
		System.out.println("OK!");
	}
	
	//用字符流中的FileWriter和FileReader对文件进行读写
	public void useZiFu(String path1,String path2) throws IOException{
		FileReader fr = new FileReader(path1);
		FileWriter fw = new FileWriter(path2);
		char[] c = new char[100];    //用来存取每次读入的数据,如果知道文件大小,直接将100改为文件的大小
		int len = 0;
		while((len=fr.read(c))!=-1){ //read(char[])每次返回读入的个数,如果已经达到流的结尾,则为-1
			fw.write(c, 0, len);     //0: 从中开始编写字符的偏移量      len:要写入的字符个数
		}
		fw.close();                 //必须关闭,否则无法读写
		fr.close();
		System.out.println("OK!");
	}
	
	//用字符流中的BufferedReader和BufferedWriter对文件进行读写
		public void useZiFu_bf(String path1,String path2) throws IOException{
			BufferedReader br = new BufferedReader(new FileReader(path1));
			BufferedWriter bw = new BufferedWriter(new FileWriter(path2));
			char[] c = new char[100];   //用来存取每次读入的数据,如果知道文件大小,直接将100改为文件的大小
			int len=0;
			while((len=br.read(c))!=-1){//read(byte[])每次返回读入的个数,如果已经达到流的结尾,则为-1
				bw.write(c, 0, len);     //0: 从中开始编写字符的偏移量      len:要写入的字符个数
			}
			br.close();                 //只要关闭最外层的流
			bw.close();
			System.out.println("OK!");
		}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值