日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 java綜合 正文

java導出txt文件列對齊

作者:hnbyboy 更新時間: 2024-07-15 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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新