import java.io.*;
class SplitFile
{
private File fSplit;
private int sizeInBytes;
private int count;
public static void main(String[] args) throws IOException
{
Console con = System.console();
String fileName;
int size = 0;
System.out.print("Enter the file name to split: ");
fileName = con.readLine();
System.out.print("Enter the size of the target file: ");
size = Integer.parseInt(con.readLine());
SplitFile sf = new SplitFile(fileName, size);
sf.split();
}
public File checkFileExists(String fName)
{
File f = new File(fName);
if (!f.exists())
{
System.out.println("File " + fName + " does not exists");
System.exit(0);
}
return f;
}
public int validateSize(int s)
{
if (fSplit.length() < s)
{
System.out.println("Invalid Size");
System.exit(0);
}
return s;
}
public String createNextFileName()
{
++count;
String fileName;
fileName = "part_" + count + "." + fSplit.getName();
return fileName;
}
public SplitFile(String fName, int s)
{
fSplit = checkFileExists(fName);
sizeInBytes = validateSize(s);
count = 0;
}
public void split() throws IOException
{
FileInputStream fis = new FileInputStream(fSplit);
BufferedInputStream bis = new BufferedInputStream(fis);
File fileSegment = new File(createNextFileName());
FileOutputStream fos = new FileOutputStream(fileSegment);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int ch;
int currentByteCount = 0;
while ((ch = bis.read()) != -1)
{
bos.write(ch);
++currentByteCount;
if (currentByteCount == sizeInBytes)
{
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();
}
}