随机访问文件
来源:互联网 发布:网络推广实战宝典pdf 编辑:程序博客网 时间:2024/04/28 06:23
实际中,常常需要随机访问物理文件,需要用到RandomAcceesFile类.其构造方法是:
public Random AccessFile(String fileName,String mode).其中,mode="rw"(可读写),"r"(只读).其常用方法是:
void close();关闭流对象,释放资源
long length();获得文件的长度
long getFilePointer();获得文件指针的位置
int read();读取一个字节数据
int read(byte[],byteArray):从文件中读取字节数据,并赋值给数组
String readLine():从文件中读取一行文本
void seek(long position);将指针移向position位置
void setLength(long length);设置文件的长度
void write(int byteValue):以字节方式向文件中写入数据
void writeBytes(String str): 向文件中写入字节数据.其他类型数据依次类推.
RandomAccessFile类的优势在于,它集中了文件输入和输出流的功能.使用简便,可以减少代码量.
下面的例子程序实现了以下功能:可以向文件中写入10行二进制数据,并保存在一个二进制文件中.并实现了对该二进制文件的读取功能.
import java.io.*;
public class RadomFile {
public static void main(String args[]) throws IOException{
File newDir=new File("d://java//test2");//创建目录对象//
File newFile=new File(newDir,"accessFile.dat");//创建文件路径对象
newFile.createNewFile();//创建文件
RandomAccessFile fileA=new RandomAccessFile(newFile,"rw");//以读写方式打开文件newFile.
for(int i=0;i<10;i++)fileA.writeBytes("This is line"+i+"/n");
fileA.close();
System.out.println("File Written");
RandomAccessFile fileB=new RandomAccessFile(newFile,"rw");
fileB.seek(fileB.length());
fileB.writeBytes("Append line!"+"/n");
fileB.close();
System.out.println("file append");
String record=new String();
RandomAccessFile fileC=new RandomAccessFile(newFile,"r");//以只读方式打开文件.
while((record=fileC.readLine())!=null)System.out.println(record);
fileC.close();
System.out.println("File Printed");
}
}
- 如何随机访问文件
- 随机访问文件
- RandomAccessFile 随机访问文件
- 读写随机访问文件
- 随机访问文件RandomAccessFil
- java随机访问文件
- 随机访问文件类RandomAccessFile
- 随机访问文件类RandomAccessFile
- 随机访问文件类RandomAccessFile
- 随机访问文件类RandomAccessFile
- RandomAccessFile:对文件随机访问
- RandomAccessFile随机访问分割文件
- C++文件的随机访问
- Java-文件操作与随机访问文件
- 9.6 文件-文件的随机访问
- 文件操作与随机访问文件
- Java 文件随机访问类-RandomAccessFile
- 模拟随机访问文件:shelve模块
- Linux网络环境配置
- 网页中的get与post
- 做一个成功的程序员的七个要素
- 五句可以分享的话
- 成功人士的20个优良习惯
- 随机访问文件
- Java3D遇到的问题
- 连接字符串
- js事件列表
- 一个男人的品位在于选择妻子
- 程序员 我为你悲哀
- 避免重复写if判断的一种写法
- 控制台程序
- 网络管理之网关篇