`

文件随机读写类

阅读更多
package accessFile;

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

/**
* 文件随机读写类
* @author wxg1022
*
*/
public class TestRandomAccessFile {

public static void main(String[] args) {
// 访问到达文件末尾发生的异常:EOFException
// 文件访问中途发生的异常:IOEException

// 打开关闭文件
// RandomAccessFile(String,String);第一个参数是文件路径,第二是打开模式
// RandomAccessFile(File,String);第一个参数是文件对象,第二是打开模式
// 其中打开模式有:r(只读),rw(读写),rws(读写及同步更新),rwd(读写及同步更新)等4种
try {
/**
* 一、打开
*/
RandomAccessFile file = new RandomAccessFile("D:/demo/test6.txt",
"rw");
// 或RandomAccessFile file1=new RandomAccessFile(new
// File("D:/demo/test6.txt"),"rw");

//(1)取得文件长度
long size = file.length();
System.out.println("文件大小:"+size);
//(2)设置文件指针的位置
//file.seek(4);
System.out.println(file.readUTF());
file.seek(0);
/**
* 二、读取
*/
//(3)读取一个数据字节
int c=file.read();//每读取一个字节,指针会向后移动一个字节的位置
System.out.println((char)c);//转换为字符
//(4)读取到字节数组
byte[] b=new byte[50];
file.read(b);
String s=new String(b);
System.out.println("读取的字节数组:"+s);
//(5)灵活读取到字节数组
b=new byte[50];
file.read(b,2,10);//从第4个位置读取10个字节
s=new String(b);
System.out.println("读取的字节数组:"+s);
//(6)读取其他方式
//boolean readBoolean();
//System.out.println(file.readBoolean());
//byte readByte();
//char readChar();等等其他查看api
//(7)读取一行字符串
System.out.println(file.readLine());
//(8)读取中文字符
//System.out.println(file.readUTF());

/**
* 三、写入文件
*/
//(9)写入一个字节
file.write(100);
//(10)写入字节数组
byte[] bb=new byte[3];
bb[0]=101;
bb[1]=102;
bb[2]=127;//不能超过127
file.write(bb);
file.write(bb,1,2);//灵活写入字节数组
//写入固定类型的数值(略)
//file.writeBoolean(true);
//file.writeBoolean(false);
//file.writeInt(130);
//file.writeByte(144);
//写入一个字符串
file.writeBytes("AA");
file.writeChars("DD");
file.writeUTF("中国人");

//查看数字对应的char
for(int i=0;i<200;i++){
System.out.println(i+"="+(char)i);
System.out.println(i+"="+(byte)i);
}

//file.close();// 关闭文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics