2020-06-12 一行一行读取文件以及数组转List

读取文件:

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 list = Arrays.asList(array);
Log.i("lxc"," ---> " + list);

2.用typeToken转化

Type type = new TypeToken>(){}.getType();
List list = new Gson().fromJson(jsonString,type);

3.使用泛型抽象

    public  List parseString2List(String json,Class clazz) {
        Type type = new ParameterizedTypeImpl(clazz);
        List 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 list = parseString2List(jsonString, Student.class);
List list2 = parseString2List(jsonString, Book.class);

你可能感兴趣的:(2020-06-12 一行一行读取文件以及数组转List)