有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文件加载和保存属性

在我的spring项目中,我的类路径中有一个名为database的文件。具有以下内容的属性:

jdbc.Classname=org.postgresql.Driver
jdbc.url=
jdbc.user=
jdbc.pass=
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate

在我的一个服务类中有一个方法,通过hibernate手动将数据库模式导出到服务器。目前,本规范中的方法为:

public void create_tables(String maquina, String usuario, String senha) {
    Configuration config = new Configuration();
            SchemaExport schema = new SchemaExport(config);
            schema.create(true, true);
}

我想从文件数据库加载属性。属性,设置传递给此变量中方法的值(url、user和pass),并将此新配置保存在同一文件中

任何人都能指出这样做的方向吗


共 (3) 个答案

  1. # 1 楼答案

    示例:从文件加载道具。 我们有文件名为conf.props的测试配置文件 包含:

    key0=value0
    key1=value1
    

    应用程序中的下一类加载属性:

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class LogProcessor {
    
    
    
        public void start(String fileName ) throws IOException {
    
            Properties prop = new Properties();
            FileInputStream fis = new FileInputStream(fileName);
            prop.load(fis);
    
            System.out.println (prop.getProperty("key0"));
        }
    }
    

    如何运行:

    public static void main(String[] args) {
    
            try {
                new LogProcessor().start();
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    返回值0

    \|/73

  2. # 2 楼答案

    I have in my classpath a file named database.properties

    I want load the properties from file database.properties in my config variable, set up the values I pass to the method in this variable (url, user and pass), and save this new configuration in the same file.

    这至少是困难的,也许是不可能的

    您试图更新的“文件”可能根本不是文件。它可能是更大的JAR或ZIP文件的一个组件。它可能是已下载内容的内存或磁盘缓存。它可能(假设)已使用公钥/私钥加密。。。我们没有“加密”密钥

    除了困难之外,这是个坏主意。假设您的服务部署为WAR文件,并且属性文件在WAR中交付。您可以修改属性。。。等等然后,出于某种原因,你重新部署了战争。这将覆盖您的配置

    如果您希望配置属性是可更新的,那么它们不应该位于类路径上。将文件放入单独的目录(webapp树之外…)并通过文件路径名或file:URL访问它


    I try remove the classpath:, but I face the error Caused by: java.io.FileNotFoundException: class path resource [database.properties] cannot be opened because it does not exist

    看起来您正在使用属性文件的(不正确)相对路径

    将文件复制到(比如)“/tmp/database.properties”,将注释更改为

        @PropertySource("/tmp/database.properties")
    

    看看这是否有效。如果确实如此,那么您可以找到一个更合适的位置来存储文件。但正如我上面所说的,如果您试图更新webapp目录中的文件,那么在重新部署时,它很有可能会被破坏。所以不要把它放在那里

  3. # 3 楼答案

    这样行吗

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream( "database.properties" );
    props.load( fis );
    fis.close();
    
    props.setProperty("jdbc.url", {{urlvalue}} );
    props.setProperty("jdbc.user", {{user value}} );
    props.setProperty("jdbc.pass", {{pass value}} );
    
    FileOutputStream fos = new FileOutputStream( "database.properties" );
    props.store( fos );
    fos.close();