分割文件

/**
	 * Split the specific file into pieces without deleting original file
	 * @param fileName Absolute path of the resource file
	 * @param desPath Destination path for generating the split files
	 * @param splitSize Size of each split part (unit: MB)
	 * @return File objects of the whole split files
	 */
	public ArrayList<File> splitFile(String fileName, String desPath, int splitSize) {
		BufferedInputStream bi = null;
		BufferedOutputStream bo = null;
		try {
			bi = new BufferedInputStream(new FileInputStream(fileName));
			
			ArrayList<File> files = new ArrayList<File>();
			byte [] buf = new byte [1024 * 1024];
			long loopCount = new File(fileName).length() / (1024 * 1024);
			if (loopCount == 0)  //防止文件大小<1MB的情况
				loopCount = 1;
			
			for (int i = 0; i < loopCount; i++) {
				int reLen, count = 1;
				bo = new BufferedOutputStream(new FileOutputStream(desPath + "\\SplitFile_" + (i + 1) + ".part"));
				while ((reLen = bi.read(buf)) != -1) {
					bo.write(buf, 0, reLen);
					count++;
					if (count > splitSize) {
						bo.close();
						break;
					}
				}
				files.add(new File(desPath + "SplitFile_" + (i + 1) + ".part"));
			}
			
			return files;
		} catch (IOException e) {
			throw new RuntimeException("Split file failed");
		} finally {
			try {
				if (bi != null) {
					bi.close();
				}
			} catch (IOException e2) {
				throw new RuntimeException("Close BufferedInputStream failed");
			}

			try {
				if (bo != null) {
					bo.close();
				}
			} catch (IOException e2) {
				throw new RuntimeException("Close BufferedOutputStream failed");
			}
		}
	}


你可能感兴趣的:(文件,分割)