本帖最后由 xiaoHei 于 2013-5-6 21:08 编辑
- import java.io.*;
- import java.util.*;
- import java.util.concurrent.locks.*;
- class Test
- {
- static int id ;
- static int del;
- static Lock lock = new ReentrantLock();
- static Condition condition = lock.newCondition();
- public static void main(String[] args)
- {
- System.out.println("请输入要分解的文件");
- Scanner input = new Scanner(System.in);
- String path = input.nextLine();
- split(path);
- System.out.println("请输入要合并的文件夹");
- path = input.nextLine();
- try {
- sequenceInputStream(path);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /*
- * 分解文件
- * RandomAccessFile+使用多线程实现
- * */
- public static void split(String path){
- final File src = new File(path); //要分解的文件
- final File dest = new File(src.getParent(),"."+src.getName()); //临时文件夹
- dest.mkdirs(); //创建临时文件夹
- final long len = src.length()/5+1; //算出每个分解出来文件时多大
- for( int i=0;i<5;i++){ //循环5次,创建5个线程,每个线程输出 分解出来的每个文件中的内容
- new Thread(){ //创建线程,输出分解出来的内容
- public void run(
- lock.lock();
- try(
- RandomAccessFile ra = new RandomAccessFile(src,"rw");
- FileOutputStream fos = new FileOutputStream(new File(dest,(id+1)+""));
- ){
- long lo = id++*len;
- ra.seek(lo);
- lock.unlock();
- int index=1;
- int l;
- byte[] b = new byte[1024*1024];
- while((l=ra.read(b,0,(int)(b.length*index++<len?b.length:len%b.length)))!=-1){
- fos.write(b,0,l);
- if(l==len%b.length) break;
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- del++;
- }
- }.start(); //开启线程
- }
- ---------------------------------------------------------------------------------------------------------------------------------------
- while(del==5){ //如果5个线程都执行完毕,就用临时文件夹,替换源文件
- /*
- * 以下代码
- * 不设断点,就执行不到,求原因
- * */
- System.out.println(src.delete());
- System.out.println(dest.renameTo(src));
- break;
- }
- ----------------------------------------------------------------------------------------------------------------------------------------
- }
- /*
- * 下面是将分解出来的5个文件合并成一个文件,没有问题....
- * */
- public static void sequenceInputStream(String path) throws IOException{
- SequenceInputStream sis=null;
- BufferedOutputStream bos=null;
- File src=new File(path);
- File dest = new File(src.getParent(),"."+src.getName());
- try{
- ArrayList<BufferedInputStream> al = new ArrayList();
-
- for(File file : src.listFiles()){
- al.add(new BufferedInputStream(new FileInputStream(file)));
- }
- sis = new SequenceInputStream(Collections.enumeration(al));
- bos = new BufferedOutputStream(new FileOutputStream(dest));
- int i;
- while((i=sis.read())!=-1){
- bos.write(i);
- }
- }finally{
- try{
- sis.close();
- }finally{
- bos.close();
- }
- }
- del(src);
- src.delete();
- System.out.println(dest.renameTo(src));
- }
- /*
- * 删除文件夹
- * */
- public static void del(File file){
- if(!file.isDirectory()){
- file.delete();
- }else{
- File[] fs = file.listFiles();
- for(File f:fs){
- del(f);
- }
- }
- }
- }
复制代码 |