/** * 生成数据文件 * * @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(); }
标签:java,String,写入,builder,list,fileName,File,return,data From: https://www.cnblogs.com/hdwang/p/18224892