当前位置:首页 » 数据仓库 » 如何读配置文件
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

如何读配置文件

发布时间: 2022-09-22 10:42:26

① java 怎么读取配置文件

一.读取xml配置文件
(一)新建一个java bean(HelloBean. java)

java代码
(二)构造一个配置文件(beanConfig.xml)
xml 代码
(三)读取xml文件
1.利用

java代码
2.利用FileSystemResource读取
java代码
二.读取properties配置文件
这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
我们还利用上面的HelloBean. java文件,构造如下beanConfig.properties文件:
properties 代码
helloBean.class=chb.demo.vo.HelloBean
helloBean.helloWorld=Hello!chb!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.来读取属性文件

java代码

(二)利用java.util.Properties读取属性文件
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
properties 代码
ip=192.168.0.1
port=8080
三.读取位于Jar包之外的properties配置文件

下面仅仅是列出读取文件的过程,剩下的解析成为properties的方法同上
1 FileInputStream reader = new FileInputStream("config.properties");

2 num = reader.read(byteStream);

3 ByteArrayInputStream inStream = new ByteArrayInputStream(byteStream, 0, num);

四.要读取的配置文件和类文件一起打包到一个Jar中
String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码
JarFile currentJar = new JarFile(currentJarPath);
JarEntry dbEntry = currentJar.getJarEntry("包名/配置文件");
InputStream in = currentJar.getInputStream(dbEntry);
//以上YourClassName是class全名,也就是包括包名

修改:
JarOutputStream out = new FileOutputStream(currentJarPath);
out.putNextEntry(dbEntry);
out.write(byte[] b, int off, int len); //写配置文件
。。。

out.close();

② 是怎么读取配置文件的

<!-- 正文开始 -->
一般来说。我们会将一些配置的信息放在。properties文件中。
然后使用${}将配置文件中的信息读取至spring的配置文件。

那么我们如何在spring读取properties文件呢。

1.首先。我们要先在spring配置文件中。定义一个专门读取properties文件的类.
例:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
<!--要是有多个配置文件,只需在这里继续添加即可 -->
</list>
</property>
</bean>

这里为什么用locations(还有一个location)
是因为。一般来说。我们的项目里面。配置文件可能存在多个。
就算是只有一个。那将来新添加的话。只需在下面再加一个value标签即可。
而不必再重新改动太多。(当然。性能上是否有影响,这个以当前这种服务器的配置来说。是基科可以忽略不计的)。

然后我们就可以在jdbc.properties文件中填写具体的配置信息了。

<!-- 配置C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>

jdbc.properties文件写的信息。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

附加一个列子:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:/data/pc-config/passport.properties</value>
<value>classpath:memcached.properties</value>
</list>
</property>
</bean>
classpath:是指的当前类文件的目录下。
file:在window下是指的当前分区(比如你的项目是放在d盘,则是在d:/data/pc-config/passport.properties)
在linux下,则是当前路径下的文件/data/pc-config/passport.properties

③ 怎么读取tomcat中的配置文件

最常用读取properties文件的方法
InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");
Java中获取路径方法
获取路径的一个简单实现
反射方式获取properties文件的三种方式

1 反射方式获取properties文件最常用方法以及思考:
Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:

InputStream in = getClass().getResourceAsStream("资源Name");

这里面有个问题,就是getClass()调用的时候默认省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。

问题是:假如我不想让某个类有对象,那么我会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,我要在静态块或者静态方法中获取properties文件,这个方法就行不通了。

那怎么办呢?其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那还不容易啊--
取所有类的父类Object,用Object.class难道不比你的用你正在写类自身方便安全吗 ?呵呵,下面给出一个例子,以方便交流。
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;

