java資料list寫入檔案

追极發表於2024-05-31
 /**
     * 生成資料檔案
     *
     * @param data     資料
     * @param fileName 檔名
     * @return 資料檔案物件
     * @throws IOException
     */
    private File generateDataFile(List<List<String>> data, String fileName) throws IOException {
        File file = new File(getTempFile(fileName));
        StringBuilder builder = new StringBuilder();
        String rowSeparator = "\n";
        String fieldSeparator = "\1";
        boolean rowSeparatorToEnd = false;
        boolean fieldSeparatorToEnd = false;
        int rowIndex = 0;
        for (List<String> row : data) {
            int colIndex = 0;
            for (String col : row) {
                builder.append(col);
                //行尾判斷是否新增欄位分隔符
                if (colIndex == row.size() - 1 && !fieldSeparatorToEnd) {
                    continue;
                }
                //新增欄位分割符
                builder.append(fieldSeparator);
                colIndex++;
            }

            //內容尾判斷是否新增換行符
            if (rowIndex == data.size() - 1 && !rowSeparatorToEnd) {
                continue;
            }
            //新增換行符
            builder.append(rowSeparator);
            rowIndex++;
        }
        FileUtils.writeStringToFile(file, builder.toString(), StandardCharsets.UTF_8);
        return file;
    }

    /**
     * 獲取暫時檔案的路徑
     *
     * @param fileName 檔名
     * @return
     */
    public String getTempFile(String fileName) {
        String uuid = IdUtils.fastSimpleUUID();
        String tmpFileName = uuid + BaseConstant.SYMBOL_SLASH + fileName;
        File tmpFile = FileUtils.getFile(FileUtils.getTempDirectory(), tmpFileName);
        tmpFile.getParentFile().mkdirs();
        return tmpFile.getAbsolutePath();
    }

相關文章