黑马程序员技术交流社区

标题: 用RandomAccessFile类实现文件的写入和读取,里面的seek()方法怎么计算指针 [打印本页]

作者: 谢毅    时间: 2012-12-31 15:41
标题: 用RandomAccessFile类实现文件的写入和读取,里面的seek()方法怎么计算指针
import java.io.*;
class  RandomAccessFileDemo
{
        public static void main(String[] args) throws IOException
        {
                //writeFile();
                readFile();
        }

        public static void readFile() throws IOException
        {
                RandomAccessFile raf = new RandomAccessFile("hebin.txt","r");
                raf.seek(9);
                byte[] buf = new byte[4];
                raf.read(buf);
                String name = new String(buf);
                int age = raf.read();
                System.out.println(name);
                System.out.println(age);
                raf.close();
        }

        public static void writeFile() throws IOException
        {
                RandomAccessFile raf = new RandomAccessFile("hebin.txt","rw");
                raf.write("lisi".getBytes());
                raf.writeInt(258);
                raf.write("wangwu".getBytes());
                raf.write(99);
                raf.close();
        }
}
raf.seek(9);里面到底该传多少才能取出wangwu的数据啊?
作者: 马志军    时间: 2012-12-31 15:55
lisi八个字节,258四个字节,一共seek(12)?
作者: ying    时间: 2012-12-31 22:36
import java.io.*;
class  RandomAccessFileDemo
{
        public static void main(String[] args) throws IOException
        {
           writeFile();
                 readFile();
        }
        public static void readFile() throws IOException
        {
                RandomAccessFile raf = new RandomAccessFile("hebin.txt","r");
                raf.seek(10);
                byte[] buf = new byte[6];
                raf.read(buf);
                String name = new String(buf);
                int age = raf.read();
                System.out.println(name);
                System.out.println(age);
                raf.close();
        }
        public static void writeFile() throws IOException
        {
         
                RandomAccessFile raf = new RandomAccessFile("hebin.txt","rw");
                raf.seek(0);
                raf.write("lisi".getBytes());
                raf.writeInt(258);
                raf.seek(10);
                raf.write("wangwu".getBytes());
                raf.write(99);
                raf.close();
        }
}
/*
* 在读取数据是一定在把指针调整到哪条数据的位置上
*/


作者: 谢毅    时间: 2012-12-31 22:45
ying 发表于 2012-12-31 22:36
import java.io.*;
class  RandomAccessFileDemo
{

你的结果我试过了,打印不完整,还是没出来。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2