JAVA读取propertise文件内容两种方式(起始还是有很多种的)

/**
     * 读取propertise文件
     * @throws IOException
     */
    @Test
    public void fun1() throws IOException {
        /*方式一【采用反射的方式获取】:最常用的方式。常用于读取同一文件夹下的文件,若不在同一文件夹下,需要往上层找*/
        InputStream inputStream = this.getClass().getResourceAsStream("../../../../config.properties");//相对路径
        InputStream inputStream = this.getClaa().getClassLoader().getResourceAsStream("华融湘江的ID.txt");//获取类加载路径,读取src下的文件
        Properties properties = new Properties();
        properties.load(inputStream);
        System.out.println(properties.getProperty("password"));;

        /*方式二【采用ResourceBundle来获取本地资源】:只适用于资源文件在src下面的情况*/
        ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
        System.out.println(resourceBundle.getString("DMUserName"));


        /*方式三:以文件流的形式读取*/
        Properties properties = new Properties();
        properties.load(new FileReader("config.properties"));   
        System.out.println(properties.getProperty("password"));
        System.out.println(URLDecoder.decode(this.getClass().getResource("").getPath(),"utf-8"));//获取当前类所在的项目路径
    }

  项目结构如下: 

public class ReadText {

    public static void main(String[] args) {
        try {
            //FileReader fileReader = new FileReader("E:/移动计费的ID.txt");
            InputStream in = ReadText.class.getClassLoader().getResourceAsStream("华融湘江的ID.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuilder builder = new StringBuilder("0");
            String str = "";
            while((str=bufferedReader.readLine()) != null) {
                builder.append(","+str);
            }
            System.out.println(builder);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

  

原文地址:https://www.cnblogs.com/tangdrogn/p/8146503.html