天天看点

java 分割合并文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class Main {

	static final String SUFFIX = ".d";
	
	static String[] divide2(String name, long size) throws Exception{
		File file = new File(name);
		if (!file.exists() || (!file.isFile())) { 
			throw new Exception("no find!");
		}
		File parent = file.getParentFile();
		long filesize =file.length();
		int num = (filesize % size != 0) ? (int)(filesize / size +1) : (int)(filesize / size);
		String[] fileNames= new String[num];
		FileInputStream in = new FileInputStream(file);
		long end = 0;
		long begin = 0;
		for(int i = 0; i < num; i++) {
			File out = new File(parent, "part_"+i + SUFFIX);
			FileOutputStream fos = new FileOutputStream(out);
			end += size;
			end = (end > filesize) ? filesize : end;
			for (; begin < end; begin++) {
				fos.write(in.read());
			}
			fos.flush();
			fos.close();
			fileNames[i] = out.getAbsolutePath();
		}
		in.close();
		return fileNames;
	}
    
	static void fileMerge(String files[], String target) {
		final int BUFFER_SIZE = 8 * 1024;
		try {
			FileChannel fos = new FileOutputStream(target).getChannel();
			for (int i = 0; i < files.length; i++) {
				FileChannel fis = new FileInputStream(files[i]).getChannel();
				ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
				while (fis.read(bb) != -1) {
					bb.flip();
					fos.write(bb);
					bb.clear();
				}
				fis.close();
			}
			fos.close();
			System.out.println("合并success!");
		} catch (Exception e) {
			System.out.println("error: " + e);
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String n = "/Users/Desktop/abc/Guide";
		long size = 900 * 1024;
		String[] fileNames;
		try {
			fileNames = divide2(n, size);
			 for (int i = 0; i < fileNames.length; i++) { 
	            System.out.println(fileNames[i]); 
	        } 
			fileMerge(fileNames, "/Users/Desktop/abc/help");
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}