Java 读取文件

一、java读取JSON文件

读取json就依赖第三方

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.12</version>
        </dependency>    

代码如下:

    @Test
    public void JSONRead(){
        String class_path = JSONReadTest.class.getClassLoader().getResource("testData").getPath();

        String filePath = class_path+"/"+"readJson.json";
        String jsonString = null;
        try {
            jsonString = FileUtils.readFileToString(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(jsonString == null || jsonString.length()==0){
            return;
        }else{
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            System.out.println(jsonObject.getString("address"));
        }
    }

二、java读取properties文件

读取properties需要用到java.util包下的类,不需要引入其他第三方包,代码如下:

    @Test
    public void readProperties(){

        Properties p = new Properties();
        try {
            p.load(JSONReadTest.class.getClassLoader().getResourceAsStream("testData/read.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(p.getProperty("name"));
    }

 

posted @ 2019-07-22 14:53  苦心明  阅读(171)  评论(0)    收藏  举报