需求:读取D:/ABC/a.text中的内容并转换为集合
File file = new File("D:\\ABC\\a.txt");
//获取文件长度
Long fileLengthLong = file.length();
//创建一个数组
byte[] fileContent = new byte[fileLengthLong.intValue()];
if(file.exists()){
//如果文件存在
try {
//创建输入流
FileInputStream inputStream = new FileInputStream(file);
//读取内容
inputStream.read(fileContent);
//关闭流
inputStream.close();
//将字节数组转为String
String s = new String(fileContent);
//将json字符转为list
List<PointCollection> list = JSONObject.parseArray(s, PointCollection.class);
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
List<PointCollection> pointCollections = new ArrayList<>();
return pointCollections;
前提是文本中存的内容是对应的json串,否则会报json解析异常。