当前位置: 代码迷 >> J2SE >> [IO]修改文件的疑问?请问
  详细解决方案

[IO]修改文件的疑问?请问

热度:28   发布时间:2016-04-24 02:01:23.0
[IO]修改文件的疑问?请教
欲修改database.properties文件,文件内容如下:
Java code
#DBCP database propertiesusername=rootdontencry=YESpassword=rootdriverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/gcra

只需将password=root修改为:password=admin 。
我以为可以直接使用java.io包中的类,譬如RandomAccessFile直接write就完事了。自己做实验,设置写入点,然后调用write,但方法是调用了,文件并没有改变。  
Java code
    public void modifyFile(String fileName, String key, String value){        OptProperties op = new OptProperties();                File file = op.getFileFromBasePath(fileName);        RandomAccessFile raf = null;        //position        long oldPos = 0;        long newPos = 0;                String lineStr = "";        try {            raf = new RandomAccessFile(file, "rw");            oldPos = raf.getFilePointer();            lineStr = raf.readLine();            newPos = raf.getFilePointer();            while(lineStr != null){                //key = "password"                if(lineStr.contains(key)){                    //将读取位置设置到oldPos                    raf.seek(oldPos);                                        System.out.println(oldPos);                                        raf.write(value.getBytes());                    //raf.write(value.getBytes(), (int)(oldPos+1), (int)(newPos-oldPos));                    break;                }                oldPos = raf.getFilePointer();                lineStr = raf.readLine();                newPos = raf.getFilePointer();            }                        /*for(int i=0; i<7; i++){                System.out.println(raf.readLine() + ", " + raf.getFilePointer());            }*/                    } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally{            if(raf != null){                try {                    raf.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

======


------解决方案--------------------
文件偏移量设置得不对
Java code
raf.seek(oldPos);改为raf.seek(oldPos + key.length() + 1);    //+1是因为有个等号
------解决方案--------------------
如果文件完全没有改变就不是因为位置的问题
没有抛异常吗?
另外,检查下你的value变量传入的对不对
  相关解决方案