ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(buffer);
}
在循环中FileInputStream如何知道第二次该从1025读起,又没传位置进去。看了一下jdk源码,read是本地方法,不知道它底层是如何实现的?
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(buffer);
}
在循环中FileInputStream如何知道第二次该从1025读起,又没传位置进去。看了一下jdk源码,read是本地方法,不知道它底层是如何实现的?
解决方案 »
- J2SE 关于JPanel的页面跳转问题
- 求实现JTextPane/JEditorPane撤销回复功能的代码,最好功能强点的,先谢了
- 怎么会编译不同过呢
- 关于静态方法
- 请问为什么我的输出的GUI没有按钮和对话框?
- 想用JAVA写一个网络嗅探器,望大侠,指明一下学习方向
- 关于JAVA截取字符串
- 那能下载到java htmlelp docmentation
- java中如果不清楚具体文件名,比如只知道文件名的前缀字符串,能否获得以这个字符串为前缀的所有文件列表?
- 一个数组的问题。
- JAVA程序 输入数字 选择算法直接出结果 哪位大虾来解决下
- object landscapes and lifetimes
//小心溢出,如果文件太大的话
int locate = 0;
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
locate += r;
buffer.flip();
fcout.write(buffer);
}
FileOutputStream fout = new FileOutputStream(outfile);//目标文件
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
//假设fin中有2000个字节,循环中第一次读了1024个字节,第二次如何知道从1025读起???
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(buffer);
}
RandomAccessFile类同时实现了DataInput和DataOutput接口,提供了对文件随机存取的功能,利用这个类可以在文件的任何位置读取或写入数据。
RandomAccessFile类提供了一个文件指针,用来标志要进行读写操作的下一数据的位置。
可以去做类比.
FileOutputStream fout = new FileOutputStream(outfile);//目标文件
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
//小心溢出,如果文件太大的话
int location= 0;
while (true) {
buffer.clear();
//假设fin中有2000个字节,循环中第一次读了1024个字节,第二次如何知道从1025读起???
//每次都从location的位置读起,第一次为0(或者1,对这个函数不太熟悉),第二次则为1024(或者1025)
int r = fcin.read(buffer, location);
if (r == -1) {
break;
}
//在第一次循环完成后,location应当为1024
location+= r;
buffer.flip();
fcout.write(buffer);
}
当然你想看的话。在文件流支持的情况下,JDK中有相关的方法来定位流的位置的。
好像是
(int readlimit)
在此输入流中标记当前的位置
Supported()
测试此输入流是否支持 和 reset 方法。
reset()
将此流重新定位到对此输入流最后调用 方法时的位置。
skip(long n)
跳过和放弃此输入流中的 n 个数据字节。这几个方法可能对你解决这个问题有帮助。
private native int readBytes(byte b[], int off, int len) throws IOException;
int r = fcin.read(buffer, location);
现在是我不用指定location ,我发现也能从上次读到的位置又读下去,难道FileOutputStream本身有1个标记???
File file= new File(filename);
try {
InputStream is=new FileInputStream(file);
byte[] bs=new byte[1024];//一次要从文件中读去的长度,自已定义
is.read(bs, 0, bs.length);
System.out.println(new String(bs));
} catch (Exception e) {
e.printStackTrace();
}
}
public void readTxt2(String filename){
File file= new File(filename);
try {
InputStream is=new FileInputStream(file);
byte[] bs=new byte[1024];
int pos=0;//位置
while((pos=is.read(bs, 0, bs.length))!=-1){
is.read(bs, 0, pos);//pos是文件读到那个位置
System.out.println(new String(bs,0,pos));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ReadFile rf=new ReadFile();
rf.readTxt2("f:/readme.txt"); }}