Java RandomAccessFile writeUTF()方法

java.io.RandomAccessFile.writeUTF(String str) 方法将一个字符串写入使用经修订的UTF-8编码以与机器无关的文件的方式。

1 语法

public final void writeUTF(String str)

2 参数

str:要写入的字符串。

3 返回值

4 示例 

package com.yiidian;

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

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

        try {
            String s = "Hello world";

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

            // write a string in the file
            raf.writeUTF(s);

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

            // read string
            System.out.println("" + raf.readUTF());

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

            // write a string at the start
            raf.writeUTF("This is an example");

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

            // read string
            System.out.println("" + raf.readUTF());

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

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

ABCDE  

输出结果为:

Hello world
This is an example

热门文章

优秀文章