Java RandomAccessFile writeShort()方法

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

1 语法

public final void writeShort(int v)

2 参数

v:要写入的short值。

3 返回值

4 示例 

package com.yiidian;

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

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

        try {
            short s = 15;

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

            // write a short in the file
            raf.writeShort(s);

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

            // read short
            System.out.println("" + raf.readShort());

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

            // write a short at the start
            raf.writeShort(20);

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

            // read short
            System.out.println("" + raf.readShort());

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

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

ABCDE  

输出结果为:

15
20

热门文章

优秀文章