File Merger

 Description:          The following two programs merge the pieces obtained from the splitting using File Splitter class.
 
Primary Inputs:    Name of the original file that was split using FileSplitter.java
Primary Output:    Original File in its entirety.
Platform Used:      JDK 1.6 with JCreator
 

//File Name: MergeFiles.java
//Contains the main function for file merging
//this file uses the FileMerger class
import java.io.*;
class MergeFiles
{
public static void main (String[] args) throws IOException
{
Console con=System.console();
String fileName;

//get the file name of the original file that was splitted using SplitFile.java
System.out.print("Enter the File Name for merging: ");
fileName=con.readLine();

FileMerger f=new FileMerger(fileName);
f.merge();
}
}

 

/*******************************************************************
*This class merges the file segments created using SplitFile.java
*Requires specification of the original file name that was splitted.
*It does not take into account how many no of segments were created.
*So, if some of the parts of the file are lost, then it would merge
*till the last part found in sequence starting from 1.
********************************************************************
*/
//File Name: FileMerger.java
import java.io.*;
class FileMerger
{
File fileMerge; //to store result file
int count; //to hold the count of current file segment being merged

//private methods
private String getNextFileName(int c) //to get the expected file name of the next segment in sequence

{
String fileName;
fileName="part_"+c+"."+fileMerge.getName();
return fileName;
}
private boolean checkFileExists(String fName)
{
File f=new File(fName);
if(f.exists()==false)
return false;
return true;
}

//public methods
public FileMerger(String fileName) //constructor
{
fileMerge=new File(fileName);
File f=new File(getNextFileName(1)); //get name of the first required file-part
if(!checkFileExists(getNextFileName(1))) //check if the first-part exists
{
System.out.println("File "+f.getName()+" is missing");
System.exit(0);
}
count=0;
}
public void merge() throws IOException
{
//set first source file segment
File currentFile=new File(getNextFileName(++count));
FileInputStream fis=new FileInputStream(currentFile);
BufferedInputStream bis=new BufferedInputStream(fis);

//set destination file
FileOutputStream fos=new FileOutputStream(fileMerge);
BufferedOutputStream bos=new BufferedOutputStream(fos);

int ch; //to hold each byte

while(true)
{
while((ch=bis.read())!=-1)
bos.write(ch);

//eof for current part reached. close the streams
bis.close(); fis.close();

currentFile=new File(getNextFileName(++count)); //get next file-part name
if(currentFile.exists())
{
fis=new FileInputStream(currentFile);
bis=new BufferedInputStream(fis);
}
else //next part in sequence is not found. Abort merging
break;
}
//close output streams
bos.close();
fos.close();
}
}

 

Rate this post

Leave a Reply