思维导图
字节流使用案例以及注释
public static void main(String[] args) {
try {
InputStream is = new FileInputStream(new File("com/summer/java/a.txt")); //定义输入流并设置文件的位置
OutputStream os = new FileOutputStream(new File("com/summer/java/b.txt")); //定义输出流并设置文件的位置
byte[] bytes = new byte[1024]; //选择用byte数组来进行流动作,可以任意设置大小
int len;
while((len = is.read(bytes)) != -1){ //读取为-1时文件输入完毕,len为数组节点的位置
os.write(bytes,0,len); //以数组写入,从0到len的节点位置
}
os.flush(); //强制刷新写入
is.close(); //关闭输入流
os.close(); //关闭输出流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流使用案例以及注释
public static void main(String[] args) {
BufferedReader reader = null; //定义一个字符输入流
BufferedWriter writer = null; //定义一个字符输出流
try {
File srcFile = new File("com/summer/java/a.txt"); //输入的文件地址
File targetFile = new File("com/summer/java/b.txt"); //输出的文件地址
InputStream is = new FileInputStream(srcFile); //字节输入流
OutputStream os = new FileOutputStream(targetFile); //字节输出流
reader = new BufferedReader(new InputStreamReader(is)); //利用InputStringReader将字节输入流转换为字符输入流
writer = new BufferedWriter(new OutputStreamWriter(os)); //利用InputStringReader将字节输出流转换为字符输出流
String temp;
while((temp = reader.readLine()) != null){ //temp为读取的每一行数据
System.out.println(temp);
writer.write(temp); //写入文件
writer.newLine(); //进入下一行
}
writer.flush(); //强制刷新写入
reader.close(); //关闭输入流
writer.close(); //关闭输出流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
同时I/O流也是使用装饰者设计模式最多的类,
可以自定义设置流的转换规则类,如下:
- 首先设置一个类继承FilterInputStream,下面是一个将所有大写转换为小写的装饰类
public class LowerCase extends FilterInputStream {
protected LowerCase(InputStream in) {
super(in);
}
public int read() throws IOException{
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException{
int result = super.read(b,offset,len);
for (int i = 0; i < offset + result; i++) {
b[i] = (byte) Character.toLowerCase((char)b[i]);
}
return result;
}
}
- 然后再到测试类中使用
public class InputTest {
public static void main(String[] args) {
int c;
try {
InputStream in =
new LowerCase(
new BufferedInputStream(
new FileInputStream("java_io/test.txt")));
while ((c = in.read()) >= 0){
System.out.print((char)c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意在使用装饰器时,自己写的类要包装在最外层