java如何导出txt文件

hnnxzhoujia hnnxzhoujia 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我想把我获得的数据(一个list),导出成固定路径的TXT文本文件
要导出的格式如下:
city ¦area_code ¦start_gt ¦hlr_name ¦ //这是表示数据库的字段
金华 ¦579 ¦861373892 ¦金华HLR3 ¦ //这是依次对应的数据
金华 ¦579 ¦861373893 ¦金华HLR3 ¦
金华 ¦579 ¦861373894 ¦金华HLR3 ¦
金华 ¦579 ¦861373895 ¦金华HLR3 ¦

我做过一个导出EXCEL文件的例子,但导出TXT没用过.哪位有这方面的开发经验,请教一下,生成TXT用哪个类啊,我是开发新手,请高人详细指点下,谢谢
我导出EXCEL的文件如下:
public class ExportExcel {

public static byte[] toSellExcel(String[] column, List list, String filename,
String[] excelFile) {

byte[] bytes = null;
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值
HSSFSheet sheet = workbook.createSheet();
// 设置Excel的显示格式
HSSFRow row;
HSSFCell cell;
HSSFCellStyle style;
HSSFFont hf;

for (int i = 0; i < 1; i++) {
// 在索引0的位置创建行(最顶端的行)
row = sheet.createRow((short) i);
for (int j = 0; j < column.length; j++) {
// 在索引0的位置创建单元格(左上端)(相当于列数)
cell = row.createCell((short) j);
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);

// 定义样式
style = workbook.createCellStyle();
// 创建工作本的字体
hf = workbook.createFont();
hf.setFontName("楷体_GB2312");
style.setFont(hf);
// 设置列的属性
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(style);
// 在所创建的单元格填入值
if (i == 0) {
cell.setCellValue(column[j]);
}
}
}

for (int i = 0; i < list.size(); i++) {

Object obj = list.get(i);
Class objclass = obj.getClass();
Field[] fields = obj.getClass().getDeclaredFields();
int count=0;
for (int j = 0; j < fields.length; j++) {
Field subField = fields[j];
String subName = subField.getName();
boolean flag = true;
for (int k = 0; k < excelFile.length; k++) {
if (excelFile[k].equals(subName)) {
flag = false;
break;
}
}
if (flag) {
String getFieldMethod = "get"
+ subName.substring(0, 1).toUpperCase()
+ subName.substring(1, subName.length());
Class FieldClass = subField.getType();
String FieldClassName = FieldClass.getName();
String value = "";
if (!FieldClass.isArray()) {
Method method = null;
try {
method = obj.getClass().getMethod(
getFieldMethod, null);
} catch (Exception e1) {
e1.printStackTrace();
}
if (method != null) {
Object methodValue = (Object) method.invoke(
obj, null);
if (methodValue != null) {
value = methodValue.toString();
}
}
}
row = sheet.createRow((short) i + 1); // 从第1行开始
// 在索引0的位置创建单元格(左上端)(相当于列数)
cell = row.createCell((short) count);
count++;
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);

// 定义样式
style = workbook.createCellStyle();
// 创建工作本的字体
hf = workbook.createFont();
hf.setFontName("楷体_GB2312");
style.setFont(hf);
// 设置列的属性
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(style);
// 在所创建的单元格填入值

cell.setCellValue(value);
}

}

}
// 新建一输出文件流


bytes= workbook.getBytes();


} catch (Exception e) {
System.out.println("已运行 xlCreate() :错误信息 " + e);
e.printStackTrace();
}
return bytes;
}


}
...全文
评论 22
收藏 已收藏
分享
返回顶部
hnnxzhoujia
Web 开发 81,108 成员 341,721 内容