1.如何读取文件的内容为字符串
public String readFileAsString(String filePath) throws java.io.IOException {
StringBuffer fileData = new StringBuffer("");
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
2.如何合并多个文件的内容到一个大文件中
![这里是引用](https://img-blog.csdnimg.cn/20210617230231115.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAxNDcyMQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210617230435961.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAxNDcyMQ==,size_16,color_FFFFFF,t_70)
public class Combine {
public static void main(String[] args) throws Exception {
String FileOut="C:\\Users\\Administrator\\Desktop\\Work\\combine.txt";
BufferedWriter bw=new BufferedWriter(new FileWriter(FileOut));
Process process = new Process();
File[] list = new File("C:\\Users\\Administrator\\Desktop\\Work\\before").listFiles();
for(File file : list)
{
String text = process.readFileAsString(file.toString());
text = text.replace("\n", "").replace("\r", "").replace("\t","");
bw.write(file.toString());
bw.write("\t\t");
bw.write(text);
bw.newLine();
}
bw.close();
System.out.println("读取完成");
}
}
public class Process {
public String readFileAsString(String filePath) throws java.io.IOException {
StringBuffer fileData = new StringBuffer("");
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
}