可以实现不同文件的合并,将文件拖入这个命令即可。
@echo off
setlocal enabledelayedexpansion
set "outputFile=merged_output.txt"
rem Check if the output file already exists and delete it
if exist "%outputFile%" del "%outputFile%"
rem Loop through all the dragged files
for %%I in (%*) do (
type "%%I" >> "%outputFile%"
)
echo Files merged successfully into %outputFile%
pause
```java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class MergeSqlFiles {
public static void main(String[] args) {
// 输入SQL文件夹路径
String sqlFolder = "originalPath";
// 合并后的文件路径和名称
String mergedFilePath = "targetPath\\merged.sql";
//方法1
mergeSqlFiles(sqlFolder, mergedFilePath);
//方法2
mergeSqlFilesByStream(sqlFolder, mergedFilePath);
}
/**
* 合并多个sql文件为一个sql文件
*
* @param folderPath
* @param mergedFilePath
*/
public static void mergeSqlFiles(String folderPath, String mergedFilePath) {
//获取文件夹
File floder = new File(folderPath);
File[] files = floder.listFiles();
//新的文件夹
File newFile = new File(mergedFilePath);
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(newFile))) {
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".sql") && !file.getName().startsWith("merged")) {
//读取文件内的内容
System.out.println("merging file: " + file.getName());
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
//写入新的一行
bufferedWriter.write(line);
//写入换行符号
bufferedWriter.newLine();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void mergeSqlFilesByStream(String folderPath, String mergedFilePath) {
//获取文件夹
Path floder = Paths.get(folderPath);
//新的文件夹
Path mergeFile = Paths.get(mergedFilePath);
try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergeFile))) {
if (Files.isDirectory(floder)) {
Files.list(floder)
.filter(file -> file.toFile().isFile() && file.getFileName().toString().endsWith(".sql") && !file.getFileName().toString().startsWith("merge"))
.forEach(file -> {
System.out.println("mergeFile: " + file.getFileName());
try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file))) {
byte[] bytes = new byte[1024];
int bytesRead;
while ((bytesRead=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,bytesRead);
}
outputStream.write(System.lineSeparator().getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
进入对应的文件目录使用此命令
copy *.sql merge.sql