//File Name: SplitFile.java
//SplitFile.java
//Contains the main function for file splitting
//this file uses the FileSplitter class
import java.io.*;
class SplitFile
{
public static void main (String[] args) throws IOException
{
Console con=System.console();
String fileName;
int size=0;
//get the file name in current folder for splitting
System.out.print("Enter the file name to split: ");
fileName=con.readLine();
//get the size of the target files (in bytes)
System.out.print("Enter the size of the target file(s): ");
size=Integer.parseInt(con.readLine());
//create object of FileSplitter with current file and size of target
FileSplitter splitMyFile=new FileSplitter(fileName,size);
splitMyFile.split(); //call the method to split the file
}
}
//File Name: FileSplitter.java
//Holds the functions for splitting the file
import java.io.*;
class FileSplitter
{
private File fileToSplit; //to store the file name which will be split
private int sizeInBytes; //to hold the size (in bytes) of the target files
private int count; //to hold the count of splitted parts created so far.
private File checkFileExists(String fName) //check if a file exists there with specified name
{
File f=new File(fName);
if(f.exists()==false)
{
System.out.println("File "+fName+" does not exists");
System.exit(0);
}
return f;
}
private int validateSize(int s)
{
if(fileToSplit.length()"
{
++count;
String fileName;
fileName="part_"+count+"."+fileToSplit.getName();
return fileName;
}
public FileSplitter(String fName,int s) //counstructor to set the file name (after checking its existance) and target file size
{
fileToSplit=checkFileExists(fName);
sizeInBytes=validateSize(s);
count=0;
}
public void split() throws IOException //actual splitter function for dividing the file
{
//create various objects to be used in the process
FileInputStream fis=new FileInputStream(fileToSplit); //FileInputStream object to hold the file for reading
BufferedInputStream bis=new BufferedInputStream(fis); //BufferedInputStream object to lower the no. of disk operations
File fileSegment=new File(createNextFileName()); //to hold the file reference of the next split file part
FileOutputStream fos=new FileOutputStream(fileSegment); //FileOutputStream object to write the output to.
BufferedOutputStream bos=new BufferedOutputStream(fos); //BufferedOutputStream object to lower the no. of disk operations
int ch; //to hold each byte as read from the file
int currentByteCount=0; //to hold the no. of bytes read so far for this file segment.
while((ch=bis.read())!=-1)
{
bos.write(ch);
++currentByteCount;
if(currentByteCount==sizeInBytes) //if the no. of bytes read has reached the specified byteCount
{
bos.close();
fos.close();
fileSegment=new File(createNextFileName());
fos=new FileOutputStream(fileSegment);
bos=new BufferedOutputStream(fos);
currentByteCount=0;
}
}
bis.close();
fis.close();
bos.close();
fos.close();
}
}