day day up--Java编程之RandomAccessFile操作系统属性文件

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;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值