日期:2014-05-20  浏览次数:20705 次

RandomAccessFile中writeInt()的使用问题
package IO;
import java.io.*;
public class RandomAcessFileDemo {
  public static void main(String[] args) throws Exception {
File f=new File("D:"+File.separator+"text.txt");
RandomAccessFile raf=null;
raf=new RandomAccessFile(f,"rw");
String name=null;
int age=0;
  name="zhangsan";
age=15;
raf.writeBytes(name);
raf.skipBytes(8);
  raf.writeInt(age);
  raf.close();
  }

}
这儿使用RandomAccessFile流把字符串和int型数据写入到text.txt中
查看时,字符串没有乱码,int型数据变成了乱码。这儿该怎么解决,使
int型数据也能写入?

------解决方案--------------------
Java code

import java.io.File;
import java.io.RandomAccessFile;

public class RandomAcessFileDemo {
    public static void main(String[] args) throws Exception {
        File f = new File("temp.txt");
        RandomAccessFile raf = null;
        raf = new RandomAccessFile(f, "rw");
        String name = "zhangsan";
        Integer age = 15;
        raf.writeBytes(name);
        raf.skipBytes(8);
        raf.writeInt(age);
        raf.seek(0);//找位置
        byte[] b = new byte[8];
        raf.read(b);
        System.out.println(new String(b));
        System.out.println(raf.readInt());
        raf.close();
    }

}