source.conf配置文件
screen={
m
{"name":"巴南区交委防火墙", "x":20, "y":40},
{"name":"巴南区交委交换机", "x":25, "y":40},
{"name":"巴南区路政", "x":28, "y":50}
]
device={
router=100
switch=200
firewall=90
camera=1
server=50
}
}
package com.mvc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
public class FileInputStreamDemo {
private static final int SIZE = 4096;
public static void main(String[] args) throws IOException {
/*
* 将已有文件的数据读取出来
* 既然是读,使用InputStream
* 而且是要操作文件 FileInputStream
*
*/
//为了确保文件一定在之前是存在的,将字符串路径封装成File对象
File file = new File("src/main/java/com/mvc/configure/source.conf");
if(!file.exists()){
throw new RuntimeException("要读取的文件不存在");
}
//创建文件字节读取流对象时,必须明确与之关联的数据源。
FileInputStream fis = new FileInputStream(file);
//创建一个字节数组,定义len记录长度
int len = 0;
byte[] buf = new byte[SIZE];
while((len=fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
//关资源
fis.close();
}
}
一行一行的读取. redeLine()
然后在进行字符串切割.
public class Bean {
private String name;
private int x;
private int y;
BufferedReader bw=null;
StringBuffer sb=null;
try {
bw=new BufferedReader(new FileReader("src/source.conf"));
sb=new StringBuffer();
String line=null;
while((line=bw.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String result=sb.toString().replaceAll("\\s+", "");
Pattern p = Pattern.compile("m//正则表达式提取
Matcher m = p.matcher(result);
while(m.find()){
String res=m.group();
res=res.substring(res.indexOf("["), res.lastIndexOf("]")+1);
Gson gson=new Gson();
List beans=gson.fromJson(res, new TypeToken<>>() {}.getType());//Gson转为List集合
System.out.println(beans);
}