gpt4 book ai didi

Java 编写/编辑属性文件

转载 作者:行者123 更新时间:2023-12-02 04:06:47 31 4
gpt4 key购买 nike

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

这是代码:

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"),则仅当您未指定目录时才会使用当前工作目录。

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

关于Java 编写/编辑属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34210006/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com