java.io.RandomAccessFile.writeBytes(String s) 方法写入字符串到文件为一个字节序列。字符串中的每个字符写入出来,按顺序排列,通过丢弃其高8位。写入从文件指针的当前位置。
声明
以下是java.io.RandomAccessFile.writeBytes()方法的声明
public final void writeBytes(String s)
参数
-
s -- 要写入的字节的字符串。
返回值
此方法无任何返回值。
异常
-
IOException -- 如果发生I/ O错误。
例子
下面的示例演示java.io.RandomAccessFile.writeBytes()方法的用法。
package com.yiibai; import java.io.*; public class RandomAccessFileDemo { public static void main(String[] args) { try { // create a new RandomAccessFile with filename test RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw"); // write bytes in the file raf.writeBytes("Hello World"); // set the file pointer at 0 position raf.seek(0); // read line System.out.println("" + raf.readLine()); // set the file pointer at 0 position raf.seek(0); // write bytes at the start raf.writeBytes("This is an example"); // set the file pointer at 0 position raf.seek(0); // read line System.out.println("" + raf.readLine()); } catch (IOException ex) { ex.printStackTrace(); } } }
假设我们有一个文本文件c:/ test.txt,它具有以下内容。该文件将被用作输入到我们的示例程序:
ABCDE
让我们来编译和运行上面的程序,这将产生以下结果:
Hello World This is an example