最近做项目有一个需要用到导出txt文件的地方,内容大概就是一个把list数据类型格式的数据导出到txt文件,但是txt的排版是一个令人头疼的事情。但是一直不知道怎么让每列对齐,所以就出现了下面这样的情况。
思路
思路其实很简单,就是跟html画表格一样,考虑到表格中的每列的宽度都是固定的。那我们导出的时候也把每列宽度都固定不就行了吗。假设每列宽度最大为20个字符,那么我们就把这一列宽度设置为20个字符,不足20的用空格填充。不多说了,下面贴代码。
package com.seemygo.shop.cloud;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Random;
public class formatStr {
public static void main(String[] args) {
addStr();
}
public static void addStr(){
// filename指定默认的名字
File file=new File("D:/data/stu.txt");
BufferedWriter bw=null;
StringBuffer write = new StringBuffer();
String tab = "\t\t";
String enter = "\r\n";
try {
//创建输出流
bw=new BufferedWriter(new FileWriter(file,true));
int length = 20;
write.append(appentStr4Length("平台订单号",length));
//write.append(tab);
write.append(appentStr4Length("商户订单号",length));
// write.append(tab);
write.append(appentStr4Length("商户批次号",length));
//write.append(tab);
write.append(appentStr4Length("账号",length));
//write.append(tab);
write.append(appentStr4Length("账户名称",length));
//write.append(tab);
write.append(appentStr4Length("账户类型",length));
//write.append(tab);
write.append(appentStr4Length("金额",length));
//write.append(tab);
write.append(appentStr4Length("状态 ",length));
//write.append(tab);
write.append(appentStr4Length("手续费",length));
//write.append(tab);
write.append(appentStr4Length("支付类型",length));
write.append(enter);
write.append("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ");
write.append(enter);
Random random = new Random();
for(int i = 0;i<10;i++){
w