java CSV写文件

@Test
    public void write(){
    try {
             // 创建CSV写对象
    List<Student> ls=new ArrayList<Student>();
             for (int i = 0; i <1000000; i++) {
            Student s=new Student();
            s.setName("小帅"+i);
            s.setAge(i);
            s.setScore("100"+i);
            s.setSex("男"+i);
            ls.add(s);
}
             //写入临时文件
             File tempFile = File.createTempFile("vehicle", ".csv");
             CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(),',', Charset.forName("UTF-8"));
             // 写表头
             long s= System.currentTimeMillis();
             System.err.println();
             String[] headers = {"姓名","年龄","编号","性别"};
             csvWriter.writeRecord(headers);
             for (Student stu : ls) {
        csvWriter.write(stu.getName());
        csvWriter.write(stu.getAge()+"");
        csvWriter.write(stu.getScore());
        csvWriter.write(stu.getSex());
        csvWriter.endRecord();
        }
             csvWriter.close();
             long e=System.currentTimeMillis();

             System.err.println(e-s);;

   /**
    * 写入csv结束,写出流
    */
   java.io.OutputStream out = getResponse.getOutputStream();  
   byte[] b = new byte[10240];
   java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());  
   getResponse.reset();
   getResponse.setContentType("application/csv");  
   getResponse.setHeader("content-disposition", "attachment; filename=vehicleModel.csv");  
    long fileLength = fileLoad.length();  
    String length1 = String.valueOf(fileLength);  
    getResponse.setHeader("Content_Length", length1);  
    java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);  
    int n;  
    while ((n = in.read(b)) != -1) {  
       out.write(b, 0, n); //每次写入out1024字节 
    }  
       in.close();  
       out.close(); 

         } catch (IOException e) {
             e.printStackTrace();
         }
    }

 

posted @ 2023-02-21 16:16  Lost blog  阅读(156)  评论(0编辑  收藏  举报