java导出txt文本

时间:2023-01-19 17:03:06

页面

java导出txt文本

项目结构

java导出txt文本

html代码

<html>
</head> <body>
<form action="down/downLoad" method="post">
<input type="text" name="name">
<input type="submit" value="Submit" />
</form>
</body>
</html>

注意form表单路径,也可以用request.getContextPath()/down/downLoad

web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app>     <display-name>Spring MVC Application</display-name>
  
    <servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
  
    <servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
  
    <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:mvc-dispatcher-servlet.xml</param-value>
</context-param>
  
    <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

 

spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" > <context:component-scan base-package="main.*" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/pages</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/Student?useUnicode=true&characterEncoding=UTF-8"
p:username="root"
p:password="root" />
</beans>

  

 如果不从数据库查的话只用到controller就行了,List的数据自己构造

controller

package main.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import main.dao.GetInfoDao;
import main.model.Student; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/down")
public class DownLoadController {
@Autowired
private GetInfoDao dao; @RequestMapping("/downLoad")
public void down(HttpServletRequest request,
HttpServletResponse response){
String name=request.getParameter("name");
System.out.println("name:"+name);
//List<Student> students=dao.getInfo();
List<String> students = new ArrayList<String>();
students.add("111111");
students.add("222222");
students.add("333333");
students.add("444444");
students.add("555555");
//List<Student> students={};
exportText(response, students);
}
public void exportText(HttpServletResponse response,List students){
response.setContentType("text/plain");// 一下两行关键的设置
response.addHeader("Content-Disposition","attachment;filename=20160629.txt");
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String tab = " ";
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
outSTr = response.getOutputStream();
buff = new BufferedOutputStream(outSTr);
for (Object li :students) {
write.append("名字:" + tab);
write.append(li + enter);
write.append(enter);
}
buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (IOException e) {
e.printStackTrace();
}// 建立
}
}

结果,导出来的数据

  java导出txt文本

用到数据库的话,把数据库的数据查询出来放到List集合即可

这时候需要更新spring配置,XML配置不需要更改

我这使用springJdbc操作

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" > <context:component-scan base-package="main.*" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/pages</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/Student?useUnicode=true&characterEncoding=UTF-8"
p:username="root"
p:password="root" />
<!-- 定义jdbc模板的bean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
</beans>

Student:

 

package main.model;

import org.springframework.stereotype.Component;

@Component
public 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;
}
}

DAO:

package main.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import main.model.Student; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; @Repository
public class GetInfoDao {
@Autowired
private JdbcTemplate template; public List<Student> getInfo(){
String sql="select * from T_Student";
List<Student> students=new ArrayList<Student>();
students=template.query(sql, new StudentMapper());
return students; }
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
} }

Controller: 

 

package main.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.List; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import main.dao.GetInfoDao;
import main.model.Student; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/down")
public class DownLoadController {
@Autowired
private GetInfoDao dao; @RequestMapping("/downLoad")
public void down(HttpServletRequest request,
HttpServletResponse response){
String name=request.getParameter("name");
System.out.println("name:"+name);
List<Student> students=dao.getInfo();
exportText(response, students);
}
public void exportText(HttpServletResponse response,List students){
response.setContentType("text/plain");// 一下两行关键的设置
response.addHeader("Content-Disposition","attachment;filename=20160629.txt");
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String tab = " ";
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
outSTr = response.getOutputStream();
buff = new BufferedOutputStream(outSTr);
write.append("ID"+tab+"姓名"+tab+"年龄"+ enter);
for (int i=0;i<students.size();i++) {
Student s=(Student)students.get(i);
write.append(s.getId()+ tab);
write.append(s.getName()+ tab);
write.append(s.getAge()+ enter);
write.append(enter);
}
buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (IOException e) {
e.printStackTrace();
}// 建立
}
public String delNull(String str){
String xx="****";
if (str!=null||!"".equals(str)){
xx=str;
}
return xx; } }

导出来的数据截图:

 java导出txt文本 

 

如果数据量大的话则采用先把数据写到一个文件里面,然后再去下载这个文件