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();
}
}
}
java IO总结之字节流操作文件读写(高效)
最新推荐文章于 2024-07-31 21:34:18 发布