Java.io.RandomAccessFile.skipBytes() 方法
描述
java.io.RandomAccessFile.skipBytes(int n) 方法尝试跳过 n 个字节的输入,丢弃跳过的字节。 此方法可能会跳过一些较小的字节数,可能为零。 这可能是由多种情况中的任何一种造成的; 在跳过 n 个字节之前到达文件末尾只是一种可能性。 此方法从不抛出 EOFException。 返回实际跳过的字节数。 如果 n 为负数,则不跳过任何字节。
声明
以下是 java.io.RandomAccessFile.skipBytes() 方法的声明。
public int skipBytes(int n)
参数
n − 要跳过的字节数。
返回值
此方法返回实际跳过的字节数。
异常
IOException − 如果发生 I/O 错误。
示例
下面的例子展示了 java.io.RandomAccessFile.skipBytes() 方法的使用。
package com.tutorialspoint;
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 something in the file
raf.writeUTF("Hello World");
// set the file pointer at 0 position
raf.seek(0);
// print the string
System.out.println("" + raf.readUTF());
// set the file pointer at 0 position
raf.seek(0);
// attempt to skip 10 bytes and print the number of bytes skipped
System.out.println("" + raf.skipBytes(10));
// print what is left after skipping
System.out.println("" + raf.readLine());
// set the file pointer to position 8
raf.seek(8);
// attempt to skip 10 more bytes and print the number of bytes skipped
System.out.println("" + raf.skipBytes(10));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDE
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello World 10 rld 5

