lillian1205

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  0 Posts :: 5 Stories :: 0 Comments :: 0 Trackbacks

用Properties和RandomAccessFile

1 Properties
    用Properties读取特别简单,以下是一些小方法
    写文件的时候用BufferedWriter可以自由换行,代替换行符 。但是用这种方法写文件会覆盖掉文件原有的内容,也就是说不能满足追加信息的功能
这就用到RandomAccessFile了


public class IniRead {
private static Properties ini = null;
    
//设置INI文件
    static File file=new File("Config-增加.ini");
    
static {
        
try    {
            ini 
= new Properties ();
            
//加载文件
            ini.load (new FileInputStream (file));
        }
catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    
private IniRead() {
    }

    
/**
     * 读取INI信息
     * 
*/

    
public static String getIniKey (String key) {
        
if(!ini.containsKey (key)) {
            
return "";
        }

        
return ini.get(key).toString ();
    }

    
/**
     * 修改INI信息
     * 
*/

    
public static void setIniKey (String key, String value) {
        
if(!ini.containsKey (key)) {
            
return;
        }

        ini.put (key, value);
    }

    
/**
     * 保存INI信息
     * 
*/

    
public static void saveIni (String k[]) {
        
try    {
            FileWriter fw 
= new FileWriter ("ADViewer.ini");
            BufferedWriter bw 
= new BufferedWriter (fw);
            bw.newLine ();
            
for (int i = 0; i < k.length; i++{
                bw.write (k[i] 
+ "=" + getIniKey (k[i]));
                System.out.println(getIniKey (k[i]));
                bw.newLine ();
            }

            
            bw.close ();
            fw.close ();
        }
catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}

    


2  RandomAccessFile
    一边读一边写,还能移动指针

/*
     * 读取需添加的ini文件信息,并写入到相应的ini文件中
     
*/

    
public void write(String readFile, String writeFile) throws Exception {

        RandomAccessFile rafRead 
= new RandomAccessFile(readFile, mode);
        RandomAccessFile rafWrite 
= new RandomAccessFile(writeFile, mode);
        
//按行读取
        String lineStr = rafRead.readLine();
        
while (lineStr != null{
            
// 写入一行后换行
            lineStr += "\r\n";
            
//将指针移动到文件尾部
            rafWrite.seek(rafWrite.length());
            
//写入读取的一行
            rafWrite.write(lineStr.getBytes());

            lineStr 
= rafRead.readLine();
        }


    }
posted on 2009-10-09 15:25 lillian 阅读(114) 评论(0)  编辑  收藏 所属分类: java读取操作ini文件

只有注册用户登录后才能发表评论。


网站导航: