java IO总结之字节流操作文件读写(高效)

来源:互联网 发布:it occured that 编辑:程序博客网 时间:2024/06/06 03:12
package com.java;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class IOTest3 {/** * 字节流操作文件读写(高效) */public static void main(String[] args) {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(new FileInputStream("from.txt"));bos = new BufferedOutputStream(new FileOutputStream("to.txt"));// 单个字符的循环输入输出oneWordIO(bis, bos);// 一行一行循环输入输出oneLineIO(bis, bos);} catch (IOException e) {e.printStackTrace();} finally {try {bos.close();bis.close();} catch (IOException e) {e.printStackTrace();}}}/** * 一行一行循环输入输出 */private static void oneLineIO(BufferedInputStream in,BufferedOutputStream out) throws IOException {byte[] buf = new byte[1024];int len = -1;while ((len = in.read(buf)) != -1) {out.write(buf, 0, len);out.flush();}}/** * 单个字符的输入输出 */private static void oneWordIO(BufferedInputStream in,BufferedOutputStream out) throws IOException {int ch = -1;while ((ch = in.read()) != -1) {out.write(ch);out.flush();}}}

0 0