一.读取excel或者其他类型文件的数据作为待替换的数据
//读取excel数据
File file2 = new File(filePath + "Excel标准参数.xls");
Workbook workbook = null;
try {
workbook = new XSSFWorkbook(file2);
} catch (Exception e) {
workbook = new HSSFWorkbook(new FileInputStream(file2));
}
Sheet sheet = workbook.getSheetAt(0);
List<String> list1 = parseData(sheet);
//创建方法读取数据——————————》
private List parseData(Sheet sheet) {
int rowCount = sheet.getPhysicalNumberOfRows();
List<String> list = new ArrayList<>();
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
//参数名
row.getCell(0).setCellType(CellType.STRING);
String name = row.getCell(0).getStringCellValue().trim();
//参数值
row.getCell(1).setCellType(CellType.STRING);
String value = row.getCell(1).getStringCellValue().trim();
if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(value)) {
list.add(name + "=" + value);
}
}
return list;
}
二.将读取的数据替换txt指定行的内容
//替换指定行的内容
List<String> lines = Files.readAllLines(Paths.get(filePath + fileName));
List<String> replaced = new ArrayList<>();
//读取txt开始的行数
int lineNo = 4;
int i = 0;
for (String line : lines) {
if (lineNo > 3 && lineNo <= 29) {
replaced.add(list1.get(i));
i++;
} else {
replaced.add(line);
}
lineNo++;
}
Files.write(Paths.get(filePath + "new" + fileName), replaced);