Java RandomAccessFile writeInt()方法

java.io.RandomAccessFile.writeInt(int v) 方法写入一个int到文件为四个字节,高字节在前。写入从文件指针的当前位置。

1 语法

public final void writeInt(int v)

2 参数

v:要写入一个整型值。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.RandomAccessFile.writeInt(int v)方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {

        try {
            int f = 1847;

            // create a new RandomAccessFile with filename test
            RandomAccessFile raf = new RandomAccessFile("d:/test.txt", "rw");

            // write an int in the file
            raf.writeInt(f);

            // set the file pointer at 0 position
            raf.seek(0);

            // read int
            System.out.println("" + raf.readInt());

            // set the file pointer at 0 position
            raf.seek(0);

            // write a int at the start
            raf.writeInt(200);

            // set the file pointer at 0 position
            raf.seek(0);

            // read int
            System.out.println("" + raf.readInt());

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

假设test.txt文件内容如下:

ABCDE  

输出结果为:

1847
200

热门文章

优秀文章