合并文件java,在java中合并文件

i have an array of files that i want to merge them in one file

please give me method

thank's in advance

i used this but this not work

public static void joinf(File f1, File f2){

try{

InputStream in = new FileInputStream(f1);

OutputStream out = new FileOutputStream(f2,true);

byte[] buf = new byte[8192];

int len;

while ((len = in.read(buf)) > 0){

out.write(buf, 0, len);

}

in.close();

out.close();

System.out.println("File copied.");

}

catch(FileNotFoundException ex){

System.out.println(ex.getMessage() + " in the specified directory.");

System.exit(0);

}

catch(IOException e){

System.out.println(e.getMessage());

}

}

public void pro(File a,File[]b){

for(int i=0;i

joinf(a,b[i]);

}

}

解决方案

Use IOUtils to do this. See my example:

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class SourceCodeProgram {

public static void main(String[] args) throws Exception {

IOCopier.joinFiles(new File("D:/d.txt"), new File[] {

new File("D:/s1.txt"), new File("D:/s2.txt") });

}

}

class IOCopier {

public static void joinFiles(File destination, File[] sources)

throws IOException {

OutputStream output = null;

try {

output = createAppendableStream(destination);

for (File source : sources) {

appendFile(output, source);

}

} finally {

IOUtils.closeQuietly(output);

}

}

private static BufferedOutputStream createAppendableStream(File destination)

throws FileNotFoundException {

return new BufferedOutputStream(new FileOutputStream(destination, true));

}

private static void appendFile(OutputStream output, File source)

throws IOException {

InputStream input = null;

try {

input = new BufferedInputStream(new FileInputStream(source));

IOUtils.copy(input, output);

} finally {

IOUtils.closeQuietly(input);

}

}

}

If you can't use IOUtils lib, then write your own implementation. Example:

class IOUtils {

private static final int BUFFER_SIZE = 1024 * 4;

public static long copy(InputStream input, OutputStream output)

throws IOException {

byte[] buffer = new byte[BUFFER_SIZE];

long count = 0;

int n = 0;

while (-1 != (n = input.read(buffer))) {

output.write(buffer, 0, n);

count += n;

}

return count;

}

public static void closeQuietly(Closeable output) {

try {

if (output != null) {

output.close();

}

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值