java将查询数据转化为txt文件
package com.elite.hisservice.utils;
import org.apache.commons.io.LineIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* 读取文件类 txt将txt文件保存到数据库
*/
public class FileUtils {
private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
// 使用commons-io.jar包的FileUtils的类进行读取
public static String [] readTxtFileByFileUtils(String fileName) {
File file = new File(fileName);
//返回每一行切割的数据
String[] linarr = new String[0];
try {
LineIterator lineIterator = org.apache.commons.io.FileUtils.lineIterator(file, "GB2312");
while (lineIterator.hasNext()) {
String line = lineIterator.nextLine();
// 行数据转换成数组
linarr = line.split("\t");
}
} catch (IOException e) {
e.printStackTrace();
logger.info("分割数组中出现异常"+e.getMessage());
}
return linarr;
}
/**
* 将字符串内容写入txt
* @param text 写入的字符串内容文件
* @param filename
* @throws IOException
*/
public static void writeToTextFile(String text,String filename) throws IOException {
try {
File file = new File(filename); // 相对路径,如果没有则要建立一个新的output。txt文件
// 创建新文件
file.createNewFile();
// write 解决中文乱码问题
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
BufferedWriter out = new BufferedWriter(fw);
out.write(text+"\r\n"); // \r\n即为换行
out.flush(); // 把缓存区内容压入文件
out.close(); // 最后记得关闭文件
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 使用common-io的FileUtils将zip文件转化为byte[]
*/
public static byte[] toByteArray1(String filePath) throws Exception {
File file = new File(filePath);
if(!file.exists()){
return new byte[0];
}
return org.apache.commons.io.FileUtils.readFileToByteArray(file);
}
/**
*将zip文件转化字节流数组
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filename) throws IOException{
File f = new File(filename);
if(!f.exists()){
throw new FileNotFoundException(filename);
}
//字节数组输出
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());
BufferedInputStream in = null;
try{
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while(-1 != (len = in.read(buffer,0,buf_size))){
bos.write(buffer,0,len);
}
return bos.toByteArray();
}catch (IOException e) {
e.printStackTrace();
throw e;
}finally{
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 将byte转化为zip文件
*/
public static void convertByteArrayToZipFile(byte[] certFile,String filePath) throws IOException{
File zipFile = new File(filePath);
try{
OutputStream out = new FileOutputStream(zipFile);
out.write(certFile);
out.flush();
}catch (Exception e){
throw new IOException(e);
}
}
}