RadomAccessFile_java读写文件时如…

如果用 流读取文件 FileInputStream,FileReader 只能顺序读取。读一个字符指针移动一个位置

如果用 RadomAccessFile,可以用 seek 指定移动到文件的某个位置。
位置定位以字符为单元

要定位到某行,试试 java.io.LineNumberReader 和 java.io.LineNumberInputStream


例子: RadomAccessFile

package org.kodejava.example.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample {

public static void main(String[] args) {
try {
//
// Create a new instance of RandomAccessFile class. We'll do a "r"
// read and "w" write operation to the file. If you want to do a write
// operation you must also allow read opeartion to the RandomAccessFile
// instance.
//
RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");

//
// Let's write some book's title to the end of the file
//
String books[] = new String[5];
books[0] = "Professional JSP";
books[1] = "The Java Application Programming Interface";
books[2] = "Java Security";
books[3] = "Java Security Handbook";
books[4] = "Hacking Exposed J2EE & Java";

for (int i = 0; i < books.length; i++) {
raf.writeUTF(books[i]);
}

//
// Write another data at the end of the file.
//
raf.seek(raf.length());
raf.writeUTF("Servlet & JSP Programming");

//
// Move the file pointer to the beginning of the file
//
raf.seek(0);

//
// While the file pointer is less than the file length, read the
// next strings of data file from the current position of the
// file pointer.
//
while (raf.getFilePointer() < raf.length()) {
System.out.println(raf.readUTF());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值