2020-06-12 一行一行讀取文件以及數(shù)組轉(zhuǎn)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字符串?dāng)?shù)組轉(zhuǎn)成List對象:
1.數(shù)組轉(zhuǎn)List

Student[] array = new Gson().fromJson(jsonString,Student[].class);
List<Student> list = Arrays.asList(array);
Log.i("lxc"," ---> " + list);

2.用typeToken轉(zhuǎn)化

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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容