Java基础之I/O流详解(1)(3)
分享于 点击 33479 次 点评:62
RandomAccessFile随机文件读写类):
1)RandomAccessFile类:它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据只需要改变文件的读写位置的指针)。
2)由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据比如采用readLong()方法读取长整数,而利用 readInt()方法可以读出整数值等)。
RandomFileRW.java
- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class RandomFileRW {
- public static void main(String args[]) {
- StringBuffer buf = new StringBuffer();
- char ch;
- try {
- while ((ch = (char) System.in.read()) != '\n') {
- buf.append(ch);
- }
- // 读写方式可以为"r" or "rw"
- /**
- * @param mode 1. r 2. rw 3. rws 4. rwd
- * "r" Open for reading only. Invoking any of the write methods of the resulting object will
- * cause an IOException to be thrown.
- * "rw" Open for reading and writing. If the file does not already exist then an attempt will
- * be made to create it.
- * "rws" Open for reading and writing, as with "rw", and also require that every update to the
- * file's content or metadata be written synchronously to the underlying storage device.
- * "rwd" Open for reading and writing, as with "rw", and also require that every update to the
- * file's content be written synchronously to the underlying storage device.
- */
- RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt", "rw");
- myFileStream.seek(myFileStream.length());
- myFileStream.writeBytes(buf.toString());
- // 将用户从键盘输入的内容添加到文件的尾部
- myFileStream.close();
- } catch (IOException e) {
- }
- }
- }
用户点评