Java读取文件 I/O模型

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @Author: Yongkang Hou
 */
public class FileReadTest {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            //获取文件地址
            String pathname = "/Users/houyongkang/Downloads/Student.csv";
            // 建立一个输入流对象reader
            InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(pathname)), "GB2312");
            //存入缓存
            br = new BufferedReader(reader);
            String line;
            List  students = new ArrayList ();
            while ((line = br.readLine()) != null) {
                String temp[] = line.split(",");
                Student student = new Student();
                student.setId(Integer.parseInt(temp[0]));
                student.setAge(Integer.parseInt(temp[1]));
                student.setName(temp[2]);
                students.add(student);
            }
            for (Student s : students) {
            //已json格式输出
                System.out.println(JSONObject.toJSONString(s));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static class Student {
        private int id;
        private String name;
        private int age;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

你可能感兴趣的:(java后端,java,读取文件)