现在的位置: 首页 > 综合 > 正文

如何实现文件的分割与合并?

2013年08月12日 ⁄ 综合 ⁄ 共 1914字 ⁄ 字号 评论关闭

        使用RandomAccessFile类可实现文件的分割和合并功能,该类具有在文件任意位置进行读写的功能。例如多线程下载、断点续传等功能都需要用到文件分割和合并。

        简单示例如下,不完善之处,请多指教。

public class ImplementsFileCutAndUnite {
	
	/**
	 * 
	 * @param fileName 源文件
	 * @param filterFolder 分割文件所在目录
	 * @param size 每一份大小,以KB为单位
	 */
	public void cut(String fileName, String filterFolder, int size) {
		size = size * 1024;
		int maxSize = 0;
		
		File outFolder = new File(filterFolder);
		if(!outFolder.exists()) {
			outFolder.mkdirs();
		}
		File inFile = new File(fileName);
		
		// 取得文件的大小
		int fileLength = (int) inFile.length();
		
		// 取得要分割的个数
		int value = 0;
		
		RandomAccessFile inn = null;
		RandomAccessFile outt = null;
		try {
			// 打开要分割的文件
			inn = new RandomAccessFile(inFile, "r");
			value = fileLength / size;
			
			int i = 0;
			int j = 0;
			
			for(; j < value; j ++) {
				File outFile = new File(filterFolder + File.separator + inFile.getName() + j + "tmp");
				RandomAccessFile out = new RandomAccessFile(outFile, "rw");
				maxSize += size;
				for(; i < maxSize; i ++) {
					out.write(inn.read());
				}
				out.close();
			}
			File outFile = new File(filterFolder + File.separator + inFile.getName() + j + "tmp");
			outt = new RandomAccessFile(outFile, "rw");
			for(; i < fileLength; i ++) {
				outt.write(inn.read());
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				outt.close();
				inn.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param fileName 合并之后的文件
	 * @param filterFolder 分割文件所在目录
	 * @param filterName 分割后的文件后缀
	 * @throws Exception
	 */
	public void unite(String fileName, String filterFolder, final String filterName) throws Exception {
		File [] tt;
		File inFile = new File(filterFolder);	// 在当前目录下的文件
		File outFile = new File(fileName);		// 取得输出名
		RandomAccessFile outt = new RandomAccessFile(outFile, "rw");
		
		tt = inFile.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				String rr = new File(name).toString();
				return rr.endsWith(filterName);
			}
			
		});
		
		for(int i = 0; i < tt.length; i ++) {
			System.out.println(tt[i]);
		}
		
		for(int i = 0; i < tt.length; i ++) {
			RandomAccessFile inn = new RandomAccessFile(tt[i], "r");
			int c = 0;
			while((c = inn.read()) != -1) {
				outt.write(c);
			}
		}
		
		outt.close();
	}
}

抱歉!评论已关闭.