黑马程序员技术交流社区
标题:
RandomAccessFile的方法writeInt()写入一个比较大的数据后,再用...
[打印本页]
作者:
王希军
时间:
2013-7-29 16:32
标题:
RandomAccessFile的方法writeInt()写入一个比较大的数据后,再用...
本帖最后由 杨兴庭 于 2013-7-30 22:37 编辑
RandomAccessFile的方法writeInt()写入一个比较大的数据后,再用RandomAccessFile的readInt()方法读取时,读的数据不一致。
import java.io.*;
/*
该类不算是IO中的子类,
而是直接继承的Object。
但是它是IO包中的成员,因为它具备读写功能
内部封装了一个数组,而且通过指针对数组的元素进行操作
通过getFilePointer方法获取指针的位置
通过seek方法改变指针的位置
*/
class RandomAccessFileDemo
{
public static void main(String[] args) throws IOException
{
//writeFile();
readFile();
//System.out.println(Integer.toBinaryString(259));
}
public static void readFile() throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ram.txt","r");
//调整数组中的指针
//raf.seek(5);
//跳过指定的字符
//raf.skipBytes();
byte[] buf=new byte[10];
raf.read(buf);
String name=new String(buf);
int age=raf.readInt();
System.out.println("name="+name);
System.out.println("age="+age);
}
public static void writeFile() throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ram.txt","rw");
raf.write("wang wu".getBytes());
//raf.write(66);
raf.writeInt(4);
raf.write("zhao si".getBytes());
//raf.write(66);
raf.writeInt(333333333);
raf.close();
}
}
作者:
taomingking
时间:
2013-7-29 21:06
本帖最后由 taomingking 于 2013-7-29 21:30 编辑
这个道理很简单的,你writeFile()方法存入的wang wu是7个字节,writeInt()存入的4是4个字节,但是你readFile()方法里却是先读了10个字节,再用readInt()读取了4个字节,把zhao si的前三个字节读取了出来.
总的来说就是你存入和读取的字节数不一致,导致这种情况
下面是代码我更改了一下
package com.itheima;
import java.io.*;
class RandomAccessFileDemo
{
public static void main(String[] args) throws IOException
{
writeFile();
System.out.println("wang wu".getBytes().length);//打印一下wang wu的字节数
readFile();
//System.out.println(Integer.toBinaryString(259));
}
public static void readFile() throws IOException
{
RandomAccessFile raf = new RandomAccessFile("ram.txt","r");
byte[] buf=new byte[7];//这里改成7就可以了
raf.read(buf);
String name=new String(buf);
int age=raf.readInt();
System.out.println("name="+name);
System.out.println("age="+age);
}
public static void writeFile() throws IOException
{
RandomAccessFile raf=new RandomAccessFile("ram.txt","rw");
raf.write("wang wu".getBytes());//存入的是7个字节
//raf.write(66);
raf.writeInt(4);
raf.write("zhao si".getBytes());
//raf.write(66);
raf.writeInt(333333333);
raf.close();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2