用java如何读取一个文件的指定字节位置的数据?

用java如何读取一个文件的指定字节位置的数据?现在我指定一个文件1.shp的第33-36个字节(4个字节)的位置是存储了一个整型数据,怎么读出来并存储为整型呢?

可以使用RandomAccessFile类。例如要从100字节开始输出工作目录下的data.txt文件的类容。
package konw.test1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test1
{
public static void main(String[] args)
{
long pos = 100;
try
{
String str = "";
RandomAccessFile randomAccessFile = new RandomAccessFile("data.txt", "rw");
randomAccessFile.seek(pos);//将文件流的位置移动到pos字节处
while( (str = randomAccessFile.readLine()) != null)
{
System.out.println(str);
}
randomAccessFile.close();

} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-18
public static void testReadFile(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("c:/out.txt", "r");
//跳过字节数
raf.skipBytes(32);
//读取一个数字
int num = raf.readInt();
System.out.println(num);
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
第2个回答  2012-02-18
byte[] buff=new byte[4];
try {
DataInputStream dis=new DataInputStream(new FileInputStream(new File("c:/rr.ifo")));
dis.skip(32);
dis.read(buff);
ByteArrayInputStream bintput = new ByteArrayInputStream(buff);
int f = bintput.read();
System.out.println(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}本回答被提问者采纳
相似回答