在工作中,常常會遇到一些文件轉(zhuǎn)換的問題,比如從txt格式轉(zhuǎn)換為excel,還有從excel再轉(zhuǎn)換為txt,有普通格式轉(zhuǎn)換為JSON格式的,當(dāng)然也有再轉(zhuǎn)換回來的。
這些工作如果手動操作就想當(dāng)麻煩了,但是好在可以程序處理,下面這個例子就是從txt文本中讀取數(shù)據(jù),再解析JSON格式數(shù)據(jù)的問題,讓我們一起來看下處理過程。
主要分為兩部分,下面是具體實現(xiàn)。
1.讀取txt文件,一次性從內(nèi)存中讀取數(shù)據(jù)。
/**
* 解析txt文件
* @param filePath
* @return
*/
public static String readTxtFile(String filePath){
StringBuilder sb = new StringBuilder();
try {
String encoding="UTF-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判斷文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考慮到編碼格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
sb.append(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("讀取文件內(nèi)容出錯");
e.printStackTrace();
}
return sb.toString();
}
2.解析JSON格式數(shù)據(jù)
解析JSON一般常用的工具包有Google的Gson,JackJson和阿里巴巴的fastjson。
這里我使用最常用的fastjson。
引入jar包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
txt內(nèi)容:
[
{
"city_name": "北京",
"city_id": "bj"
},
{
"city_name": "上海",
"city_id": "sh"
},
{
"city_name": "廣州",
"city_id": "gz"
},
{
"city_name": "深圳",
"city_id": "sz"
}
]
下面是具體解析過程:
/**
* 把JSON文件轉(zhuǎn)換為一行一行的數(shù)據(jù)
* @param txt
* @return
*/
private static String parseJson(String txt){
//獲取jsonObject對象
JSONArray jsonArray = JSONObject.parseArray(txt);
StringBuilder sb = new StringBuilder();
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
JSONObject jsonObject = (JSONObject) iterator.next();
String cityName = String.valueOf(jsonObject.get("city_name"));
String cityId = String.valueOf(jsonObject.get("city_id"));
sb.append(cityId).append("=").append(cityName).append("\n");
}
return sb.toString();
}
總結(jié)
以上就是最基本的讀取txt文本和解析JSON的方法,歡迎與我溝通交流。