① 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
讀取的時候寫,讀入文件(文件名),分割文本(文件名,#換行符,),再用分割文本(文件名,"=",)把名稱和數量分割開,不懂的話追問給你寫個完整的代碼