繁体   English   中英

Java编写/编辑属性文件

[英]Java writing/editing a properties file

我有一个非常困惑的问题。 我正在尝试更改我的属性文件中的属性,但是它没有改变...

这是代码:

package config;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

    /**
     * @author Crunchify.com
     * 
     */
    public class CrunchifyGetPropertyValues {
        String result = "";
        InputStream inputStream;

        public String getPropValues() throws IOException {

            try {
                Properties prop = new Properties();
                String propFileName = "config.properties";

                inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

                if (inputStream != null) {
                    prop.load(inputStream);
                } else {
                    throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
                }

                Date time = new Date(System.currentTimeMillis());

                // get the property value and print it out
                String user = prop.getProperty("user");
                String company1 = prop.getProperty("company1");
                String company2 = prop.getProperty("company2");
                String company3 = prop.getProperty("company3");
                prop.setProperty("company1", "Amazon");
                prop.store(new FileOutputStream("config.properties"), null);

                // result = "Company List = " + company1 + ", " + company2 + ", " +
                // company3;
                // System.out.println(result + "\nProgram Ran on " + time + " by
                // user=" + user);
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            } finally {
                inputStream.close();
            }
            return result;
        }
    }## Heading ##

我专门看的代码是

prop.setProperty("company1", "Amazon");
prop.store(new FileOutputStream("config.properties"), null);

由于某些原因,我的属性文件不会更改...

 #Crunchify Properties
    user=Crunchify
    company1=Google
    company2=eBay
    company3=Yahoo

任何帮助表示赞赏

当您使用getResourceAsStream( ,它将从类路径中检索文件。例如,如果您在类路径中具有/home/user/resources ,它将在其中查找文件。

如果使用new FileOutputStream("config.properties") ,则仅在未指定目录的情况下,才使用当前工作目录。

简而言之,它是在写入属性,而不是正在读取的属性。 您可以在类路径中写入一个,只要它来自目录,但是我建议您仅写入当前工作目录或配置中提供的目录。

我认为这是因为您正在从一个位置(即资源)读取文件,并且可能是正在将文件保存在另一位置(即当前工作目录)中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM