在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Java语言基础 → 词条转换(ConverStringBill)

词条转换(ConverStringBill)

Java语言基础

下载此实例
  • 开发语言:Java
  • 实例大小:0.53M
  • 下载次数:4
  • 浏览次数:27
  • 发布时间:2021-10-27
  • 实例类别:Java语言基础
  • 发 布 人:欧航荣
  • 文件格式:.zip
  • 所需积分:2
 相关标签: edit IT

实例介绍

【实例简介】
【实例截图】

【核心代码】

package cn.swiftpass.convert;

import cn.swiftpass.convert.ui.Controller;
import com.alibaba.fastjson.JSON;

import cn.swiftpass.convert.config.Config;
import cn.swiftpass.convert.config.ConfigAosVersion;
import cn.swiftpass.convert.config.SpecialCharacterEntity;
import cn.swiftpass.convert.config.SpecialCharacterEntity.SpeciallistBean;


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.net.URL;
import java.util.*;

public class Main extends Application {

    private final static String configPath = "./config_output.json";
    private final static String configAosPath = "./config_aos.json";

    private final static String specialCharacterAosPath = "./SpecialASCIICharacters_aos.txt";
    private static List<String> columnNameList;
    private static List<String> outFileNameList;
    private static Config config;
    private static SpecialCharacterEntity specialCharacterEntity;

    private static ConfigAosVersion configAosVersion;


    private static Map<String, List<String>> resultMap = new LinkedHashMap<>();
    private String numberText = "1";


