日期:2014-05-20 浏览次数:20854 次
BufferedReader in = new BufferedReader(new FileReader("test.data"));
String line = null;
boolean opStream = false;
while ((line = in.readLine()) != null)
{
boolean bool = .....
if (bool)
{
//开始截取文件
opStream = true;
}
if (opStream)
{
//TODO 想在此处做处理。 如果不能做到,请提供一个简单的demo。非常感谢。
}
if (!bool)
{
//停止截取文件
opStream = false;
}
}
另有一个API方法,
void read(InputStream in);
void read(Reader in);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedReader in = new BufferedReader(new FileReader("test.data"));
String line = null;
boolean opStream = false;
long size = 0;
while ((line = in.readLine()) != null) {
boolean bool = (size + line.getBytes() <= 1024); //假设让文件的前1k作为输入流
if (bool) {
bos.write(line.getBytes());
} else {
break;
}
}
in.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); //把bos的信息转成输入流
//可以用bis作为参数变成各种输入流,如
DataInputStream dis = new DataInputStream(bis);
...
------解决方案--------------------
上面在while的循环最后加上 size += line.getBytes().length; 否则size没有发生变化
------解决方案--------------------
另一个可以考虑的使用:RandomAccessFile 该类本身就已经实现了 InputStream 接口。
可以用 seek()进行快速定位,然后直接按照InputStream进行流式读取操作,控制好读取长度即可。
这种做法的好处是整个过程可以完全流式操作,不需要预先将部分数据全部读取到内存中。
如果想做的更完美点,可以自己封装一个LimitInputStream(InputStream is, int limit)类来限制读取长度。
这样的话总体上就是:
RandomAccessFile raf = new RandomAccessFile("文件");
raf.seek(起始位置);
LimitInputStream lis = new LimitInputStream(raf, 最大读取长度);
然后把lis给出去就行了。
------解决方案--------------------
java.nio.channels.FileChannel
MappedByteBuffer map(FileChannel.MapMode mode, long position, long size)
Maps the file into memory.
可以指定把一个文件的一部分加载入内存变成一个 ByteBuffer.而这个ByteBuffer基本上你可以当成输入流一样来读取其中的内容。