如何从一个InputStream流中从指位置截取指定长度的流

lonelydreamsym 2010-07-13 08:09:09
java中,对于一个InputStream流,需要从中间的第n个字节开始,截取到第m个字节,如何处理?
...全文
1394 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
光头谠 2011-04-08
  • 打赏
  • 举报
回复
也在考虑这个问题。只能skip掉吗?
smileflyer 2010-07-14
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 superman1986 的回复:]

read(byte[] b, int off, int len)
将最多 len 个数据字节从此输入流读入字节数组。
[/Quote]

的确有这个问题。那应该考虑buffer
以下代码解决这个问题。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test {
private final static int BUFFER_SIZE = 10;
public static void main(String[] args) {
try {
int need2read = 22;
int probe = 0;
byte []data = new byte[BUFFER_SIZE];
FileInputStream fis = new FileInputStream("c:\\test.txt");
fis.skip(6);

while((probe<need2read/BUFFER_SIZE) && (fis.read(data)!=-1)) {
for(int i=0;i<data.length;i++) {
System.out.print((char)data[i]);
}
probe++;
}

//
int overage = need2read%BUFFER_SIZE;
if(overage != 0) {
int ir = fis.read(data,0,overage);
for(int i=0;i< ir;i++) {
System.out.print((char)data[i]);
}
}

fis.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}
superman1986 2010-07-13
  • 打赏
  • 举报
回复
read(byte[] b, int off, int len)
将最多 len 个数据字节从此输入流读入字节数组。
happysmhzp 2010-07-13
  • 打赏
  • 举报
回复
2楼正解
smileflyer 2010-07-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ctkqqq 的回复:]

这里API和源码例子
一个英文的,一个翻译的:
http://apicode.gicp.net/class.do?api=selectByfatherIndex&father=255
http://apicodecn.gicp.net/class.do?api=selectByfatherIndex&father=255
[/Quote]
ls的地址收藏了。
lonelydreamsym 2010-07-13
  • 打赏
  • 举报
回复
或者从一个文件的第n个字节截取到第m个字节
smileflyer 2010-07-13
  • 打赏
  • 举报
回复
可以的。

Test.java


public class Test {
public static void main(String[] args) {
try {
byte []data = new byte[10];
FileInputStream fis = new FileInputStream("c:\\test.txt");
fis.skip(6);
fis.read(data);
fis.close();

for(int i=0;i<data.length;i++) {
System.out.print((char)data[i]);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}


c:\test.txt

hello,world.wellcome.good job.


执行结果
output:

world.well


Good Luck.
ctkqqq 2010-07-13
  • 打赏
  • 举报
回复

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