Java 讀取檔案

lixon166發表於2021-01-17

一、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"));
    }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69992808/viewspace-2750553/,如需轉載,請註明出處,否則將追究法律責任。

相關文章