RandomAccessFile的public int read(byte[] b,int off,int len) throws IOException也挺方便的
public class Test { public static void main(String[] args) { System.out.println(read(3,9)); } public static String read(int from ,int to){ String result=""; try{ FileInputStream fis=new FileInputStream("d:\\ss.txt"); BufferedInputStream bis=new BufferedInputStream(fis); bis.skip(from-1); int c=0; for(int i=0;(i<to-from)&&(c=bis.read())!=-1;i++){ result+=(char)c; } }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } return result; } }
在标准的J2SE中,实现LZ的需求,支持使用RandomAccessFile类RandomAccessFile r = new RandomAccessFile(new File("c:/1.txt", "r"));//只读方式打开文件 r.seek(100);//指定下一次的开始位置 byte[] bs = new byte[1024]; r.read(bs); r.readChar(); r.readInt();//读取一个整数
public class Test { public static void main(String[] args) { System.out.println(read(3,9)); } public static String read(int from ,int to){ String result=""; byte[] result2=new byte[to-from+1]; try{ FileInputStream fis=new FileInputStream("d:\\ss.txt"); BufferedInputStream bis=new BufferedInputStream(fis); bis.skip(from-1); bis.read(result2, 0, to-from+1); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } return new String(result2); } } second
RandomAccessFile对于楼主的情况来说绝对好用!!byte[] b = new byte[int length]; fis.read(b); 不过注意read一次,游标就会移动,如果读到你想要的东西要修改或者在该处写入 就要提前定义getFilePointer() ,再用seek()回到该游标位置
注意二楼的方法是错误的,已经验证了。(原因:不管始FileInputStream还是RandomAccessFile中方法:read(byte[],int off, int len)中,off都是指在byte中的偏移(即开始位置),并不是指从制定位置开始。可以参考java的api文档。) 一楼和6楼的是正确的。
fis.read(bs); 得到内容
public class Test { public static void main(String[] args) {
System.out.println(read(3,9));
}
public static String read(int from ,int to){
String result="";
try{
FileInputStream fis=new FileInputStream("d:\\ss.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
bis.skip(from-1);
int c=0;
for(int i=0;(i<to-from)&&(c=bis.read())!=-1;i++){
result+=(char)c;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return result;
}
}
r.seek(100);//指定下一次的开始位置
byte[] bs = new byte[1024];
r.read(bs);
r.readChar();
r.readInt();//读取一个整数
public class Test { public static void main(String[] args) {
System.out.println(read(3,9));
}
public static String read(int from ,int to){
String result="";
byte[] result2=new byte[to-from+1];
try{
FileInputStream fis=new FileInputStream("d:\\ss.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
bis.skip(from-1);
bis.read(result2, 0, to-from+1);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return new String(result2);
}
} second
fis.read(b); 不过注意read一次,游标就会移动,如果读到你想要的东西要修改或者在该处写入 就要提前定义getFilePointer() ,再用seek()回到该游标位置
代码热心人已经贴了,我就不贴了。
注意二楼的方法是错误的,已经验证了。(原因:不管始FileInputStream还是RandomAccessFile中方法:read(byte[],int off, int len)中,off都是指在byte中的偏移(即开始位置),并不是指从制定位置开始。可以参考java的api文档。)
一楼和6楼的是正确的。