java IO 简单应用

 
package com.hzq;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 文件输入输出流练习 分字节流和字符流 2010-05-11
 */
public class FileIO {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		File srcFile = new File("src.txt");// 源文件
		File copyFile = new File("copyFile.txt");// 复制后的文件

		// ****************************************
		// *********使用字节流复制文件的标准代码*********
		// *****************************************
		try {
			FileInputStream in = new FileInputStream(srcFile);
			FileOutputStream out = new FileOutputStream(copyFile);
			int b;
			while ((b = in.read()) != -1) {// 当等于-1时读到文章末尾
				out.write(b);
			}
			/*
			 * 关闭流
			 */
			out.close();
			in.close();

			// ****************************************
			// *********以下代码加上缓存以提高读写效率*********
			// *****************************************
			// 方法 一 用buffer 过滤
			BufferedInputStream iput = new BufferedInputStream(
					new FileInputStream(srcFile));
			BufferedOutputStream oput = new BufferedOutputStream(
					new FileOutputStream(copyFile));
			int c;
			while ((c = iput.read()) != -1) {
				oput.write(c);
			}
			/*
			 * 关闭流
			 */
			oput.close();
			iput.close();

			// 方法二自定义缓存
			FileInputStream in2 = new FileInputStream(srcFile);
			FileOutputStream out2 = new FileOutputStream(copyFile);
			int b2;
			byte[] buffe = new byte[512];// 缓存
			while ((b2 = in2.read(buffe)) != -1) {// 当等于-1时读到文章末尾
				out2.write(buffe);
			}
			/*
			 * 关闭流
			 */
			out2.close();
			in2.close();

			// ****************************************
			// *********使用字符流读写文本文件*************
			// *****************************************
			BufferedReader reader = new BufferedReader(new FileReader(srcFile));
			PrintWriter pw = new PrintWriter(copyFile);
			String line;
			while ((line = reader.readLine()) != null) {
				pw.write(line);
			}
			/*
			 * 关闭流
			 */
			pw.close();
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值