Java生成批量txt文件,可以通过循环便利生成,示例如下:
response.setContentType(CONTENT_TYPE)response.setHeader("Content-disposition", "inlinefilename=\""+ new String( fileName.getBytes("gb2312"), "ISO8859-1" )+"\"")
HashMap paras = new HashMap()
paras = (HashMap)model.get("paras")
//要导出的文件,其实是Json对象,通知我们要导出哪些表
String files = MapUtils.getString(paras, "file")
//解析成数组
String[] file = files.split(",")
//获取压缩包文件名
String fileName = SysParaConfig.getProperty("fileName")
String fileName = new String(fileName + ".zip")
File[] files = new File[file.length]
String path = request.getRealPath("test/download")
//循环遍历生成文件
for(int i = 0i < file.lengthi++){
String table = file[i]
File toFile = new File(path+"/"+table+".TXT")
if(!toFile.exists()){
toFile.createNewFile()
}
FileOutputStream fos = new FileOutputStream(toFile)
StringBuffer sbf= new StringBuffer()
//结果集,按一定规则(比如数据间隔符)查询表
String resultSql = ""
String fieldSql = ""
ListfileData =
jdbcTemplate.queryForList(fieldSql + " union all " +resultSql )
int dataSize = fileData.size()
for(int j = 0 j < dataSize j++){
String result = (String)fileData.get(j).get("data")
sbf.append(result)
if(j != dataSize -1){
sbf.append("\r\n")
}
}
}
fos.write(strBuf.toString().getBytes("GBK"))
fos.flush()
fos.close()
}
生成TXT的方法有很多的。常用位字节流和字符流import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
public class TextFileGenerator {
public static void main(String[] args) throws Exception {
method1()
method2()
}
private static void method1() throws Exception {
String txtContent = "Hello World!"
File file = new File("test1.txt")
FileWriter fw = new FileWriter(file)
fw.write(txtContent)
fw.close()
}
private static void method2() throws Exception {
String txtContent = "Hello World!"
File file = new File("test2.txt")
FileOutputStream fos = new FileOutputStream(file)
fos.write(txtContent.getBytes())
fos.close()
}
}
package fileimport java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
/** 用FileOutputStream类往指定文件中写入数据 */
public class FileOutputStreamTest {
public static void main(String[] args) {
FileOutputStream out = null
try {
//step1: 创建一个向指定名的文件中写入数据的FileOutputStream
//第二个参数设置为true表示:使用追加模式添加字节
out = new FileOutputStream("D:\\IOTest\\dest.txt",true)
//step2: 写数据
out.write('#')
out.write("helloWorld".getBytes())
out.write("你好".getBytes())
out.write("\r\n".getBytes())//换行
out.write("百度新浪".getBytes())
//step3: 刷新此输出流
out.flush()
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) { // 捕获IO异常
e.printStackTrace()
}finally{
if(out != null){
try {
out.close() //step4: 关闭输出流
} catch (IOException e) {
e.printStackTrace()
} } } }}
给你看看我写的 参考下吧
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)