Monday 11 January 2016

Java program to Split a file into multiple files

In this program we split a given file into multiple files of desired(less than original file) size. This program can be practically useful for transferring files when we do not have portable device of sufficient capacity. In this we ask user to enter the pathname of file and desired output file size.

Source Code:


import java.io.*;
class FileSplit
{
private String name,path,gname;
private long nsize,size,n=0;
public FileSplit(String pn,int i )
{
name=pn;
nsize=i;
}
public void run()
{
try
{
FileInputStream fis=new FileInputStream(name);
File f=new File(name);
size=f.length(); //calc size of input file
System.out.println("\nLength "+size);
path=f.getParent();
long d=0;
while(size>=d) //no.of files
{
n++;
d=d+nsize;
}
System.out.println("\nNumber of Files created: "+n);
int ch;
gname=f.getName();
for(int i=0;i<n;i++)
{
System.out.println(path+"\\"+i+"."+gname);
FileOutputStream fos=new FileOutputStream(path+"\\"+i+"."+gname);
while((ch=fis.read()) != -1)
{
fos.write(ch);
if(new File(path+"\\"+i+"."+gname).length()==nsize)
{
fos.close();
break;
}
}
}
fis.close();
f.delete();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class M
{
public static void main(String args[]) throws Exception
{
Console con=System.console();
System.out.println("Enter the fileName with Path: ");
String s=con.readLine();
System.out.println("Enter the fidesired file size(in bytes): ");
int l=Integer.parseInt(con.readLine());

FileSplit f=new FileSplit(s,l);
f.run();
}
}

No comments:

Post a Comment