Commit 25f1ad20 authored by 郝彦辉's avatar 郝彦辉

添加Excel表格数据和black_list_new表里数据比对的工具/black_list/queryDateBack

参数说明:
filePath:原文件地址;titleNames:表格的头部标题,已逗号分隔;haveTitle:是否有标题列,默认true;queryType:查询类别,目前可以传idCard或phoneNo,name暂不支持
parent f6cd205e
Pipeline #77 failed with stages
......@@ -300,6 +300,26 @@
<artifactId>enoch-agent-spring-boot-starter</artifactId>
</dependency>
<!-- add by 2019.09.09 -->
<!--<dependency>
<groupId>jxl</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12.1</version>
</dependency>-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
</dependencies>
</project>
......@@ -38,6 +38,9 @@ public class Constant {
public static String XYQB_USER_QUERY_USER_DETAIL_BY_UUID_SQL = "select user_id from user a left join user_detail b on a.id=b.user_id where a.uuid = '%s'";
public static String BLACK_LIST_NEW_QUERY_BY_IDNO_SQL2 = "select * from black_list_new where id_no = '%s' and created_at < '%s' and status = true;";
public static String BLACK_LIST_NEW_QUERY_BY_PHONENO_SQL2 = "select * from black_list_new where phone_no = '%s' and created_at < '%s' and status = true;";
}
public static class BATCH_TYPE {
......
......@@ -22,4 +22,16 @@ public class BlackListQueryManagerController {
return iBlackListQueryManagerService.queryBlackList(uuid, name, phoneNo, idCard, type);
}
/**
* @描述
* @参数 [filePath:原文件地址; titleNames:表格的头部标题,已逗号分隔; haveTitle:是否有标题列,默认true; queryType:查询类别,目前可以传idCard或phoneNo,name暂不支持]
* @返回值 cn.quantgroup.qgblservice.response.GlobalResponse
* @创建人 yanhui.Hao
* @创建时间 2019.09.10
*/
@RequestMapping("/queryDateBack")
public GlobalResponse queryDateBack(String filePath,String titleNames, String haveTitle, String queryType){
return iBlackListQueryManagerService.queryDateBack(filePath,titleNames,haveTitle,queryType);
}
}
......@@ -11,4 +11,7 @@ public interface IBlackListQueryManagerService {
public GlobalResponse queryBlackList(String uuid, String name, String phoneNo, String idCard, String type);
public void initChannelBlackListExpireConfig();
public GlobalResponse queryDateBack(String filePath, String titleNames,String haveTitle, String queryType);
}
......@@ -5,6 +5,8 @@ import cn.quantgroup.qgblservice.repository.mybatis.entity.blacklist.BlackListCh
import cn.quantgroup.qgblservice.repository.mybatis.entity.tidb.BlackListQueryTidbVo0;
import cn.quantgroup.qgblservice.response.GlobalResponse;
import cn.quantgroup.qgblservice.service.IBlackListQueryManagerService;
import cn.quantgroup.qgblservice.utils.ReadExcelUtils;
import cn.quantgroup.qgblservice.utils.ReadOrWriteTxt;
import cn.quantgroup.qgblservice.utils.jdbc.JdbcExecuters;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Stopwatch;
......@@ -116,7 +118,6 @@ public class BlackListQueryManagerServiceImpl implements IBlackListQueryManagerS
blackListQueryTidbVo0.setJoinBlackTime(new Timestamp(blackListQueryTidbVo0.getCreatedAt().getTime()).toLocalDateTime().format(DateTimeFormatter.ofPattern(Constant.DAYE_FORMAT.YYYY_MM_DD_HH_MM_SS)));
});
} else {
queryListBlackListByPhoneNos.stream().filter(o -> Timestamp.valueOf(
......@@ -137,7 +138,6 @@ public class BlackListQueryManagerServiceImpl implements IBlackListQueryManagerS
JdbcExecuters.blackListUpdateBatchExecute(blackListQueryTidbVo0s, Constant.SQL.BLACK_LIST_NEW_UPDATE_FIRST_OR_MAX_OVERDUE_DAYS_SQL, blackListJdbcTemplate, Constant.BATCH_TYPE.BATCH_UPDATE_OVERDUE_DAYS);
}
log.info("查询黑名单结束, uuid: {} , name: {} , phoneNo: {} , idNo: {} , type: {} , result: {} , 耗时: {} ", uuid, name, phoneNo, idNo, type, JSON.toJSONString(queryListBlackListByPhoneNos), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return queryListBlackListByPhoneNos;
}
......@@ -149,4 +149,165 @@ public class BlackListQueryManagerServiceImpl implements IBlackListQueryManagerS
log.info("加载渠道黑名单有效期配置完成, result: {} ", JSON.toJSONString(channelBlackListExpireConfigMap));
}
@Override
public GlobalResponse queryDateBack(String filePath,String titleNames,String haveTitle, String queryType) {
log.info("用户black_list_new黑名单比对开始, filePath: {} , titleNames: {} , haveTitle: {} , queryType: {} ", filePath, titleNames, haveTitle, queryType);
Stopwatch stopwatch = Stopwatch.createStarted();
List<Map<String,String>> paramsList = new ArrayList<Map<String,String>>();
if(filePath!=null && queryType!=null){
boolean have = haveTitle!=null && haveTitle.equals("false") ? false:true;//默认有标题
Map<String, Object> readMap = ReadExcelUtils.readExcel(filePath,titleNames, have);
List<String> readList = null;
if(readMap!=null && readMap.get("code").toString().equals("0") && readMap.get("result")!=null) {
readList = (List<String>) readMap.get("result");
if(readList==null || readList.size()==0){
return GlobalResponse.error("读取文件内容为空!");
}
}else{
return GlobalResponse.error(readMap.get("msg").toString());
}
String sql = "";
List<BlackListQueryTidbVo0> blackList = new ArrayList<BlackListQueryTidbVo0>();
//queryType:idCard phoneNo name
if(queryType.equals("idCard")){
StringBuffer querysql = new StringBuffer();
int beachCount = 0;
for(String params : readList){
beachCount++;
String tmp[] = params.split("[|]");
String tmpSql = String.format(Constant.SQL.BLACK_LIST_NEW_QUERY_BY_IDNO_SQL2, tmp[0], tmp[3].substring(0,10)+" 00:00:00");
if(beachCount==500){//500条查询一次
querysql.append(tmpSql);
List<BlackListQueryTidbVo0> tmpQueryList = blackListJdbcTemplate.query(querysql.toString(), new BeanPropertyRowMapper<>(BlackListQueryTidbVo0.class));
if (CollectionUtils.isNotEmpty(tmpQueryList)) {
blackList.addAll(tmpQueryList);
}
beachCount=0;
querysql = new StringBuffer();
}else{
querysql.append(tmpSql.replace(";", " union all "));
}
}
//最后不够500
if(querysql!=null && querysql.length()>0){
String sql2 = querysql.toString();
if(querysql.toString().endsWith("union all") || querysql.toString().endsWith("union all ")){
sql2 = sql2.substring(0,sql2.lastIndexOf("union all"));
}
if(!querysql.toString().endsWith(";")){
sql2 = sql2 + ";";
}
List<BlackListQueryTidbVo0> tmpQueryList = blackListJdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(BlackListQueryTidbVo0.class));
if (CollectionUtils.isNotEmpty(tmpQueryList)) {
blackList.addAll(tmpQueryList);
}
}
}else if (queryType.equals("mobile")){
StringBuffer querysql = new StringBuffer();
int beachCount = 0;
for(String params : readList){
beachCount++;
String tmp[] = params.split("[|]");
String tmpSql = String.format(Constant.SQL.BLACK_LIST_NEW_QUERY_BY_PHONENO_SQL2, tmp[2], tmp[3].substring(0,10)+" 00:00:00");
if(beachCount==500){//500条查询一次
querysql.append(tmpSql);
List<BlackListQueryTidbVo0> tmpQueryList = blackListJdbcTemplate.query(querysql.toString(), new BeanPropertyRowMapper<>(BlackListQueryTidbVo0.class));
if (CollectionUtils.isNotEmpty(tmpQueryList)) {
blackList.addAll(tmpQueryList);
}
beachCount=0;
querysql = new StringBuffer();
}else{
querysql.append(tmpSql.replace(";", " union all "));
}
}
//最后不够500
if(querysql!=null && querysql.length()>0){
String sql_2 = querysql.toString();
querysql=null;
if(sql_2.toString().endsWith("union all") || sql_2.toString().endsWith("union all ")){
sql_2 = sql_2.substring(0,sql_2.lastIndexOf("union all"));
}
if(!sql_2.toString().endsWith(";")){
sql_2 = sql_2 + ";";
}
List<BlackListQueryTidbVo0> tmpQueryList = blackListJdbcTemplate.query(sql_2, new BeanPropertyRowMapper<>(BlackListQueryTidbVo0.class));
if (CollectionUtils.isNotEmpty(tmpQueryList)) {
blackList.addAll(tmpQueryList);
}
}
}else{
log.warn("用户black_list_new黑名单比对结束, filePath: {} , titleNames: {} , haveTitle: {} , queryType: {} , result: {} , 耗时: {} ", filePath, titleNames, haveTitle, queryType, "无效的查询类型[queryType]", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return GlobalResponse.error("无效的查询类型[queryType]");
}
if (CollectionUtils.isNotEmpty(blackList)) {
blackList.stream().filter(o -> Timestamp.valueOf(
LocalDateTime.now().minusYears(channelBlackListExpireConfigMap.get(o.getType())).format(DateTimeFormatter.ofPattern(Constant.DAYE_FORMAT.YYYY_MM_DD_HH_MM_SS))
).getTime() - o.getCreatedAt().getTime() < 0 && o.isStatus()).forEach(blackListQueryTidbVo0 -> {
/* if (CollectionUtils.isNotEmpty(totalOverdueDaysList)) {
Object totalOverdueDays = totalOverdueDaysList.get(0).get(Constant.PARAM.TOTAL_OVERDUE_DAYS);
blackListQueryTidbVo0.setTotalOverdueDays(Objects.nonNull(totalOverdueDays) ? totalOverdueDays.toString() : null);
}
if (CollectionUtils.isNotEmpty(maxOverdueDaysList)) {
Object maxOverdueDays = maxOverdueDaysList.get(0).get(Constant.PARAM.MAX_OVERDUE_DAYS);
blackListQueryTidbVo0.setMaxOverdueDays(Objects.nonNull(maxOverdueDays) ? maxOverdueDays.toString() : null);
}
blackListQueryTidbVo0s.add(blackListQueryTidbVo0);*/
Timestamp updatedAt = new Timestamp(System.currentTimeMillis());
String updatedAtStr = updatedAt.toLocalDateTime().format(DateTimeFormatter.ofPattern(Constant.DAYE_FORMAT.YYYY_MM_DD_HH_MM_SS));
blackListQueryTidbVo0.setBlackUpdatedTime(updatedAtStr);
blackListQueryTidbVo0.setUpdatedAt(updatedAt);
blackListQueryTidbVo0.setJoinBlackTime(new Timestamp(blackListQueryTidbVo0.getCreatedAt().getTime()).toLocalDateTime().format(DateTimeFormatter.ofPattern(Constant.DAYE_FORMAT.YYYY_MM_DD_HH_MM_SS)));
});
StringBuffer tmp = new StringBuffer();
String[] titilName = {"id", "uuid", "name", "phone_no", "id_no", "major_type", "type", "total_overdue_days", "max_overdue_days", "black_level", "join_black_reason", "status", "created_at", "updated_at"};
//标题
for (int i = 0; i < titilName.length; i++) {
if (i==0){
tmp.append(titilName[i]);
}else{
tmp.append("\t");
tmp.append(titilName[i]);
}
}
for (BlackListQueryTidbVo0 bean:blackList) {
tmp.append("\n");
tmp.append(bean.getId());
tmp.append("\t"+bean.getUuid());
tmp.append("\t"+bean.getName());
tmp.append("\t"+bean.getPhoneNo());
tmp.append("\t"+bean.getIdNo());
tmp.append("\t"+bean.getMajorType());
tmp.append("\t"+bean.getType());
tmp.append("\t"+(bean.getTotalOverdueDays()!=null ? bean.getTotalOverdueDays(): ""));
tmp.append("\t"+(bean.getMaxOverdueDays()!=null ? bean.getMaxOverdueDays(): ""));
tmp.append("\t"+bean.getBlackLevel());
tmp.append("\t"+bean.getJoinBlackReason());
tmp.append("\t"+bean.isStatus());
tmp.append("\t"+bean.getJoinBlackTime());
tmp.append("\t"+bean.getBlackUpdatedTime());
}
String writeFilePath = "";
if(filePath.lastIndexOf("/")!=-1){//linux
writeFilePath = filePath.substring(0,filePath.lastIndexOf("/"))+"/"+queryType+"_"+blackList.size()+"_"+System.currentTimeMillis()+".txt";
}else{//windows
writeFilePath = filePath.substring(0,filePath.lastIndexOf("\\"))+"\\"+queryType+"_"+blackList.size()+"_"+System.currentTimeMillis()+".txt";
}
ReadOrWriteTxt.writeTxt(writeFilePath,tmp.toString());
log.info("用户black_list_new黑名单比对结束, filePath: {} , titleNames: {} , haveTitle: {} , queryType: {} , result: {} , 耗时: {} ", filePath, titleNames, haveTitle, queryType, ("导出成功,文件位置:"+writeFilePath), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return GlobalResponse.success("导出成功,文件位置:"+writeFilePath);
}else{
log.warn("用户black_list_new黑名单比对结束, filePath: {} , titleNames: {} , haveTitle: {} , queryType: {} , result: {} , 耗时: {} ", filePath, titleNames, haveTitle, queryType, "查询为空", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return GlobalResponse.success("查询为空!");
}
}
log.warn("用户black_list_new黑名单比对结束, filePath: {} , titleNames: {} , haveTitle: {} , queryType: {} , result: {} , 耗时: {} ", filePath, titleNames, haveTitle, queryType, "参数为空", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return GlobalResponse.error("参数为空!");
}
}
package cn.quantgroup.qgblservice.utils;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* -----------------------------------------------------------------------------<br>
* 描述: <br>
* 作者: Haoyanhui <br>
* 时间:2019.09.09 20:53 <br>
* 授权: (C) Copyright (c) 2017 <br>
* 公司: 北京众信利民信息技术有限公司 <br>
* -----------------------------------------------------------------------------
*/
public class ReadExcelUtils {
private static Workbook wb;
private static Sheet sheet;
private static Row row;
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
private static final Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);
/**
* 读取表头
*
* @param inputStream inputStream
* @param suffix file suffix
* @return map <index,value>
*/
public static Map<Integer, String> readExcelTitle(InputStream inputStream, String suffix) {
getWorkbook(inputStream, suffix);
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 标题总列数
int colNum = row.getPhysicalNumberOfCells();
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < colNum; i++) {
map.put(i, row.getCell(i).getStringCellValue());
}
return map;
}
/**
* 读取excel内容
*
* @param inputStream 文件
* @return Map<行, Map < 下标, Object>>
*/
public static Map<Integer, Map<Integer, String>> readExcelContent(InputStream inputStream, String suffix) {
getWorkbook(inputStream, suffix);
Map<Integer, Map<Integer, String>> content = new HashMap<>();
sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, String> cellValue = new HashMap<>();
while (j < colNum) {
String obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
private static String getCellFormatValue(Cell cell) {
String cellValue = "";
if (cell != null) {
// 判断当前Cell的Type
switch (cell.getCellType()) {
// 如果当前Cell的Type为NUMERIC
case Cell.CELL_TYPE_NUMERIC:
case Cell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
Instant instant = cell.getDateCellValue().toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
cellValue = dateTimeFormatter.format(localDateTime);
} else {
// 如果是纯数字
// 取得当前Cell的数值
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
// 如果当前Cell的Type为STRING
case Cell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellValue = cell.getRichStringCellValue().getString();
break;
default:
// 默认的Cell值
cellValue = "";
}
}
return cellValue;
}
//HSSFWorkbook,XSSFWorkbook的区别:前者是解析出来excel 2007 以前版本的,后缀名为xls的,后者是解析excel 2007 版的,后缀名为xlsx
private static void getWorkbook(InputStream inputStream, String suffix) {
try {
//2003
if (EXCEL_XLS.equals(suffix)) {
wb = new HSSFWorkbook(inputStream);
//2007/2010
} else if (EXCEL_XLSX.equals(suffix)) {
wb = new XSSFWorkbook(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static Workbook getWorkbookByPath(String filePath) throws IOException {
Workbook wb = null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
//Excel2003
if (filePath.endsWith(".xls")) {
wb = new HSSFWorkbook(inputStream);
//Excel2007,Excel2010
} else if (filePath.endsWith(".xlsx")) {
wb = new XSSFWorkbook(inputStream);
}
} catch (IOException e) {
//e.printStackTrace();
throw e;
} finally {
try {
if(inputStream!=null){
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return wb;
}
/**
* @描述
* @参数 [path, haveTitle]
* @返回值 java.util.Map<java.lang.String,java.lang.Object>
* <br> code: 0 成功,1 失败 ; msg: 失败说明 ; result: List<String> 识别结果
* @创建人 yanhui.Hao
* @创建时间 2019.09.10
*/
public static Map<String,Object> readExcel(String path, String titleNames, boolean haveTitle){
Map<String,Object> readMap = new HashMap<String,Object>();
try {
List<String> readList = new ArrayList<String>();
//HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(path));
Workbook wb = getWorkbookByPath(path);
if (wb==null) {
readMap.put("code","1");
readMap.put("msg","文件["+path+"]不是 Excel.");
return readMap;
}
//HSSFSheet sheet = wb.getSheetAt(0);
Sheet sheet = wb.getSheetAt(0);
for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter.hasNext();) {
Row row = iter.next();
// 获得当前行数
int rowNum =row.getRowNum();
if(rowNum==0){ //第一行标题
if(haveTitle){
StringBuffer titles = new StringBuffer();
for (Iterator<Cell> iter1 = (Iterator<Cell>) row.cellIterator(); iter1.hasNext();) {
Cell cell1 = iter1.next();
int thisColNum = cell1.getColumnIndex();
String content = getCellFormatValue(cell1);
if(thisColNum==0){
titles.append(content.trim());
}else{
titles.append(",");
titles.append(content.trim());
}
}
//if(titles.toString().indexOf(titleNames)!=-1){
if(titles.toString().indexOf("idcard,name,mobile,dateBack")==-1){
readMap.put("code","1");
readMap.put("msg","Excel 表格的列标题顺序必须是 [idcard,name,mobile,dateBack...other...]");
return readMap;
}
continue;
}
}
StringBuffer context = new StringBuffer();
for (Iterator<Cell> iter2 = (Iterator<Cell>) row.cellIterator(); iter2.hasNext();) {
Cell cell = iter2.next();
// 获得当前列数
int col = cell.getColumnIndex();
//String content = cell.getStringCellValue();// 除非是sring类型,否则这样迭代读取会有错误
String content = getCellFormatValue(cell);
if(col==0){
context.append(content);
}else{
context.append("|");
context.append(content);
}
}
readList.add(context.toString());
}
readMap.put("code","0");
readMap.put("msg","ok");
readMap.put("result",readList);
} catch (IOException e) {
//e.printStackTrace();
//System.err.println("readExcel() IOException,"+e.getMessage());
logger.error("readExcel() IOException,"+e.getMessage(),e);
readMap.put("code","1");
readMap.put("msg",e.getMessage());
}
return readMap;
}
public static void main(String[] args) {
//code: 0 成功,1 失败 ; msg: 失败说明 ; result: List<String> 识别结果
Map<String, Object> readMap = ReadExcelUtils.readExcel("D:\\JavaTeam\\shmf.xls", "idcard,name,mobile,dateBack", false);
if(readMap!=null && readMap.get("code").toString().equals("0") && readMap.get("result")!=null) {
List<String> readList = (List<String>) readMap.get("result");
for(String tmp:readList){
System.out.println(tmp);
}
}
System.out.println(readMap.toString());
}
}
package cn.quantgroup.qgblservice.utils;
import java.io.*;
import java.util.List;
/**
* -----------------------------------------------------------------------------<br>
* 描述: <br>
* 作者: Haoyanhui <br>
* 时间:2019.09.09 22:34 <br>
* 授权: (C) Copyright (c) 2017 <br>
* 公司: 北京众信利民信息技术有限公司 <br>
* -----------------------------------------------------------------------------
*/
public class ReadOrWriteTxt {
/**传入txt路径读取txt文件
* @param txtPath
* @return 返回读取到的内容
*/
public static String readTxt(String txtPath) {
File file = new File(txtPath);
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**使用FileOutputStream来写入txt文件
* @param txtPath txt文件路径
* @param content 需要写入的文本
*/
public static void writeTxt(String txtPath,String content){
FileOutputStream fileOutputStream = null;
File file = new File(txtPath);
try {
if(file.exists()){
//判断文件是否存在,如果不存在就新建一个txt
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeTxt(String txtPath,List<String> contentList){
FileOutputStream fileOutputStream = null;
File file = new File(txtPath);
try {
if(file.exists()){
//判断文件是否存在,如果不存在就新建一个txt
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
for(String content:contentList){
fileOutputStream.write(content.getBytes());
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//String filePath = "D:\\JavaTeam\\shmf.txt";
String filePath = "/opt/web_app/shmf.txt";
String queryType = "aa";
String writeFilePath = "";
if(filePath.lastIndexOf("/")!=-1){//linux
writeFilePath = filePath.substring(0,filePath.lastIndexOf("/"))+"/"+queryType+".txt";
}else{//windows
writeFilePath = filePath.substring(0,filePath.lastIndexOf("\\"))+"\\"+queryType+".txt";
}
System.out.println(filePath);
System.out.println(writeFilePath);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment