如何將兩個文件合併?

在Java面試題中,我們經常會遇到將兩個文件合併的題目,這一次我特意認真做了一下這個題目,用了三種方法實現兩個文件的合併。

第一種方法:

需要使用到FileInputStream類和FileOutputStream類:

代碼如下:

File mergeFile=new File("D:\\eclipse\\merge.txt");
File file1=new File("context.txt");
File file2=new File("words.conf");
if(!mergeFile.exists()){
try {
mergeFile.createNewFile();
FileOutputStream mergeStream=new FileOutputStream(mergeFile);
FileInputStream inputStream1=new FileInputStream(file1);
FileInputStream inputStream2=new FileInputStream(file2);
byte[] b=new byte[100];
while((inputStream2.read(b))!=-1){
mergeStream.write(b);
}
while((inputStream1.read(b))!=-1){
mergeStream.write(b);
}
mergeStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}

注意:在輸出流之後,最好養成flush()的習慣;

第二種方法,需要用到SequenceInputStream和FileInputStream和FileOutputStream

try {
FileOutputStream fileOutputStream=new FileOutputStream(new File("D:\\eclipse\\merge.txt"));
FileInputStream inputStream1=new FileInputStream("context.txt");
FileInputStream inputStream2=new FileInputStream("words.conf");
SequenceInputStream sequenceInputStream=new SequenceInputStream(inputStream2, inputStream1);
byte[] b=new byte[100];
while((sequenceInputStream.read(b))!=-1){
fileOutputStream.write(b);
}
} catch (Exception e) {
e.printStackTrace();
}

第三種方法,需要用到RandomAccessFile 

try {
RandomAccessFile writeFile=new RandomAccessFile(new File("D:\\eclipse\\merge.txt"), "rw");
RandomAccessFile readFile=new RandomAccessFile("context.txt", "r");
RandomAccessFile readFile2=new RandomAccessFile("words.conf", "r");
byte[] b=new byte[100];
while((readFile.read(b))!=-1){
writeFile.write(b);
}
while((readFile2.read(b))!=-1){
writeFile.write(b);
}
} catch (Exception e) {
e.printStackTrace();
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章