java使用RandomAccessFile 类存取文件,,下面例子演示如何使用Ra
分享于 点击 35868 次 点评:154
java使用RandomAccessFile 类存取文件,,下面例子演示如何使用Ra
下面例子演示如何使用RandomAccessFile类。
在下面的例子中我们首先打开文本文件,并指定读写权限,然后向文件中写入两行文本,然后将文件指针指向第二行开始处,然后读取第二行的内容。
import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;/** * * @author byrx.net */public class Main { /** * RandomAccessFile 使用示例 */ public void testRandomAccessFile(String filename) { RandomAccessFile randomAccessFile = null; try { //定义要写入文件的字符串 String line1 = "First line\n"; String line2 = "Second line\n"; //创建RandomAccessFile实例,指定读写权限 randomAccessFile = new RandomAccessFile(filename, "rw"); //写入字符串 randomAccessFile.writeBytes(line1); randomAccessFile.writeBytes(line2); //将文件指针指向line1结尾处 randomAccessFile.seek(line1.length()); //声明一个和line2相同长度的字节数组 byte[] buffer = new byte[line2.length()]; //读取line2内容 randomAccessFile.read(buffer); //将读取出来的字符串打印到控制台 System.out.println(new String(buffer)); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (randomAccessFile != null) randomAccessFile.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().testRandomAccessFile("myFile.txt"); }}
文件内容:
First lineSecond line
控制台输出:
Second line
用户点评