JAVA_IO_缓冲流

26 篇文章 0 订阅
1.字符缓冲流BufferedReader、BufferedWriter
package test.buffered;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 字符缓冲流 + 新增方法
 * @author WL20180732
 *
 */
public class BufferedCharDemo {
	public static void main(String[] args) {
		File src = new File("E:/test/a.txt");
		File dest = new File("E:/test/b.txt");
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			reader = new BufferedReader(new FileReader(src));
			writer = new BufferedWriter(new FileWriter(dest));
			String line = null;
			while (null != (line = reader.readLine())) {
				writer.write(line);
				writer.newLine(); // 换行符号
			}
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("源文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取失败");
		} finally {
			try {
				if (null != writer) {
					writer.close();
				}
			} catch (Exception e2) {
			}
			try {
				if (null != reader) {
					reader.close();
				}
			} catch (Exception e2) {
			}
		}
	}
}

2.字节缓冲流BufferedInputStream、BufferedOutputStream
package test.buffered;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 字节流文件拷贝 + 缓冲流 ,提高性能
 * @author WL20180732
 *
 */
public class BufferedByteDemo {

	public static void main(String[] args) {
		try {
			copyFile("E:/test/2.pdf", "E:/test/3.pdf");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void copyFile(String srcPath, String destPath) throws IOException {
		File src = new File(srcPath);
		File dest = new File(destPath);
		if (src.exists() && src.isFile()) {
			InputStream in = new BufferedInputStream(new FileInputStream(src));
			OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
			byte[] buffer = new byte[1024];
			int len = 0;
			while (-1 != (len = in.read(buffer))) {
				out.write(buffer);
			}
			out.flush();
			
			//关闭流
			out.close();
			in.close();
		} else {
			if (!src.exists()) {
				System.out.println(src + "文件不存在");
			} else if(!src.isFile()) {
				System.out.println(src + "不是文件");
			}
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值