[Java] 纯文本查看 复制代码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class Tool_FilesConnect {
public static void main(String[] args) throws IOException {
System.out.println(System.getProperty("user.dir"));
Scanner sc = new Scanner(System.in);
File dirFile = null;
while(true) {
System.out.println("请输入需要连接的文件存在的文件夹路径,当前路径请直接确定:");
String strOne = sc.nextLine();
if("".equals(strOne)) {
dirFile = new File(System.getProperty("user.dir"));
}else{
dirFile = new File(strOne);
}
if(!dirFile.exists()){
System.out.println("文件目录不存在");
}else if(dirFile.isFile()) {
System.out.println("该路径指向的是单个文件,不需要连接");
}else {
break;
}
}
sc.close();
System.out.println("连接中.........");
File connectedFile = new File(dirFile.getAbsolutePath().substring(0, dirFile.getAbsolutePath().lastIndexOf("/")) + "/[整合]" +(dirFile.getName() == null ? "" : dirFile.getName()));
toolMethod_FilesConnect(dirFile,connectedFile);
System.out.println("收工!");
}
private static void toolMethod_FilesConnect(File dirFile,File connectedFile) throws IOException {
File[] allFile = dirFile.listFiles();
Arrays.sort(allFile);
for (File file : allFile) {
/*
* 如果是文本文档
* */
if (file.isFile() && file.canRead() && !file.isHidden() && (file.getName().endsWith(".txt") || file.getName().endsWith(".md"))) {
System.out.print(file.getAbsolutePath());
try(
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
BufferedWriter bw =
new BufferedWriter(new FileWriter(connectedFile.getAbsolutePath()
+ file.getName().substring(file.getName().lastIndexOf("."),file.getName().length()),true));
) {
String line;
while((line = br.readLine()) != null){
bw.write(line);
bw.newLine();
}
}
System.out.println("...已连接!");
}else if (file.isFile() && !file.isHidden() && file.canRead()) {
System.out.print(file.getAbsolutePath());
try(
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(connectedFile.getAbsolutePath()
+ file.getName().substring(file.getName().lastIndexOf("."),file.getName().length()),true))
) {
int temp;
while((temp = bis.read()) != -1) {
bos.write(temp);
}
}
System.out.println("...已连接!");
}else if (file.isDirectory()) {
toolMethod_FilesConnect(file,connectedFile);
}
}
}
}