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(); } }
作者: lost blog
出处: http://www.cnblogs.com/JAYIT/
关于作者:专注服务器端开发
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接 如有问题, 可邮件(sawyershaw@qq.com)咨询.