java.lang.Objectjava.io.InputStream
java.io.SequenceInputStream
Example of divide a file:filepath: the file to be separated.
size:the size of each separated file.
count: the number of separated file.
FileInputStream fileInputStream = new FileInputStream(new File(filepath)); BufferedInputStream bufInputStream = new BufferedInputStream(fileInputStream); byte[] data = new byte[1]; int count = 0; //Count the number of separated files. if(fileInputStream.available() % size == 0) count = fileInputStream.available() / size; else count = fileInputStream.available() / size + 1; for(int i = 0; i < count; i++) { int num = 0; File file = new File(filepath + "_" + (i + 1)); BufferedOutputStream bufOutputStream = new BufferedOutputStream( new FileOutputStream(file)); //Write the read-out data into a separated file while(bufInputStream.read(data) != -1) { bufOutputStream.write(data); //count the bytes of the separated file. num++; if(num == size) { bufOutputStream.flush(); bufOutputStream.close(); break; } } if(num < size) { bufOutputStream.flush(); bufOutputStream.close(); } }Example of combine separated files:filename: the path of the separated files locatenumber : the number of the separated files.List<InputStream> list = new ArrayList<InputStream>(); //collect the separated files for(int i = 0; i < number; i++) { File file = new File(filename + "_" + (i+1)); list.add(i, new FileInputStream(file)); } final Iterator<InputStream> iterator = list.iterator(); Enumeration<InputStream> enumation = new Enumeration<InputStream>() { public boolean hasMoreElements() { return iterator.hasNext(); } public InputStream nextElement() { return iterator.next(); } }; BufferedInputStream bufInputStream = new BufferedInputStream( new SequenceInputStream(enumation), 8192); BufferedOutputStream bufOutputStream = new BufferedOutputStream( new FileOutputStream(filename), 8192); byte[] data = new byte[1]; while(bufInputStream.read(data) != -1) bufOutputStream.write(data); bufInputStream.close(); bufOutputStream.flush(); bufOutputStream.close();
沒有留言:
張貼留言