java.io.Writer.write()剥离双反斜杠\\

时间:2013-05-16 05:18:31

标签: java string properties

我正在从Windows机器的文件目录中读取:

C:\\some dir\\someDir

当我使用java.io.Writer.write()将其写入文件时,某些\\字符会被删除吗?我的输出如下:

C:some dirsomeDir

我的方法:

    /**
     * Sets the property value for given property.
     *     Allows for either overwriting the original file from what
     *     is in memory (default Java Properties API behavior) or perform
     *     an in-place update of a given property.
     * 
     * @param propertyName Name of property to be changed.
     * @param value Value to change named property to.
     * @param overwrite True to overwrite (replace) properties file with what is in memory 
     *             (no guarantee of property order and comments will be gone),
     *             False to update properties file (preserve comments and property order etc).
     * @return Return's true if successful operation, false if something failed.
     */
    public boolean setConfig(String propertyName, String value, boolean overwrite) {
        if (overwrite) {
            try {
                this.prop.load(new FileInputStream(this.propertyFile));
            } catch (IOException e) {
                return false;
            }
            this.prop.setProperty(propertyName, value);
            try {
                this.prop.store(new FileOutputStream(this.propertyFile), null);
            } catch (IOException e) {
                return false;
            }
            return true;
        } else {

            BufferedReader br = null;
            BufferedWriter bw = null;

            try {

                String curVal = this.getConfig(propertyName);

                FileInputStream fis = new FileInputStream(new File(this.propertyFile));
                br = new BufferedReader(new InputStreamReader(fis));

                String str = "";
                String line = br.readLine();
                while (line != null) {
                    str = str.concat(line.concat(System.getProperty("line.separator")));
                    line = br.readLine();
                }

                FileWriter fw = new FileWriter(new File(this.propertyFile));
                bw = new BufferedWriter(fw);

                bw.write(str.replace(propertyName + "=" + curVal, propertyName + "=" + value));

            } catch (IOException | ConfigException e) {
                return false;
            } finally {
                try {
                    br.close();
                    bw.close();
                } catch (IOException e) {
                    // does not matter
                }
            }
            return true;
        }
    }

0 个答案:

没有答案