1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import java.io.*;
public class FileSplitter
{
public static final long floppySize = (long)(1.4 * 1024 * 1024);
public static long chunkSize = 100;
/**
* split the file specified by filename into pieces, each of size
* chunkSize except for the last one, which may be smaller
*/
public static void split(String filename)
{
// open the file
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
// get the file length
File f = new File(filename);
long fileSize = f.length();
// loop for each full chunk
int subfile;
for (subfile = 0; subfile < fileSize / chunkSize; subfile++)
{
// open the output file
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename + "." + subfile));
// write the right amount of bytes
for (int currentByte = 0; currentByte < chunkSize; currentByte++)
{
// load one byte from the input file and write it to the output file
out.write(in.read());
}
// close the file
out.close();
}
// loop for the last chunk (which may be smaller than the chunk size)
if (fileSize != chunkSize * (subfile - 1))
{
// open the output file
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename + "." + subfile));
// write the rest of the file
int b;
while ((b = in.read()) != -1)
out.write(b);
// close the file
out.close();
}
// close the file
in.close();
}
/**
* list all files in the directory specified by the baseFilename
* , find out how many parts there are, and then concatenate them
* together to create a file with the filename <I>baseFilename</I>.
*/
public static void join(String baseFilename)
{
int numberParts = getNumberParts(baseFilename);
// now, assume that the files are correctly numbered in order (that some joker didn't delete any part)
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(baseFilename));
for (int part = 0; part < numberParts; part++)
{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(baseFilename + "." + part));
int b;
while ( (b = in.read()) != -1 )
out.write(b);
in.close();
}
out.close();
}
} |
Partager