1.使用FileReader()方法
2.使用Thread.currentThread().getContextClassLoader()
2.1使用Test02.class.getClassLoader().getResourceAsStream()
3.ResourceBundle.getBundle()
4.使用 new ClassPathResource()
public class Test02 {
public static void main(String[] args) throws IOException {
//这种方式的路径缺点是:移植性差,在IDEA环境下可以使用这个方式,在IDEA中默认的当前路径是project的根.[和模块平级]
//这个代码假设离开了IDEA,换到了其他位置,可以当前路径就不是project的根了,这时这个路径就无效了.
//FileReader reader = new FileReader("day09\\class.properties");//使用相对路径
//FileReader reader = new FileReader("C:\\Users\\ma\\Desktop\\myprojects\\myprojectPowerNode\\day09\\class.properties");//使用绝对路径
//接下来说一种比较通用的一种路径.即使代码换位置了,这样编写任然是通用的.
//注意:使用以下通用方式的前提是:这个文件必须在类路径下[类路径:和com平级目录,存放.class文件的目录]
//在src下的都是在类路径下.
//src是类的根路径.
/*
介绍:
Thread.currentThread() 当前线程对象
getContextClassLoader() 是线程对象的方法,可以获得当前线程的类加载器对象.[启动加载器,扩展类加载器,应用类加载器]
getResiurce() [获取资源]这是类加载器对象的方法,当前线程的类加载器默认从类的根路径下加载资源.
*/
String path = Thread.currentThread().getContextClassLoader().getResource("class1.properties").getPath();
/*InputStream resourceAsStream = Test02.class.getClassLoader().getResourceAsStream("class1.properties");*/
System.out.println(path);
FileReader fr = new FileReader(path);
Properties properties1 = new Properties();
properties1.load(fr);
fr.close();
String className1 = properties1.getProperty("className");
System.out.println(className1);
//直接以流的形式返回
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("class1.properties");
Properties properties2 = new Properties();
properties2.load(resourceAsStream);
String className2 = properties2.getProperty("className");
System.out.println(className2);
//java.util包下提供了一个资源绑定器,便于获取属性文件的内容.
//使用以下这种方式的时候,属性配置文件xxx.properties必须放到类路径下.
/*
资源绑定器,只能绑定xxx.properties文件.并且这个文件必须在类路径下[类路径:和com平级目录,存放.class文件的目录]
并且在写路径的时候,路径后面的扩展名不能写
*/
ResourceBundle bundle = ResourceBundle.getBundle("class1");
String className = bundle.getString("className");
System.out.println(className);
}
}
ResourceBundle 配置文件国际化
1.在src目录下创建配置文件:配置文件的命名规则:自定义文件名_语言码_国别码.properties
例如:中文的配置文件:mypro_zh_CN.properties
英文的配置文件:mypro_en_US.properties
通过getBoundle的第二个参数选择哪个properties文件
2.
public class Test01 {
public static void main(String[] args) {
//1.获取一个ResourceBundle对象
//getBundle()方法自动去src目录下找mypro名字的配置文件,语言码:zh,国别码:CN
//根据语言码:zh,国别码:CN来定位具体解析是mypro_en_US.properties还是mypro_zh_CN.properties
ResourceBundle bundle = ResourceBundle.getBundle("mypro", new Locale("zh", "CN"));
//获取某个键的值
String bt1 = bundle.getString("bt");
System.out.println(bt1);
ResourceBundle bundle1 = ResourceBundle.getBundle("com//111", new Locale("en", "US"));
String string = bundle1.getString("ma");
System.out.println(string);
}
}
4 new ClassPathResource
String path = new ClassPathResource("fdfs_client.conf").getPath();