读取文件:
public static void read2(String filePath){
File file = new File(filePath);
if(file.exists()){
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String lineContent = null;
while((lineContent = br.readLine())!=null){
System.out.println(lineContent);
}
br.close();
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("no this file");
e.printStackTrace();
} catch (IOException e) {
System.out.println("io exception");
e.printStackTrace();
}
}
Gson字符串数组转成List对象:
1.数组转List
Student[] array = new Gson().fromJson(jsonString,Student[].class);
List<Student> list = Arrays.asList(array);
Log.i("lxc"," ---> " + list);
2.用typeToken转化
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> list = new Gson().fromJson(jsonString,type);
3.使用泛型抽象
public <T> List<T> parseString2List(String json,Class clazz) {
Type type = new ParameterizedTypeImpl(clazz);
List<T> list = new Gson().fromJson(json, type);
return list;
}
private class ParameterizedTypeImpl implements ParameterizedType {
Class clazz;
public ParameterizedTypeImpl(Class clz) {
clazz = clz;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
@Override
public Type getRawType() {
return List.class;
}
@Override
public Type getOwnerType() {
return null;
}
}
使用:
List<Student> list = parseString2List(jsonString, Student.class);
List<Book> list2 = parseString2List(jsonString, Book.class);