六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 32|回复: 0

InputStream的mark和reset方法测试

[复制链接]

升级  37.4%

217

主题

217

主题

217

主题

进士

Rank: 4

积分
687
 楼主| 发表于 2013-2-3 13:37:19 | 显示全部楼层 |阅读模式
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) {// 重设位置到4inputStream.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 = (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.5.6.7.8.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表