    @Override
    public void start(Stage primaryStage) throws Exception {


        URL location = getClass().getResource("/layout/main.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(location);
        fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
        Parent root = fxmlLoader.load();

        primaryStage.setTitle("词条自动转换");
        primaryStage.setScene(new Scene(root, 450, 300));
        Controller controller = fxmlLoader.getController();

        controller.btn_select_sheet.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                FileChooser directoryChooser = new FileChooser();
                File file = directoryChooser.showOpenDialog(primaryStage);
                if (file != null) {
                    String sheetPath = file.getPath();
                    config.setConvertFilePath(sheetPath);
                    controller.tv_sheet.setText(sheetPath);
                    writeConfigFile(configPath, JSON.toJSONString(config));
                }

            }
        });
        controller.btn_select_res_path.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                DirectoryChooser directoryChooser = new DirectoryChooser();
                File file = directoryChooser.showDialog(primaryStage);
                if (file != null) {
                    String resPath = file.getPath();
                    configAosVersion.setOutFilePath(resPath);
                    controller.tv_res_path.setText(resPath);
                    writeConfigFile(configAosPath, JSON.toJSONString(configAosVersion));
                }
            }
        });
        if (configAosVersion != null) {
            if (configAosVersion.getOutFilePath() != null && configAosVersion.getOutFilePath().length() > 0) {
                controller.tv_res_path.setText(configAosVersion.getOutFilePath());
            }
        }

        if (config != null) {
            if (config.getConvertFilePath() != null && config.getConvertFilePath().length() > 0) {
                controller.tv_sheet.setText(config.getConvertFilePath());
            }
        }
        controller.btn_confirm.setOnAction(event -> {
            numberText = controller.ed_string_number.getText();
            resultMap.clear();
            readExcellList(readExcel(config.getConvertFilePath()));
            genAosXml();
        });
        primaryStage.show();

    }

    public static void main(String[] args) {
        System.out.println("start......");
        initConfig();
        configAos();

        launch(args);
    }

    private static void initConfig() {

        String configStr = readConfigFile(configPath);
        if (!configStr.isEmpty()) {
            config = JSON.parseObject(configStr, Config.class);
        }
        System.out.println(JSON.toJSON(config));


    }

    private static void configAos() {
        String characterPath = readConfigFile(specialCharacterAosPath);
        if (!characterPath.isEmpty()) {
            generateSpecialList(characterPath);
        }
        String configAosStr = readConfigFile(configAosPath);
        if (!configAosStr.isEmpty()) {
            configAosVersion = JSON.parseObject(configAosStr, ConfigAosVersion.class);
        }
        System.out.println(JSON.toJSON(configAosStr));
        columnNameList = configAosVersion.getColNameList();
        outFileNameList = configAosVersion.getOutFileNameList();
        resultMap.clear();
    }


    private static void generateSpecialList(String characterPath) {
        specialCharacterEntity = new SpecialCharacterEntity();
        List<SpeciallistBean> speciallistBeans = new ArrayList<>();
        String items[] = characterPath.replace("\r\n", "").split("##");
        for (int i = 0; i < items.length; i  ) {
            String totalItemStr = items[i];
            String childItems[] = totalItemStr.split("=");
            SpeciallistBean speciallistBean = new SpeciallistBean();
            speciallistBean.setValue(childItems[0].replace("\r\n", ""));
            speciallistBean.setName(childItems[1].replace("\r\n", ""));
            speciallistBeans.add(speciallistBean);
        }
        specialCharacterEntity.setSpeciallist(speciallistBeans);
    }


    private static String readConfigFile(String filePath) {


        File file = new File(filePath);
        if (!file.exists()) {
            return "";
        }

        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            char[] buf = new char[1024];
            int len;
            while ((len = reader.read(buf)) != -1) {
                stringBuilder.append(buf, 0, len);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    private void writeConfigFile(String filePath, String data) {
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream buf = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            buf = new BufferedOutputStream(fileOutputStream);
            buf.write(data.getBytes());
            buf.flush();
            buf.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (buf != null) {
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void readExcellList(Workbook wb) {
        Sheet sheet = null;
        String cellData = null;
        Row row = null;
        if (wb != null) {

            int sheetNumber = 0;
            Integer number = Integer.valueOf(numberText);
            if (number > 0) {
                sheetNumber = number-1;
            }
            sheet = wb.getSheetAt(sheetNumber);

            row = sheet.getRow(0);


            int rowNum = sheet.getPhysicalNumberOfRows();

            int colnum = row.getPhysicalNumberOfCells();


            List<Integer> columnIndexList = new ArrayList<>();
            for (int i = 0; i < columnNameList.size(); i  ) {
                for (int j = 0; j < colnum; j  ) {
                    cellData = (String) getCellFormatValue(row.getCell(j));
                    if (cellData != null && !cellData.isEmpty() && columnNameList.get(i).equals(cellData)) {
                        columnIndexList.add(j);
                    }
                }
            }
            if (columnIndexList.size() != columnNameList.size()) {
                throw new IllegalStateException(":"   columnNameList);
            }


            for (int i = 1; i < rowNum; i  ) {
                row = sheet.getRow(i);
                if (row == null) {
                    break;
                }

                List<String> temp = null;
                for (int j = 0; j < columnNameList.size(); j  ) {
                    int index = columnIndexList.get(j);
                    cellData = (String) getCellFormatValue(row.getCell(index));
                    if (j == 0) {
                        if (cellData.isEmpty()) {

                            break;
                        }

                        temp = new ArrayList<>();
                        resultMap.put(cellData, temp);
                    } else {
                        temp.add(cellData);
                    }
                }
            }

        }

    }


    private void genAosXml() {
        String topTitle = "<resources>";
        String bottomTitle = "</resources>";
        File itemFile = null;
        for (int i = 0; i < outFileNameList.size(); i  ) {
            try {
                String parentName = configAosVersion.getOutFilePath()  "/" outFileNameList.get(i);
                itemFile = new File(parentName);
                if (!itemFile.exists()) {
                    itemFile.mkdirs();
                }

                itemFile = new File(parentName, "string_p"   numberText   ".xml");
                if (!itemFile.exists()) {
                    itemFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(itemFile);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
                bw.write(topTitle);
                bw.newLine();

                // formatted="false"
                String inputResultFormat = "<string name=\"%s\" formatted=\"false\">%s</string>";
                for (Map.Entry<String, List<String>> entry : resultMap.entrySet()) {
                    String key = entry.getKey();

                    key = key.replace("-", "_");
                    String value = entry.getValue().get(i);
                    System.out.println("value:"   value   " key:"   key);

                    List<SpeciallistBean> speciallistBeans = specialCharacterEntity.getSpeciallist();
                    for (int j = 0; j < speciallistBeans.size(); j  ) {
                        // &#192=?;
                        SpeciallistBean speciallistBean = speciallistBeans.get(j);
                        String specialName = speciallistBean.getName();
                        String changeValue = speciallistBean.getValue();

                        if (value.contains(specialName)) {
                            // <string name="EC01_22">eVoucher No. &amp; Expiry Dates</string>
                            if (specialName.equals("&") && value.contains("&#")) {

                                // <string name="EC05_3_a">Required Points:&#160; </string>
                                break;
                            }
                            value = value.replace(specialName, changeValue);
                        }
                    }

                    if (value.isEmpty()) {
                        throw new Exception(key   "");
                    }

                    String itemLineStr = String.format(inputResultFormat, key, value);
                    bw.write(itemLineStr);
                    bw.newLine();
                }
                bw.write(bottomTitle);
                bw.newLine();
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }

    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {

            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }

}

标签: edit IT

实例下载地址

词条转换(ConverStringBill)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警