Java RandomAccessFile writeChars()方法
java.io.RandomAccessFile.writeChars(String s) 方法将一个字符串写入该文件为一个字符序列。每个字符都使用writeChar方法写入数据输出流。写入从文件指针的当前位置。
1 语法
public final void writeChars(String s)
2 参数
s:要写入的字符串值。
3 返回值
无
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.io.RandomAccessFile.writeChars(String s)方法的例子
*/
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 char in the file
raf.writeChars(s);
// set the file pointer at 0 position
raf.seek(0);
// read chars
for (int i = 0; i < 11; i++) {
System.out.print("" + raf.readChar());
}
// set the file pointer at 0 position
raf.seek(0);
// change the line for better view
System.out.println();
// write a char at the start
raf.writeChars("This is an example");
// set the file pointer at 0 position
raf.seek(0);
// read chars
for (int i = 0; i < 18; i++) {
System.out.print("" + raf.readChar());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
假设test.txt文件内容如下:
ABCDE
输出结果为:
Hello World
This is an example
热门文章
优秀文章