将资源配置文件写入到文件:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* 只能存储字符串(key,value)
* 使用Properties输出到文件,也叫资源配置文件
* @author 30869
* 存储方法:
*后缀名为properties
*store(OutputStream out, String comments)
store(Writer writer, String comments)
后缀名为XML
storeToXML(OutputStream os, String comment)
storeToXML(OutputStream os, String comment, String encoding)
*
*/
public class ToFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
//创建资源文件对象
Properties properties=new Properties();
//存储信息
properties.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
properties.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
properties.setProperty("user", "scott");
properties.setProperty("pwd", "tiger");
//存储到G:/others 存在盘符的叫绝对路径
// properties.store(new FileOutputStream(new File("G:/others/db.properties")), "db配置");//程序与外界联系(checked),需要声明异常
// properties.storeToXML(new FileOutputStream(new File("G:/others/db.XML")), "db配置");
//存储到相对路径 默认为当前工程,也可以指定目录,比如src/db.properties
properties.store(new FileOutputStream(new File("src/com/lilin/Properties/db.properties")), "db配置");
}
}
读取资源配置文件(绝对路径和相对路径):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
* 使用Properties读取配置文件(绝对和相对路径(当前项目、工程 ))
*
* .properties load(InputStream inStream) load(Reader reader)
*
* .XML loadFromXML(InputStream in)
*
* @author 30869
*
*/
public class ReadProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties properties = new Properties();
// 读取资源配置文件 绝对路径
properties.load(new FileReader("G:/others/db.properties"));
// 输出资源文件内容
System.out.println(properties.getProperty("user","未找到"));
// 读取资源配置文件 相对路径
properties.load(new FileReader("db.properties"));
// 输出资源文件内容
System.out.println(properties.getProperty("uf","未找到"));
}
}
读取资源配置文件(类路径):
import java.io.IOException;
import java.util.Properties;
/**
* 使用类相对路径读取资源文件
* @author 30869
*
*/
public class ReadProperties2 {
public static void main(String[] args) throws IOException {
Properties properties=new Properties();
//类相对路径读取 斜杠 / 表示bin目录
properties.load(ReadProperties2.class.getResourceAsStream("/com/lilin/Properties/db.properties"));
System.out.println(properties.getProperty("pwd","未找到文件"));
//使用类加载器加载资源文件 空 "" 表示bin目录
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lilin/Properties/db.properties"));
System.out.println(properties.getProperty("pwd","未找到文件"));
}
}