Java I/O操作除了InputStream和OutputStream,还有另外一个独立的类RandomAccessFile,它不同于标准输入输出操作,它提供方法seek()可以跳转到文件任何位置并进行操作,能够发挥该方法的好处的前提是你必须知道文件的结构。使用RandomAccessFile对文件进行操作时,需要指定打开文件的操作方式,只读“r”,读写“rw”,同步读写“rws”和“rwd”,“rws"和”rwd“的区别在于前者把”元数据“即文件的属性信息都同步写入基础存储设备。下面是读取固定长度的配置文件的源代码,属性名和属性值的长度根据实际情况来指定。
<span style="white-space:pre"> </span>public static final int KEY_MAX_LENGTH = 31; //属性名最大长度
public static final int VALUE_MAX_LENGTH = 95;//属性值最大长度
public static boolean setProperty(String key, String value) {
String s,filename;
byte c;long p=0;
byte[] buf = new byte[32];
StringBuffer sb = new StringBuffer();
RandomAccessFile randomfile = null;
//创建文件读取对象
try {
randomfile = new RandomAccessFile(filename,"rwd");
//文件指针对文件进行搜索
while(p <= randomfile.length() && p+128<randomfile.length())
{
randomfile.seek(p); //跳转到文件指针p所在的位置
for(int i=0;i<key.length();i++)
{
c = randomfile.readByte();
buf[i] = c;
}
s = new String(buf);
//若存在,则修改属性
if(key.equals(s.trim()))
{
randomfile.seek(p+32);
randomfile.writeBytes(value);
for(int i=0;i<96-value.length();i++)
randomfile.write(0x00);
return true;
}
else
p += 128;
randomfile.seek(p);
}
//若不存在,则添加到内容尾
randomfile.writeBytes(key);
randomfile.seek(p+32);
randomfile.writeBytes(value);
for(int i=0;i<96-value.length();i++)
randomfile.write(0x00);
}catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
获取文件属性的方法:
public static String getProperty(String key) {
long p=0;byte c;
byte[] buf = new byte[32],buf2 = new byte[96];
RandomAccessFile randomfile = null;
String filename,s;
try {
randomfile = new RandomAccessFile(filename,"r");
while(p <= randomfile.length()&& p<randomfile.length()-128)
{
randomfile.seek(p); //调到需要开始操作的文件位置
for(int i=0;i<key.length();i++)
{
c = randomfile.readByte();
buf[i] = c;
}
s = new String(buf);
if(key.equals(s.trim())) //与去空白后的字符串进行比较
{
randomfile.seek(32);
for(int j=0;j<=VALUE_MAX_LENGTH;j++)
buf2[j]=randomfile.readByte();
s = new String(buf2);
return s.trim();
}
else
p += 128;
randomfile.seek(p);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
return null;
}catch(IOException e){
e.printStackTrace();
return null;
}
return null;
}