黑马程序员 java文件流的读写

---------------------- android培训java培训、期待与您交流! ----------------------

java文件流分为字节流和字符流,文件读写都是基于字符流和字节流

读取文件包含 InputStream和Reader

写文件包含 OutputStream 和Writer

如果文件类型为文本文件则使用Reader和Writer,如果文件类型为非文本文件则使用InputStream和OutputStream

如果文件很大,这时需要提高文件读写的效率,就要用到以Buffered为前缀,上面四种基类为后缀的类,如BufferedInputStream,BufferedReader,BufferedOutputStream,BufferedWriter,而这些类被称为它们的装饰类,以下是两个流读写的例子,分别是文本文件读写和非文本文件读写。

import java.io.*;

public class InputStreamDemo {

    public InputStreamDemo() {
    }

	public void writeToTxt(String fileName) throws Exception
		{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),"GBK"));
		String line=null;
    	while((line=br.readLine())!=null)
    	{
    		if(new String(line).equals("over"))
    			break;
    		bw.write(line);
    		bw.newLine();
    		bw.flush();
    	}
	}
	public void copyFile(String fileName,String fileName2){
		BufferedInputStream bis=null;
		BufferedOutputStream bos = null;
	try{
		 bis = new BufferedInputStream(new FileInputStream(fileName));
		 bos = new BufferedOutputStream(new FileOutputStream(fileName2));
		byte[] by = new byte[1024];
		int len=0;
		while((len=bis.read(by))!=-1)
		{
			bos.write(by,0,len);
		}
	}catch(IOException e)
	{
		new RuntimeException("文件读取有误");
	}
		finally{
			try{
					bis.close();
					bos.close();
			}catch(Exception e)
			{}
		}

	}

    public static void main(String [] args) throws Exception
    {
		InputStreamDemo id = new InputStreamDemo();
		id.copyFile("d:\\111.jpg","d:\\222.jpg");

    }
}


---------------------- android培训java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值