剪切文件_配置文件修改-我们到底能走多远系列(4)

我们到底能走多远系列(4)

扯淡:

  不知道有多少人喜欢听着音乐写点代码的?我是其中一个。以前在公司的时候期望能买个好点的MP3什么的心无旁骛的写点代码,领点工资。生活总是没有想象得美好。程序员要处理的事有很多不是坐在舒服的椅子上,喝点咖啡或绿茶,敲几行代码能解决的。

  是不是大家都是容易放弃的人呢?反正我是的,上个月,看本书看了2章,就搁置了。上个星期开始尝试听voa,临近的3天就荒废了。今天继续吧。

  园子里读到过一篇怎样找出自己人生的终极目标:用一个小时,勿打扰的思考,不断记下浮现脑海的答案,列出表格。作者认为用这种方式在最后能够发现每个人自己一生的目标。从而开启一个不一样的人生旅程。不知道有没有人试过呀。

  人生就像抛硬币,只要我们能接住,就会有结果。

剪切文件:


复制文件+删除文件=剪切文件?

好吧,原始的方式:

    public static boolean moveFile1(String fromPath, String toPath) throws IOException{
        File fromFile = new File(fromPath);
        InputStream is = new BufferedInputStream(new FileInputStream(fromFile));
        OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(toPath)));
        
                byte b[] = new byte[(int)fromFile.length()] ;
                while(is.read(b, 0, b.length) != -1){
                    os.write(b, 0, b.length);
                }
            
            is.close();
            os.close();
            return fromFile.delete();
    }

但是我们不会用上面的方法去实现,因为File有自己的方式去解决剪切这件事:

    /**
     * 
     * @param fromPath 被剪切文件路径 -->"d:/我的文档/www.txt"
     * @param toPath   剪切去的位置路径 -->"d:/我的文档/test/www.txt"
     */
    public static void moveFile2(String fromPath, String toPath){
        File fromFile = new File(fromPath);
        File toFile = new File(toPath);
        //存在同名文件 
        if(toFile.exists()){
            // 截断路径
            int last = toPath.lastIndexOf(File.separator) > toPath.lastIndexOf("\\")? toPath.lastIndexOf(File.pathSeparator):toPath.lastIndexOf("\\");
            String path = toPath.substring(0, last);
            // 备份文件名
            File fileBak = new File(path + File.separator + toFile.getName() + ".bak");
            // 备份文件同名
            if( ! toFile.renameTo(fileBak)){
                fileBak.delete();//删除同名备份文件
            }
            // 备份文件
            toFile.renameTo(fileBak);
        }
        // 剪切
        fromFile.renameTo(toFile);
    }

上例需要注意renameTo的方法的使用,如果返回false,说明操作失败,可能会影响后续的操作。(比如说已经有同名的文件)


下班回到家,想修改配置文件这件事,原始的方式:

/**
     * 
     * @param path config文件路径
     * @param nodeName 修改节点名
     * @param value 修改值
     * @return 修改节点数,如果返回-1,修改失败
     * @throws IOException
     */
    public int changeConfig(String path, String nodeName, String value) throws IOException{
        File config = new File(path);
        if( ! config.exists() || nodeName == null){
            return -1;
        }
        File configBak = new File(path + "_bak");
        //
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(config)));
        //
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configBak)));
        // 节点形式
        String nodeStart = "<" + nodeName + ">";
        String nodeEnd = "</" + nodeName + ">";
        String str;
        int i = 0;
        // 读取每一行
        while((str = reader.readLine()) != null ){
            str = str.trim();
            if(str.equals("") || str == null){
                continue;
            }
            // 匹配每一行
            if(str.startsWith(nodeStart) && str.endsWith(nodeEnd)){
                // .*?配任意数量的重复 (?<=exp)匹配exp后面的位置 (?=exp)匹配exp前面的位置
                str = str.replaceAll("(?<=>)(.*?)(?=<)", value);
                i ++;
            }
            writer.write(str + "\t\n");
            
        }
        writer.close();
        reader.close();
        // 流关闭后才能操作
        // 删除原配置文件
        config.delete();
        // 更新配置文件
        configBak.renameTo(config);

        return i;
    }


这个世界上总有更好的方式解决问题,试着用java中DOM解析的方式来解决下:

/**
     * 
     * @param path 配置文件路径
     * @param nodeName 节点名
     * @param nodeValue 修改成什么样value
     * @return
     * @throws Exception
     */
    public int changeConfig1(String path, String nodeName, String nodeValue) throws Exception{
        File config = new File(path);
        // 解析器工厂类
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
        // 解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        // 文档树模型Document
        Document document = db.parse(config);
        // A.通过xml文档解析
        NodeList nodeList = document.getElementsByTagName(nodeName);
        // B.将需要解析的xml文档转化为输入流,再进行解析
        //InputStream is = new FileInputStream(config);
        //Document nodeList = db.parse(is); 

        for (int i = 0; i < nodeList.getLength(); i++) {   
            // Element extends Node
            Element node = (Element)nodeList.item(i);
            System.out.println( node.getElementsByTagName("b").item(0).getFirstChild().getNodeValue());
            node.getElementsByTagName(nodeName).item(0).getFirstChild().setTextContent(nodeValue);
            System.out.println( node.getElementsByTagName("c").item(0).getFirstChild().getNodeValue());
        }
        // 是改动生效,网上很多代码都没有提到这步操作,我不明白他们是怎么完成修改xml的value值的。
        // 可以理解成内存中的数据已经被改了,还没有映射到文件中
        TransformerFactory tfFac = TransformerFactory.newInstance();
        Transformer tf = tfFac.newTransformer();
        DOMSource source = new DOMSource(document);
        tf.transform(source, new StreamResult(config));// 修改内容映射到文件
        return 0;
    }

 

今天读书的时候,理解到教育要从越小的时候开始越好,那时候记下的文章能20年不忘,20几岁后学得的技能,一个月不用就生疏了,看来是越大越没用啊!不进步不是停止不前,是退步,因为所有你身边的人都在进步。

----------------------------------------------------------------------

努力不一定成功,但不努力肯定不会成功。
共勉。

 

 

  

posted on 2012-08-26 19:27  每当变幻时  阅读(626)  评论(0编辑  收藏  举报

导航