总结一下对一些文件的操作
1.复制文件
public static void main(String[] args) {
String sourcePath = "\路径\源文件.txt";
String destinationPath = "\路径\目标文件.txt";
try {
Path source = Paths.get(sourcePath);
Path destination = Paths.get(destinationPath);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件复制成功!");
} catch (IOException e) {
System.out.println("文件复制失败:" + e.getMessage());
}
}
复制文件夹
public static void copyDirectory(File sourceDirectory, File destinationDirectory) throws Exception {
if (!sourceDirectory.isDirectory()) {
throw new Exception ("Source is not a directory.");
}
if (!destinationDirectory.exists()) {
destinationDirectory.mkdirs();
}
File[] files = sourceDirectory.listFiles();
if (files != null) {
for (File file : files) {
File destination = new File(destinationDirectory, file.getName());
if (file.isDirectory()) {
copyDirectory(file, destination);
} else {
Files.copy(file.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
方法调用
public static void main(String[] args) {
File sourceDirectory = new File("/source/directory");
File destinationDirectory = new File("/destination/directory");
try {
copyDirectory(sourceDirectory, destinationDirectory);
System.out.println("Files copied successfully!");
} catch (IOException e) {
System.out.println("An error occurred during the file copy process.");
e.printStackTrace();
}
}
2.获取ini文件字段信息,设置ini文件字段内容
不需要第三方包
public static void setProperty(String iniPath,String key, String value) throws IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream(iniPath);
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream(iniPath);
props.setProperty(key, value);
props.store(out, null);
out.close();
}
public static String getProperty(String path,String key) throws IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream(path);
props.load(in);
in.close();
return props.getProperty(key);
}
3.excel操作
我这边遇到的需求是统计一个excel的总行数(一个excel页有多个Sheet页),同时也要统计某一关键字出现的个数
先引入第三方包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
代码
说明: 我想要的关键字都在表头"性质"下面。
public static void main(String[] args) {
String filePath = "C:\\测试案例\\柜面项目组_测试案例一批次.xls";
Map<String, Integer> keywordCountMap = new HashMap<>();
//关键列表头
String keyHeadword = "性质";
try {
FileInputStream file = new FileInputStream(new File(filePath));
Workbook workbook = WorkbookFactory.create(file);
//总行数
int totalRows = 0;
// 遍历每个 sheet
for (Sheet sheet : workbook) {
//每个sheet页的行数
int numRows = sheet.getLastRowNum() + 1;
totalRows += numRows;
System.out.println("Sheet '" + sheet.getSheetName() + "' 有 " + numRows + " 行");
Row headerRow = null;
//一个Sheet页面的行信息
Row row1 = sheet.getRow(0);
//boolean hasKey = false;
int headerColumnIndex = -1;
//判断行信息是否存在
if (ToolUtils.isNotEmpty(row1)) {
//遍历每个单元格元素
for (Cell cell : row1) {
//找到关键列--确定住row对象
if (cell.getCellType() == Cell.CELL_TYPE_STRING && keyHeadword.equals(cell.getStringCellValue())) {
headerRow = row1;
hasKey = true;
headerColumnIndex = cell.getColumnIndex();
break;
}
}
}
if (!hasKey) {
continue;
}
if (headerRow != null) {
String cellValue = "";
//防止关键列下面所有的数据为空
if (headerColumnIndex >= 0) {
// 遍历数据行,统计关键字出现次数
for (Row row : sheet) {
if (row.getRowNum() == headerRow.getRowNum()) {
continue; // 跳过表头行
}
Cell cell = row.getCell(headerColumnIndex);
if (ToolUtils.isNotEmpty(cell)) {
cellValue = cell.getStringCellValue();
//
if (cellValue.equals("正例") || cellValue.equals("反例")) {
int count = keywordCountMap.getOrDefault(cellValue, 0);
keywordCountMap.put(cellValue, count + 1);
}
}
}
System.out.println("当前sheet页正例个数:" + keywordCountMap.get(cellValue));
} else {
System.out.println("找不到表头为 \"" + headerRow + "\" 的列");
}
} else {
System.out.println("找不到表头为 \"" + headerRow + "\" 的行");
}
}
// 输出关键字统计结果
for (Map.Entry<String, Integer> entry : keywordCountMap.entrySet()) {
System.out.println("关键字: " + entry.getKey() + " 出现在" + "列中,出现次数:" + entry.getValue());
}
System.out.println("总共有 " + totalRows + " 行");
workbook.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
}
}
4.打包成zip
调用在main里面。
private static final byte[] buf = new byte[1024];
public static void main(String[] args) throws Exception {
//测试方法1
toZip("D:\\Downloads\\20230310.Trace.zip", "D:\\Downloads\\20230310.Trace.log", true);
}
/**
* 压缩成ZIP 方法1
*
* @param zipFileName 压缩文件夹路径
* @param sourceFileName 要压缩的文件路径
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static Boolean toZip(String zipFileName, String sourceFileName, boolean KeepDirStructure) {
Boolean result = true;
long start = System.currentTimeMillis();//开始
ZipOutputStream zos = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
zos = new ZipOutputStream(fileOutputStream);
File sourceFile = new File(sourceFileName);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();//结束
log.info("压缩完成,耗时:" + (end - start) + " 毫秒");
} catch (Exception e) {
result = false;
e.printStackTrace();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
return result;
}
/**
* 压缩成ZIP 方法2 一次性压缩多个文件
*
* @param srcFiles 需要压缩的文件列表
* @param zipFileName 压缩文件输出
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String zipFileName, List<File> srcFiles) throws Exception {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
zos = new ZipOutputStream(fileOutputStream);
for (File srcFile : srcFiles) {
compress(srcFile, zos, srcFile.getName(), true);
}
long end = System.currentTimeMillis();
log.info("压缩完成,耗时:" + (end - start) + " 毫秒");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
public static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception {
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}