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型数据也能写入?

解决方案 »

  1.   

    int使用的是一个4个字节保存的,想显示出来必须转换为字符串
      

  2.   

    我知道int型数据时4字节,当我使用RandomAccessFile类中的writeInt()写数据到文件中时,在用readInt()读取数据,输出结果时还会出现运行错误。这儿不应出现此种问题啊?
      

  3.   


    import java.io.*;public class RandomAcessFileDemo {
    public static void main(String[] args) throws IOException {
    File f = new File("C:" + File.separator + "text.txt");
    int length = 0;
    RandomAccessFile raf = null;
    // 写入
    try {
    raf = new RandomAccessFile(f, "rw");
    String name = "张三";
    int age = 15;
    byte[] bs = name.getBytes("utf-8");
    length = bs.length;
    raf.write(bs);
    raf.writeInt(age);
    } finally {
    if (raf != null) {
    raf.close();
    raf = null;
    }
    } // 读取
    try {
    raf = new RandomAccessFile(f, "rw");
    byte[] buffer = new byte[1024];
    int len = raf.read(buffer, 0, length); // 上面输入的名字的长度
    System.out.println("name:" + new String(buffer, 0, len, "utf-8"));
    int age = raf.readInt();
    System.out.println("age:" + age);
    } finally {
    if (raf != null) {
    raf.close();
    raf = null;
    }
    }
    }
    }
      

  4.   


    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();
    }}