java I/O策略及Strategy设计模式

此博客因课程要求而写,总结了3种Java I/O策略及Strategy设计模式。I/O策略包含Input和Output两部分,分别介绍了多种读写文件的方式;还阐述了Strategy设计模式的思想,通过接口和实现类实现不同策略写入文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Introduction

之前一直忘记了要更新博客,课程要求,所以在空闲时写下这篇博客。Lab5是改进程序性能,而程序的性能很大程度上和I/O有关系。所以这篇博客总结了3种I/O策略以及Strategy设计模式。

I/O策略

Input:

1.Reader:
File file=new File(文件路径);
FileReader fr=new FileReader(file);//新建一个FileReader对象。下面为不同的read方法,可以查看jdk手册深入了解。
在这里插入图片描述
本实验中我采用按行读取的策略,所以要利用Decorator设计模式将其包装为BufferedReader,即
BufferedReader in = new BufferedReader(fr);
in.readLine();//按行读取

2.Stream:
为上面的方法增加输入流使用。具体代码:
File file = new File (“文件路径”);
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
in.readLine();//同样调用readLine()进行按行读取,其他方法查看jdk手册了解。

3.RandomAccessFile:
我不知道他的具体原理,但是通过实验发现,他的性能还是比较好的。具体实现代码:
File file = new File(“文件路径”);
RandomAccessFile raf = new RandomAccessFile(file);
raf.readLine();//进行按行读取

Output

1.Writer:
与Reader相对应:
File file = new File(“文件路径”);
FileWriter fw = new FileWriter(file);
fw.write(String string);//将string写入相应文件中

2.Stream:
与Input同样类似
File file = new File(“文件路径”);
PrintWriter pw = new PrintWriter(new (BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))));//增加输出流
pw.write(String string);将string写入文件

3.Channel
具体原理不做过多解释,直接上代码:
File file = new File(“文件路径”);
ByteBuffer byteBuffer1 = ByteBuffer.allocate(1024);
FileOutputStream fos = new FileOutputStream(file);
FileChannel out = fos.getChannel();
byteBuffer1.put(string.getBytes());
byteBuffer1.flip();
while (byteBuffer1.hasRemaining()) {
try {
outChannel.write(byteBuffer1);
} catch (IOException e) {
System.out.println(“写入异常”);
}
}
byteBuffer1.clear();

Strategy设计模式

之前的实验并没有用到这种模式,由于Lab5要求,使用了这一种设计模式,并深刻理解到了这种设计模式的思想和好处。主要思想如下:
在这里插入图片描述Strategy是一个接口,里面有待实现的方法。下面的A和B是对Strategy的两种实现,利用不同的算法重写其中的方法,而Context是一个封装类,供客户端使用。有私有变量Strategy,通过构造器传入不同的实现(A或B)来采取不同的策略。理解起来比较容易,下面是其在实验5中的具体应用。以Output为例
首先实现Strategy接口:
在这里插入图片描述

只需要write方法写入内容和close方法关闭输入流即可。
然后是两个实现类A和B,不做过多赘述,只需要implements上述接口,然后按照不同思想实现write方法和close方法即可。
最后是客户端进行调用。对接口进行封装。
封装类OutContext:
在这里插入图片描述
通过传入不同的outStrategy来实现不同的策略,同样有write和close方法,具体实现delegate到具体的outStrategy去实现。
客户端代码:(kind为不同种类编号)
OutContext out;
if (kind == 1) {
out = new OutContext(new MyOutStream());
} else if (kind == 2) {
out = new OutContext(new MyWriter());
} else {
out = new OutContext(new MyOutBuffer());
}
即可实现不同策略写入文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值