配置文件:config.properties
配置文件的路徑:src/main/resources/static/config.properties
ip = 127.0.0.1
port = 8080
filepath = D:/download
username = root
password = 123456
一、使用阿里的fastjson
<!-- fastjson包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.alibaba.fastjson.JSONObject;
public class getPropertys {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
// 使用InPutStream流讀取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/resources/static/config.properties"));
properties.load(bufferedReader);
JSONObject obj = new JSONObject();
obj.put("ip",properties.getProperty("ip"));
obj.put("port",properties.getProperty("port"));
obj.put("filepath",properties.getProperty("filepath"));
obj.put("username",properties.getProperty("username"));
obj.put("password",properties.getProperty("password"));
System.out.println(obj.toString());
}
}
二、使用google的gson
<!-- gson包 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.google.gson.JsonObject;
public class getPropertys {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
// 使用InPutStream流讀取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/resources/static/config.properties"));
properties.load(bufferedReader);
JSONObject obj = new JSONObject();
JsonObject obj=new JsonObject();
obj.addProperty("ip",properties.getProperty("ip"));
obj.addProperty("port",properties.getProperty("port"));
obj.addProperty("filepath",properties.getProperty("filepath"));
obj.addProperty("username",properties.getProperty("username"));
obj.addProperty("password",properties.getProperty("password"));
System.out.println(obj.toString());
}
}