網站首頁 java綜合 正文
最近做項目有一個需要用到導出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++){
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length)); //平臺訂單號
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//商戶訂單號
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//商戶批次號
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//賬號
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//賬戶名稱
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//賬戶類型
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//金額
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//狀態
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//手續費
//write.append(tab);
write.append(appentStr4Length(String.valueOf(random.nextInt(1000)),length));//支付類型
write.append(enter);
}
Charset charset = Charset.forName("UTF-8"); // 指定編碼格式
byte[] bytes = write.toString().getBytes(charset); // 將StringBuffer轉換為byte數組
// 如果需要,可以將byte數組轉換回String
String encodedString = new String(bytes, charset);
bw.write(encodedString);
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
if (bw !=null){
try {
bw.close();
} catch (IOException ex) {
e.printStackTrace();
}
;
}
}finally{
System.out.println("111111111");
if (bw !=null){
try {
bw.close();;
}catch (IOException e){
e.printStackTrace();
}
}
}
}
public static String appentStr4Length(String str , int length){
if(str == null){
str = "";
}
try {
int strLen = 0;//計算原字符串所占長度,規定中文占兩個,其他占一個
for(int i = 0 ; i<str.length(); i++){
if(isChinese(str.charAt(i))){
strLen = strLen + 2;
}else{
strLen = strLen + 1;
}
}
if(strLen>=length){
return str;
}
int remain = length - strLen;//計算所需補充空格長度
for(int i =0 ; i< remain ;i++){
str = str + " ";
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
// 根據Unicode編碼完美的判斷中文漢字和符號
private static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
return true;
}
return false;
}
}
//大概用法
HttpServletResponse response = getHttpServletResponse();
// filename指定默認的名字
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String tab = "\t\t";
String enter = "\r\n";
ServletOutputStream outStr = null;
response.setContentType("text/plain");// 一下兩行關鍵的設置
response.addHeader("Content-Disposition",
"attachment;filename="+DateUtil.formatDateTime(DateUtil.DF_YMDHMS, new Date())+".txt");
try {
outStr = response.getOutputStream();// 建立
buff = new BufferedOutputStream(outStr);
Map<String, Object> listMap = service.getPaymentBatchDetailListById(map);
List<PaymentBatchDetailDto> resultList = new ArrayList<PaymentBatchDetailDto>();
resultList = (List<PaymentBatchDetailDto>) listMap.get("list");
int length = 20;
if (null != resultList && resultList.size() > 0) {
write.append(appentStr4Length("平臺訂單號",length));
//write.append(tab);
write.append(appentStr4Length("商戶訂單號",length));
//write.append(tab);
write.append(appentStr4Length("商戶批次號",length));
//write.append(tab);
write.append(appentStr4Length("賬號",30));
//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);
CharHidden hidden = new CharHidden();
for(int i = 0;i<resultList.size();i++){
final PaymentBatchDetailDto p = resultList.get(i);
write.append(appentStr4Length(p.getId(),length)); //平臺訂單號
//write.append(tab);
write.append(appentStr4Length(p.getMchtBatchNo(),length));商戶訂單號
//write.append(tab);
write.append(appentStr4Length(p.getMchtBatchNo(),length));//商戶批次號
//write.append(tab);
write.append(appentStr4Length(hidden.exec(new ArrayList<String>(){{add(p.getAccountNo());}}).toString(),30));//賬號
//write.append(tab);
write.append(appentStr4Length(p.getAccountName(),length));//賬戶名稱
//write.append(tab);
write.append(appentStr4Length(p.getAccountType(),length));//賬戶類型
//write.append(tab);
write.append(appentStr4Length(p.getAmount(),length));//金額
//write.append(tab);
write.append(appentStr4Length(p.getStatus(),length));//狀態
//write.append(tab);
write.append(appentStr4Length(p.getFee(),length));//手續費
//write.append(tab);
write.append(appentStr4Length(p.getPaymentBusinessType(),length));//支付類型
//write.append(tab);
write.append(appentStr4Length(p.getCreatedDate(),length));//創建日期
//write.append(tab);
write.append(appentStr4Length(p.getResponseMsg(),length));//失敗原因
write.append(enter);
}
buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} else {
throw new MemberServiceException(EMemberError.E0001.name(),
EMemberError.E0001.getValue());
}
} catch (Exception e) {
MessageBean messageBean = new MessageBean();
messageBean.setType(MessageBean.TYPE_EXCEPTION);
messageBean.setObject(0, MessageBean.EXCEPTION_LEVEL_ERROR);
messageBean.setObject(1, MchtDateUtil.formatCurrDateTime(MchtDateUtil.DF_Y_M_D_HMS));
messageBean.setObject(2, "ops-mcht-app");
messageBean.setObject(3, "支付批次明細");
messageBean.setObject(4, "com.smartpay.ops.mcht.view.agencyPay.AgencyPayController");
messageBean.setObject(5, "代付支付批次明細下載異常");
// end monitor
LoggerUtil.error(messageBean.toString());
LoggerUtil.error(e);
try {
buff.write(e.getMessage().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}finally{
try {
buff.close();
outStr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
再說兩句
計算字符的時候,由于發現在txt文件中中文占的寬度是英文字符的兩倍,所以統計的時候要把中文寬度值記為2,英文為1,最后計算出要補充的空格字符。
原文鏈接:https://blog.csdn.net/appandroid/article/details/138588803
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-07-10 組件內路由守衛beforeRouteEnter和beforeRouteLeave
- 2022-02-25 Linux下安裝Hadoop集群詳細步驟_Linux
- 2022-04-18 python函數的默認參數請勿定義可變類型詳解_python
- 2022-10-04 Android實現圓圈倒計時_Android
- 2022-07-11 Python如何獲取多線程返回結果_python
- 2022-02-21 C#多線程學習之Thread、ThreadPool、Task、Parallel四者區別_C#教程
- 2024-01-05 TCP、IP、TCP/IP、HTTP和HTTPS協議簡介
- 2022-12-09 深入了解Rust中泛型的使用_Rust語言
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支