- 拼接文本文件:利用FileReader和FileWriter类分别读取和写入文件内容,再利用BufferedReader和BufferedWriter类对文件内容进行缓存处理,实现拼接文本文件的操作。以下为示例代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ConcatenateTextFile {
public static void main(String[] args) {
String file1 = "file1.txt";
String file2 = "file2.txt";
String output = "output.txt";
try (BufferedReader br1 = new BufferedReader(new FileReader(file1));
BufferedReader br2 = new BufferedReader(new FileReader(file2));
BufferedWriter bw = new BufferedWriter(new FileWriter(output))) {
String line = null;
while ((line = br1.readLine()) != null) {
bw.write(line);
bw.newLine();
}
while ((line = br2.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
- 拼接二进制文件:利用FileInputStream和FileOutputStream类分别读取和写入文件内容,再利用ByteArrayInputStream和ByteArrayOutputStream类对文件内容进行缓存处理,实现拼接二进制文件的操作。以下为示例代码:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ConcatenateBinaryFile {
public static void main(String[] args) {
String file1 = "file1.bin";
String file2 = "file2.bin";
String output = "output.bin";
try (FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream(output)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis1.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
while ((length = fis2.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
fos.write(baos.toByteArray());
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
以上两个示例均可直接运行,结果输出到指定的output文件中。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java实现两个文件的拼接 - Python技术站