InputStream的mark和reset方法测试

本文提供了一个使用Java进行文件读写的示例程序。通过创建一个名为InputStreamTest的公共类,演示了如何将一系列字节写入文件以及如何从文件中读取这些字节,并展示了如何使用mark和reset方法来重新定位文件读取的位置。

public class InputStreamTest {
public static void main(String[] args) throws IOException {
writeToFile();
readFromFile();
}

private static void readFromFile() {
InputStream inputStream = null;

try {
inputStream = new BufferedInputStream(new FileInputStream(new File("test.txt")));

// 判断该输入流是否支持mark操作
if (!inputStream.markSupported()) {
System.out.println("mark/reset not supported!");
return;
}

int ch;
int count = 0;
boolean marked = false;
while ((ch = inputStream.read()) != -1) {
System.out.print("." + ch);

if ((ch == 4) && !marked) {
// 在4的地方标记位置
inputStream.mark(6);
marked = true;
}

if (ch == 8 && count < 2) {
// 重设位置到4
inputStream.reset();
count++;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

private static void writeToFile() {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(new File("test.txt")));
byte[] b = new byte[20];
for (int i = 0; i < 20; i++)
b[i] = (byte) i;
// 写入从0到19的20个字节到文件中
output.write(b);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


输出为:
.0.1.2.3.4.5.6.7.8[color=blue].5.6.7.8.5.6.7.8[/color].9.10.11.12.13.14.15.16.17.18.19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值