题目:编写一个Java应用程序,利用RandomAccessFile类,把几个int型整数(1,2,3,4,5,6,7,8,9,10)写入到一个名字为tom.dat文件中,然后按相反顺序读出这些数据并显示在屏幕上程序源代码是这样的:
import java.io.*;class test3
{
public static void main(String args[]) throws IOException
{
RandomAccessFile r=new RandomAccessFile("tom.dat","rw");

for (int i=1;i<=10;i++)
   r.writeInt(i); for(long position=r.length()-4;position>=0;position=position-4)
{
r.seek(position);
System.out.print(r.readInt()+"\t");
}
r.close();
}
}但是这一段我看了很久都看不懂
for(long position=r.length()-4;position>=0;position=position-4)
{
r.seek(position);
System.out.print(r.readInt()+"\t");
}
求各位大虾帮我解析一下,或者还有没有其他更简单的方法?

解决方案 »

  1.   

    x86 sizeof(int) = 4 bytes
      

  2.   

    Java code服务端
    import java.net.*;
    import java.io.*;
    import java.util.*;
    class fanserver
    {
        static List<fanclient> client = new ArrayList<fanclient>();
        public static void main(String[] args)throws Exception 
        {
            Socket s;
            ServerSocket ss = new ServerSocket(4445);
            while(true){
                s = ss.accept();
                System.out.println("haha...");
                server ser = new server(s);
                new Thread(ser).start();
                client.add(ser);
            }
        /*    BufferedReader br = 
                new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bwout = 
                new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            BufferedReader brin = 
                new BufferedReader(new InputStreamReader(s.getInputStream()));
            String str = null;
            while((str=brin.readLine())!=null){
            //    System.out.println(str);
                bwout.write(str);
                bwout.flush();
                bwout.newLine();
            }
            */
            
        //    s.shutdownOutput();
            
            
        }
    }
    class server implements Runnable
    {
        private Socket s;
        server(Socket s){
            this.s = s;
        }
        public void run(){
            try{
                
                BufferedWriter bwout = 
                    new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                BufferedReader brin = 
                    new BufferedReader(new InputStreamReader(s.getInputStream()));
                
                String str = null;
                while((str=brin.readLine())!=null){
                    System.out.println(str);
                    bwout.write(str);
                    bwout.newLine();
                    
                    bwout.flush();
                }
            //    s.shutdownOutput();
                
            }
            catch(Exception e){}
        }
    }
    Java code客户端import java.net.*;
    import java.io.*;
    class fanclient 
    {        public static void main(String[] args)throws Exception
        {
            Socket s = new Socket("192.168.30.129",4445);
            BufferedReader br = 
                new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bwout = 
                new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            BufferedReader brin = 
                new BufferedReader(new InputStreamReader(s.getInputStream()));
            new Thread(new client(brin)).start();
            String str = null;
            while((str=br.readLine())!=null){
                
                bwout.write(str);
                
                bwout.newLine();
                bwout.flush();
                
            }
            
        //    s.shutdownOutput();
        
        //    String line = brin.readLine();
        //    System.out.println(line);
        
        
        }
    }
    class client implements Runnable
    {
        private BufferedReader brin;
        client(BufferedReader brin)
        {
            this.brin = brin;
        }
        public void run(){
            String line = null;
            try{
                while((line=brin.readLine())!=null){
                    System.out.println(line);    
                }
            }catch(Exception e){}
        }
    }我同时启动好几个客户端,想让客户端通过服无端互相接收到信息,怎么处理, 
     
     
      

  3.   

    for(long position=r.length()-4;position>=0;position=position-4)
     {
     r.seek(position);
     System.out.print(r.readInt()+"\t");
     }
    一个Int 类型占了4个字节, 所以每次readInt(); 就移动了4个字节的字节, 然后seek();方法 重新定位到某一特定位置。 所以上面这段代码就 相当于倒着读出来了。
      

  4.   

    那为什么一开始的位置就设置为position=r.length()-4这个就是最后一个数的的位置吗?循环条件long position=r.length()-4;position>=0;position=position-4具体怎样运行的?
      

  5.   

    真心求教啊客户端
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    class liaot extends Frame
    {
    Socket socket=null;
    private TextArea text1;
    private TextField text2;
    //图形界面
    liaot(){
    text1 = new TextArea();
    text2 = new TextField();
    add(text1,"Center");
    add(text2,"South");
    try{
    socket = new Socket("192.168.30.129",3334);
    }catch(Exception ee){}
    event();
    setBounds(300,300,300,300);
    setVisible(true);

    }
    //事件响应
    public void event(){
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    }
    });
    text2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){


    // new Thread(new clientsend()).start();
    new Thread(new clientrec()).start();
    send();
    //rece();
    text2.setText("");
    }
    });
    } public static void main(String[] args)throws Exception 
    {
    new liaot();
    }
    //发送
    public void send(){
    byte[]buf = text2.getText().trim().getBytes();
    String str = new String(buf,0,buf.length);
    System.out.println(str);
    // text1.setText(str+text2.getText()+"\r\n");
    try{
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

    dos.writeUTF(str);
    dos.flush();
    // out.write("\r\n".getBytes());
    ;
    }catch(Exception e){}
    }

    class clientsend implements Runnable
    {
    public void run(){
    send();
    }
    }
    //接收
    public void rece(){
    try{
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    String str = dis.readUTF();

    text1.append(str+"\r\n");
    }catch(Exception e){}
    }
    class clientrec implements Runnable
    {
    public void run(){
    // byte[] buf = new byte[1024];
    rece();

    }
    }
    }
    服务端
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class liaotserver 
    {
    static List<server> list = new ArrayList<server>();
    public static void main(String[] args)throws Exception 
    {
    Socket socket;
    ServerSocket ss = new ServerSocket(3334);
    while(true){
    socket = ss.accept();
    System.out.println("hahahah....");
    server ser = new server(socket);
    list.add(ser);
    new Thread(ser).start();
    }
    }
    static class server implements Runnable
    {
    private DataOutputStream dos;
    private DataInputStream dis;
    private Socket socket = null;
    server(Socket socket){
    this.socket = socket;
    try{
    dos = new DataOutputStream(socket.getOutputStream());
    dis = new DataInputStream(socket.getInputStream());
    }catch(Exception e){}
    }
    public void send(String str){
    try{
    //System.out.println(str);
    dos.writeUTF(str);
    dos.flush();

    }catch(Exception e){}
    }
    public void run(){
    // byte[] buf = new byte[1024];
    try{
    while(true){
    String str = dis.readUTF();

    //System.out.println(str);
    for(int i=0;i<list.size();i++){
    server s = list.get(i);
    s.send(str);
    }
    }
    }catch(Exception e){}

    }
    }}
    我运行一个客户端时,运行正常,显示结果正常,运行两个客户端时,我在第一个客户端写“你好”,第一个客户端能显示“你好”,但是第二个客户端不能显示,但是我要是在第二个客户端写上“哈哈”,”哈哈“不能显示,而是第一个客户端的”你好“显示出来了,每次输入都是这样,什么原因啊,怎么改?
      

  6.   

    public class RandomAccessFileextends Objectimplements DataOutput, DataInput, Closeable此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组。存在指向该隐含数组的光标或索引,称为文件指针;输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针。写入隐含数组的当前末尾之后的输出操作导致该数组扩展。该文件指针可以通过 getFilePointer 方法读取,并通过 seek 方法设置。 通常,如果此类中的所有读取例程在读取所需数量的字节之前已到达文件末尾,则抛出 EOFException(是一种 IOException)。如果由于某些原因无法读取任何字节,而不是在读取所需数量的字节之前已到达文件末尾,则抛出 IOException,而不是 EOFException。需要特别指出的是,如果流已被关闭,则可能抛出 IOException。 
    public void seek(long pos)
              throws IOException设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。偏移量的设置可能会超出文件末尾。偏移量的设置超出文件末尾不会改变文件的长度。只有在偏移量的设置超出文件末尾的情况下对文件进行写入才会更改其长度。 参数:
    pos - 从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针。 
    import java.io.*;public class IoTest3
    {
    public static void main(String args[]) throws IOException
    {
    RandomAccessFile r=new RandomAccessFile("tom.dat","rw");for (int i=1;i<=10;i++)
    r.writeInt(i);// 从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针,控制文件偏移量
    for(long position=r.length()-4;position>=0;position=position-4)
    {
    //设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作
    r.seek(position);
     //把文件读出来,显示在屏幕上
    System.out.print(r.readInt()+"\t");
    }
    //关闭文件流
    r.close();
    }
    }