/**

④ 用C#如何读写配置文件

INI文件就是扩展名为"ini"的文件。
其一般形式如下:
[section1] // 配置节
//键名 //键值
keyword1 = valuel
keyword2 = value2
……
[section2]
keyword3 = value3
keyword4 = value4
在Windows系统中,INI文件是很多,最重要的就是"System.ini"、"System32.ini"和"Win.ini"。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。以及XML文件的国际标准化给INI文件又一次打击。
但在某些场合,INI文件还拥有其不可替代的地位。比如绿色软件的规定就是不向注册表和系统中填入新东西。对于软件需要储存的信息就需要存入到文件中了。XML虽然兼容性比较好,但对于仅仅保存几个自定义参数而言就显得大材小用了。这是就可以选择使用快速简单的储存方式:INI文件。
本文就来探讨一下C#是如何对INI进行读写操作。
主要思路是调用Win32 API。
1.引入命名空间
usingSystem.Runtime.InteropServices;
2.声明(把一个Win32 API函数转成C#函数)
//声明INI文件的写操作函数 WritePrivateProfileString()
[DllImport("kernel32")]
private static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath);
//声明INI文件的读操作函数 GetPrivateProfileString()
[DllImport("kernel32")]
private static extern intGetPrivateProfileString(string section, string key, string def, StringBuilderretVal, int size, string filePath);
3.函数
public void Writue(string section,string key, string value)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section,key, value, sPath);
}
public string ReadValue(stringsection, string key)
{
// 每次从ini中读取多少字节
System.Text.StringBuilder temp =new System.Text.StringBuilder(255);
// section=配置节,key=键名,temp=上面,path=路径
GetPrivateProfileString(section,key, "", temp, 255, sPath);
returntemp.ToString(); //注意类型的转换
}
到此基本功能已经实现了。下面我们将所有的代码重新整合一下:
namespace Library.File
{
public class Ini
{
// 声明INI文件的写操作函数 WritePrivateProfileString()
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath);
// 声明INI文件的读操作函数 GetPrivateProfileString()
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern intGetPrivateProfileString(string section, string key, string def,System.Text.StringBuilder retVal, int size, string filePath);
private string sPath = null;
public Ini(string path)
{
this.sPath = path;
}
public void Writue(string section,string key, string value)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section,key, value, sPath);
}
public string ReadValue(stringsection, string key)
{
// 每次从ini中读取多少字节
System.Text.StringBuilder temp =new System.Text.StringBuilder(255);
// section=配置节,key=键名,temp=上面,path=路径
GetPrivateProfileString(section,key, "", temp, 255, sPath);
return temp.ToString();
}
}
}
开始调用函数。
// 写入ini
Ini ini = newIni("C:/config.ini");
ini.Writue("Setting","key1", "HELLO WORLD!");
ini.Writue("Setting","key2", "HELLO CHINA!");
// 读取ini
Ini ini = newIni("C:/config.ini");
string str1 =ini.ReadValue("Setting", "key1");
MessageBox.Show(str1);
二,在一些小的应用中,有时候不需要使用数据困这样大规模的数据管理工具,也很少进行数据的查询、修改等操作,而仅用文件来存储数据。这时就需要使用。net中的文件操作对象,如file、streamReader、streamWriter等。
1,使用File对象操作文件
System.IO.File类提供了一系类的静态办法,完成对晚间的常用操作,如新建、删除、拷贝、移动等
2,使用StreamWriter写入文件
在System.IO空间中定义了一个文件写入器对象StreamWriter,使用它可以以一种特定的编码向输出流中(Stream)写入字符。
3,使用SteamReader读取文件
与streamWrite对应

⑤ SpringBoot 如何优雅读取配置文件10分钟教你搞定

很多时候我们需要将一些常用的配置信息比如阿里云 oss 配置、发送短信的相关信息配置等等放到配置文件中。

下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。

application.yml 内容如下:

wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: [email protected]:location: 湖北武汉加油中国加油books:    -name: 天才基本法description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。    -name: 时间的秩序description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。    -name: 了不起的我description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?

1.通过 @value 读取比较简单的配置信息

使用 @Value("${property}") 读取比较简单的配置信息:

@Value("${wuhan2020}")String wuhan2020;

需要注意的是 @value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。

2.通过@ConfigurationProperties读取并与 bean 绑定

LibraryProperties 类上加了 @Component 注解,我们可以像使用普通 bean 一样将其注入到类中使用。

importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@Component@ConfigurationProperties(prefix ="library")@Setter@Getter@{privateString location;privateList books;@Setter@Getter@ToStringstaticclassBook{        String name;        String description;    }}

这个时候你就可以像使用普通 bean 一样,将其注入到类中使用:

packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/** *@authorshuang.kou */@ntsInitializingBean{privatefinalLibraryProperties library;(LibraryProperties library){this.library = library;    }publicstaticvoidmain(String[] args){        SpringApplication.run(.class,args);    }@(){        System.out.println(library.getLocation());        System.out.println(library.getBooks());    }}

控制台输出:

湖北武汉加油中国加油[LibraryProperties.Book(name=天才基本法, description........]

3.通过@ConfigurationProperties读取并校验

我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式:

my-profile:name: Guide哥email: koushuangbwcx@

ProfileProperties 类没有加 @Component 注解。我们在我们要使用ProfileProperties 的地方使用@

EnableConfigurationProperties注册我们的配置 bean:

importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@{@NotEmptyprivateString name;@Email@NotEmptyprivateString email;//配置文件中没有读取到的话就用默认值privateBooleanhandsome =Boolean.TRUE;}

具体使用:

packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/** *@authorshuang.kou */@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class){privatefinalProfileProperties profileProperties;(ProfileProperties profileProperties){this.profileProperties = profileProperties;    }publicstaticvoidmain(String[] args){        SpringApplication.run(.class,args);    }@(){        System.out.println(profileProperties.toString());    }}

因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:

Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:koushuangbwcx@Origin:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress

我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:

ProfileProperties(name=Guide哥, [email protected], handsome=true)

4.@PropertySource读取指定 properties 文件

importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@SetterclassWebSite{@Value("${url}")privateString url;}

使用:

@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn/

5.题外话:Spring 加载配置文件的优先级

Spring 读取配置文件也是有优先级的,直接上图:

原文链接:https://www.toutiao.com/a6791445278911103500/?log_from=7f5fb8f9b4b47_1640606437752

⑥ 如何读取配置文件里的配置信息

以JAVA为例:

读取配置文件中数据的具体方法:

1、先在项目中创建一个包(如:config),再创建一个配置文件(如:a.properties),添加配置信息如下:
比如:

name=kaka
age=28

代码如下:

importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
publicclassPropertyTest{
publicstaticvoidmain(String[]args){
PropertyTestloadProp=newPropertyTest();
InputStreamin=loadProp.getClass().getResourceAsStream("/config/a.properties");
Propertiesprop=newProperties();
try{
prop.load(in);
}catch(IOExceptione){
e.printStackTrace();
}
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("age"));
}
}

⑦ 用java 如何读取配置文件(如:资源文件)中配

java读取配置文件的几种方法如下:
方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
方式三:采用ClassLoader方式进行读取配置信息
优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
缺点:只能加载类classes下面的资源文件。
方法4 getResouceAsStream
XmlParserHandler.class.getResourceAsStream 与classloader不同

使用的是当前类的相对路径

⑧ 易语言如何读取配置项文件里所有的配置项

貌似是取不了配置项名称的,可以不用配置项,用写到文本
石头=20
沙子=70
汽车=80
读取的时候写,读入文件(文件名),分割文本(文件名,#换行符,),再用分割文本(文件名,"=",)把名称和数量分割开,不懂的话追问给你写个完整的代码