Upload
bunty-chugh
View
184
Download
4
Tags:
Embed Size (px)
Citation preview
FILE SPLITTER
MINOR PROJECT
SUBMITTED IN PARTIAL FULFILLING
REQUIREMENT OF
BACHELOR OF TECHNOLOGY
(COMPUTER SCIENCE & ENGG)
BY
Ashish Kapoor(1704212)
Anurag Mathpal(1704213)
UNDER THE GUIDANCE OF
Er.Meenakshi
Lect. Deptt. of CSE
(SESSION Aug-Dec 2007)HARYANA COLLEGE OF TECNOLOGY & MANAGEMENT, KAITHAL
KURUKSHETRA UNIVERSITY, KURUKSHETRA
CONTENTS
Particulars Page No.
Candidate Declaration
Certificate
Acknowledgement
Abstract of Project
Chapter 1: Introduction
Chapter 2: Platform Description
2.1 SRS Documents
2.2 DFD’s
Chapter 3: Literature Review
Chapter 4: Source Code
Chapter 5: Outputs
Chapter 6: Conclusion
Chapter 7: References
CANDIDATE’S DECLARATION
I hereby certify that the work which is being presented by Ashish Kapoor and Anurag Mathpal in
partial fulfillment of requirements for the award of degree of B.Tech. in Computer Science &
Engg submitted at Haryana College of Tecnology & Management, Kaithal under
KURUKSHETRA UNIVERSITY, KURUKSHETRA is an authentic record of my own work
carried out under the supervision of Er. Meenakshi
The matter presented in this report has not been submitted by me in any other University /
Institute for the award of B.Tech Degree.
Signature of the Student
Ashish Kapoor(1704212)
Anurag Mathpal(1704213)
CERTIFICATE
This is to certify that Project Associates ASHISH KAPOOR(1704212) & ANURAG MATHPAL
(1704213) of Bachelor of Technology 7th Sem , Computer Science & Engg have successfully
completed the “MINOR PROJECT FILE SPLITTER” In the partial fulfillment for the award of
Bachelor of Technology Degree from Kurukshetra University, Kurukshetra during academic
2007 – 2008.
We wish him a prosperous, happy & bright future with all the great silvery success in his career.
Prof. V.K Shrivastav Er. Meenakshi
Head of Deptt. Lectt. , Deptt. of CSE
Computer Science & Engg
ACKNOWLEDGEMENT
I am highly grateful to the Dr. D.P. Gupta, Principal, Haryana College of Technology &
Management (HCTM), Kaithal, for providing this opportunity to carry out the project.
The constant guidance and encouragement received from Er. Meenakshi,
Department of Information Technology, HCTM, Kaithal has been of great help
in carrying our the work and is acknowledged with reverential thanks.
Without the wise counsel and able guidance, it would have been impossible
to complete the project in this manner.
I express gratitude to other faculty members of Computer Science & Engg Department, HCTM,
Kaithal for their intellectual support throughout the course of this work.
Signature of Student
Ashish Kapoor(1704212)
Anurag Mathpal(1704213)
ABSTRACT OF PROJECT
File Splitter is a java application which enables a user to split or join file of any format.With this
application, a user can make use of the secondry storage very efficiently and can optimize the
speed of the machine to be worked on. File Splitter splits a file into any no. of splits of a defined
size of the file.This application supports .jpg,..mp3,.mpeg file and saves the file into .sfl format.
INTRODUCTION
Environment: JDK 1.x to compile and JRE are required to run this application.
This includes a splitter application that splits any large file of any format into desired
number of parts.Compile the split.java file and on the command prompt enter java split
filename number. Where filename is the name of the file to be split and number is the
number of parts to be made of this file.
eg. C:\source>java split xyz.exe 3
This will produce xyz1.exe xyz2.exe xyz3.exe in the source directory in which xyz.exe was
present
The othet part of this application is the program join.java.Compile the code under join.java
and keep the class file at the destination machine\folder. Once the file is split into a number
of parts, collect all the parts move it to the destination machine\folder, make sure that
join.class is available in the same folder. Then run java join filename numberofparts.
To split a file, it is needed to specify:
The file to split. (it is not modified)
The target path; where to create these chunks; these chunks will have the name
targetpath.X, being X the chunk number.
Maximum size for each chunk.
The application also creates a batch file that allows to the user to merge the created chunks and
get the original file. It is possible to specify the kind of batch to create:
Windows platform: it creates a .bat file, with name targetpath.bat
Unix platform: it creates a sh script with name targetpath.merger
To make easier the use of Split File, it uses -only in the window interface- a settings file.
Fle Splitter can split any type of file into smaller pieces and rejoin them to the original file. It
helps you copy the split ones to floppy disk or CD/DVD, or send them via e-mail. File Splitter
supports 3 split modes: It can split a file equally by size. Users can specify a custom size such as
1.44MB(floppy disk ), 650M (CD size). It can also split a file equally by number, and cut any
segment of the file as needed.
Split large files (of any type), then easily rejoin without the use of this software. Easily break up
large files (no limits, splits any sized file) for copying to floppy or sending via email, as anyone
can recreate the original file without having this software. When you split your files, a small
program is created in the same folder and can be distributed with your split files, which will
allow anyone to recreate the original file, with the original name. You can also print any folder
contents, keep track of total files split, and view your available RAM memory. Simply run the
self-extracting file to install. (Runs on all Windows systems)
The memory space complexities are reduced in general by using this as the huge file is split in
number of splits and the obtained file is less memory consuming.
File splitter the project we are into comes as an perfect answer to this question.What this project
is all about is something that helps to reduce the memory space of files
PLATFORM DESCRIPTION
An abstract class might initially seem like an odd design. Why write a class
and not allow anyone to create instances of Java technology has evolved from a programming
language designed to create
machine-independent embedded systems into a robust, vendor-independent,
machine-independent, server-side technology, enabling the corporate community
to realize the full potential of web-centric applications.
Java began with the release of the Java Development Kit (JDK). More interface and libraries
were extended in the JDK as the corporate world demanded—and received—application
programming interfaces (API) that addressed real-world situations.
JDK API extensions fully integrated into the JDK with the release of the Java 2
Standard Edition (J2SE) of the JDK. J2SE contains all the APIs needed to build industrial
strength Java applications. However, the corporate world felt J2SE lacked the strength required
for developing enterprise-wide applications and for servicing the needs of developers of mobile
and embedded systems.
Just as C++ was becoming the language of choice for building industrial-strength
applications, another growth spurt in the evolution of programming language was
budding, fertilized by the latest disruptive technology—the World Wide Web. The
Internet had been a well-kept secret for decades before the National Science Foundation (who
oversaw the Internet) removed barriers that prevented commercialization. Until 1991 when it
was opened to commerce, the Internet was the almost exclusive domain of government agencies
and the academic community.
Once the barrier to commercialization was lifted, the World Wide Web—one of several services
offered on the Internet - became a virtual community center where visitors could get free
information about practically anything and browse through thousands of virtual stores. Browsers
power the World Wide Web. A browser translates ASCII text files written in HTML into an
interactive display that can be interpreted on any machine. As long as the browser is compatible
with the correct version of HTML and HTTP implementation , any computer running the
browser can use the same HTML document without having to modify it for a particular type of
computer, which was something unheard of at the time. Programs written in C or C++ are
machine dependent and cannot run on a different machine unless the program is recompiled.
The success of the Internet gave renewed focus to developing a machine-independent
programming language. And the same year the Internet was commercialized, five technologists
at Sun Microsystems set out to do just that. James Gosling, Patrick Naughton , ChrisWarth, Ed
Frank, and Mike Sheridan spent 18 months developing the programming language they called
Oak, which was renamed Java when this new language made its debut in 1995. Java went
through numerous iterations between 1991 and 1995, during which time many other
technologists at Sun made substantial contributions to the language.
Although Java is closely associated with the Internet, it was developed as a language
for programming software that could be embedded into electronic devices regardless of the type
of CPU used by the device. This is known as the Embedded Java platform and is in continuous
use today for closed systems.
JAVA VIRTUAL MACHINE
Writing Java programs is similar to writing C++ programs in that the programmer writes source
code that contains instructions into an editor, or in an integrated development environment, and
then the source code is compiled. However, that’s where Java and C++ part ways. The compiling
and linking process of a C++ program results in an executable that can be run on an appropriate
machine. In contrast, the Java compiler converts Java source code into bytecode that is executed
by the Java Virtual Machine (JVM). Machine-specific instructions are not included in bytecode.
Instead, they already reside in the JVM, which is machine specific. This means that the bytecode
might contain fewer instructions that need to be translated than a comparable C++ program.
Although the Java compiler generates bytecode that must be interpreted by the JVM at run time,
the number of instructions that need translation are usually minimal and have already been
optimized by the Java compiler.
OVERVIEW OF CLASSES AND OBJECTS
Java is strictly an objected-oriented programming language. All the Java code
that you write will appear in either a class or an interface. When you write a program using an
object-oriented programming language, you design your program around the objects in the
problem being solved. For each object, a class is written to describe the object’s attributes and
behaviors.
By definition, a class is a description of an object. Similarly, an object is
defined to be an instance of a class. An object consists of attributes and behaviors.
An attribute is a feature of the object, something the object “has.” A behavior is something the
object “does.”
CONSTRUCTORS
A constructor is a special method in a class that is invoked when the object gets
instantiated. The purpose of a constructor is to allow the fields of the object to
be initialized when the object is instantiated.
Remember that when an object is instantiated using the new keyword, the
memory is allocated and zeroed out. Therefore, the initial values of the fields
of an object are zero values Without a constructor, you have to go in and initialize all the fields
so that the object has meaningful data. A constructor provides an opportunity to construct the
object so that its fields have meaningful data while
the object is being instantiated.
What makes a constructor different from a method is that a constructor satisfies
the following two properties:
■ The name of the constructor must match the name of the class.
■ A constructor does not declare a return value, not even void.
OVERVIEW OF INHERITANCE
In object-oriented programming (OOP), a new class can be built upon an existing
class with the new class extending the existing class and inheriting its
attributes and behaviors. Extending a class is called inheritance.
The existing class is referred to as the parent class, and the new class is
referred to as the child class
THE ACCESS SPECIFIERS
Every member of a class (that is, the fields, methods, and constructors) has an
access specifier that determines who has access to the member. Access specifiers
allow the design of your programs to take into account who should be accessing
the various attributes and behaviors of an object.
For example, you might want to add a method to your class that performs
repetitive tasks and that is only invoked by the other methods in the class. You
can declare this method private, thereby hiding the method from anyone outside
the class.
Java provides four levels of access for members of a class:
Public access. Granted using the public keyword, public access is often
referred to as universal access because public members are accessible to
any other object.
Private access. Granted using the private keyword, private is the most
restrictive of the four access specifiers. A private member cannot be
accessed outside of the class.
Protected access. Granted using the protected keyword, a protected
member is accessible to any other class in the same package and also
child classes, no matter which package the child class is in.
Default access. Also referred to as package access, you grant default
access by not using any of the other three access specifiers. (There is
no keyword used to grant the default access.) A member with default
access is accessible to any other classes in the same package
OVERVIEW OF POLYMORPHISM
When we discussed inheritance, I explained how the is a relationship is used to
determine if your inheritance is a good design. The is a relationship is also helpful
when learning polymorphism. Polymorphism is the term used to describe
how an object can take on many forms. An object takes on many forms because
an object can be treated as a child type, a parent type, a grandparent type, and
so on up the hierarchy tree.
The term polymorphism is a combination of poly, meaning many or
multiple, and morph, meaning shapes or forms. Polymorphism in OOP
refers to the ability of an object to have many forms, which is a direct
result of inheritance.
A child object being treated as a parent class type has the following benefits:
■ Using a parent class reference to a child object.
■ Using polymorphic parameters and return values.
■ Creating heterogeneous collections of objects, where not all objects in
the collection are of the same type.
OVERVIEW OF ABSTRACTION
Abstraction refers to the ability to make a class abstract in OOP. An abstract
class is one that cannot be instantiated. All other functionality of the class still
exists, and its fields, methods, and constructors are all accessed in the same
manner. You just cannot create an instance of the class. it? In most situations,
the design of the class is such that no one would want an instance of the class.
OVERVIEW OF INTERFACES
An interface is a collection of abstract methods. Aclass implements an interface,
thereby inheriting the abstract methods of the interface. Unless the class that
implements the interface is abstract, all the methods of the interface need to be
defined in the class. An interface is similar to a class in the following ways:
■ An interface can contain any number of methods.
■ An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
■ The bytecode of an interface appears in a .class file.
1. INTRODUCTION
1.1 Purpose of this Document
File splitter splits a particular file according to the needs of the user,number of splits varies
accordingly. The main objective of the project is to reduce the memory space complexities.
This includes a splitter application that splits any large file of any format into desired
number of parts.Compile the split,java file and on the command prompt enter java split
filename number. Where filename is the name of the file to be split and number is the
number of parts to be made of this file
1.2 Scope of the Development Project
Identifies the product to be developed by name and function, lists limitations (if any), highlights
distinct features, lists benefits as clearly and precisely as possible. This will provide the basis for
the brief description of your product.
The othet part of this application is the program join.java.Compile the code under join.java
and keep the class file at the destination machine\folder. Once the file is split into a number
of parts, collect all the parts move it to the destination machine\folder, make sure that
join.class is available in the same folder. Then run java join filename numberofparts.
1.4 Reference
Help was taken from a number of sources:
www.google.com
www.sun.java.com
www.altavista.com
www.howstuffworks
www.cplusplus.com
we also refered the book The Complete reference by Herbert Schildt.
1.5 Overview of Document
A lot of things are described starting from the importance of the splitter to its applications in
various fields.The use of SRS is not only confined to the fact that only the external features are
known to the user but he becomes aware of the procedure being followed in general,it is
necessary that the user is aware of whats happening in general rather than just knowing about the
outer description,he must be aware about the constraints being placed on the programme and the
limitations that can be faced by him in the course of time.
2. GENERAL DESCRIPTION
File splitter splits the given file into number of parts as per user requirement,the number of splits
and the size varies according to the user requirement.
The splits can also be joined using this particular application.
2.1 Overview of Functional Requirements
Provide a short description of the functions to be performed by the software, i.e. what the
product should do. The file splitter splits the file according the user requirements,the splitted file
can be regained to its original form using join function.
The file splitter function is used to split the file and the output is the number of splits.
2.2 Overview of Data Requirements
A general appears infront of the user asking for:
1. The filename.
2. Path where it exists.
3. Number of splits.
4. Size of the splits.
5. Another option appears either to split or join.
2.3 General Constraints, Assumptions, Dependencies, Guidelines
The project requires no web based application.
The project is not confined for persistent data.
Only sfl file can be joined(LIMITATION).
2.4 User View of Product Use
The user can reduce memory spacing complexities by using this file splitter
It is convienient for the user as it becomes less spacious.
A screen appears infront of the user containing the following information:
The filename.
Path where it exists.
Number of splits.
Size of the splits.
Another option appears either to split or join.
The user can input the data as per his requirement either to split or to join.
3. SPECIFIC REQUIREMENTS
The user must have the knowledge about java programming.
3.3 Performance Requirement
The project is quite reliable in terms of security basis, in general several users can access it and
can carry on the proceedings .
3.4 Quality Attributes
Security issues are the main concern for any project,it is necessary the security issue does not
create any problem in any ways. The project file splitter ensures that security is the main
concern and quality is maintained.
3.5 Requirements
Hardware Requirements
P3 or p4 processor
128 mb Ram.
20 gb hardisk
Free space
Software Requirements
Jdk1.3 or above
DATA FLOW DIAGRAM
The data flow diagrams are a complete pictorial representation of how the data flows between
processes. Essentially a data flow diagram gives us an idea of the internal working of the system.
A DFD should represent all external entities, processes, data flow, databases etc. The DFD for
the project we developed is given below and deals with all data flow and processes. In the DFD
we have produced the following are the specifications:
1. Square boxes represent external entities
2. Oval shaped figures show processes
3. Rhombus shaped boxes define database entries
4. Arrows represent dataflow and are direction specific
The data flow diagram for the project as shown in the following page deals with processes and
dataflow. Here the external entities being the user of the system, the processes the functions
define the DFD
CONTEXT DIAGRAM
Level 0 DFD
LITERATURE REVIEW
We all know the fact that files being used today take a lot of space and it adds to the complexities
of the user to certain extent. Memory spacing and facts regarding memory concerns are a vital
part of any programming strategy. It is important that the files take less space to add to the
convenience of the user. It took us a lot of pain and strategic thinking to get to an answer to this
question. File splitter the project we are into comes as an perfect answer to this question.What
this project is all about is something that helps to reduce the memory space of files. Under this
project a particular procedure is followed which is as follows:
File Splitter Instruction
To Split a File :
1. Enter or browse part of file to split
2. Enter or browse directory/folder where the splits will be saved
3. Enter the size of splits in bytes
4. Splits
To Join a File:
1. Enter or browse the file to be joined(has a.sfl extension name)
(joined file be saved in same folder)
2. Press join
SOURCE CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileSplitterFrame extends JFrame implements ActionListener, KeyListener {
private JButton btnBrowseFileDir, btnBrowseSplitDir, btnSplit, btnJoin, btnExit, btnHelp;
private JTextField txtFileDir, txtSplitDir, txtSplitSize, txtFileSize, txtNumSplits;
private JLabel lblFileSize, lblNumSplits, lblFileDir, lblSplitDir, lblSplitSize;
private final JFileChooser fc;
private final static String HELP_MSG = "File Splitter Instructions:\n\n"+
To Split A File:\n 1. Enter or browse path of file to split\n "+
"2. Enter or browse directory/folder where the splits will be saved\n "+
"3. Enter the size of the splits in bytes\n 4. Press Split\n\n"+
"To Join A File:\n 1. Enter or browse the file to be joined (has a .sfl extension name)\n "+
" (joined file will be saved in the same folder)\n 2. Press Join";
public FileSplitterFrame() {
super("File Splitter");
btnBrowseFileDir = new JButton("Browse");
btnBrowseSplitDir = new JButton("Browse");
btnSplit = new JButton("Split");
btnJoin = new JButton("Join");
btnExit = new JButton("Exit");
btnHelp = new JButton("Help");
txtFileDir = new JTextField();
txtSplitDir = new JTextField();
txtSplitSize = new JTextField();
txtFileSize = new JTextField();
txtNumSplits = new JTextField();
lblFileSize = new JLabel("Size of file:");
lblNumSplits = new JLabel("No. of splits:");
lblFileDir = new JLabel("File to split/join:");
lblSplitDir = new JLabel("Splits folder:");
lblSplitSize = new JLabel("Size of splits:");
fc = new JFileChooser();
txtSplitSize.addKeyListener(this);
txtFileDir.setPreferredSize(new Dimension(300, 28));
txtSplitDir.setPreferredSize(new Dimension(300, 28));
txtSplitSize.setPreferredSize(new Dimension(105, 28));
txtFileSize.setPreferredSize(new Dimension(300, 28));
txtNumSplits.setPreferredSize(new Dimension(300, 28));
btnSplit.setPreferredSize(new Dimension(78, 28));
btnJoin.setPreferredSize(new Dimension(78, 28));
btnExit.setPreferredSize(new Dimension(78, 28));
btnHelp.setPreferredSize(new Dimension(78, 28));
txtFileDir.setEditable(false);
txtSplitDir.setEditable(false);
txtFileSize.setEditable(false);
txtNumSplits.setEditable(false);
lblFileSize.setHorizontalAlignment(JLabel.RIGHT);
lblFileDir.setHorizontalAlignment(JLabel.RIGHT);
lblSplitDir.setHorizontalAlignment(JLabel.RIGHT);
lblSplitSize.setHorizontalAlignment(JLabel.RIGHT);
lblNumSplits.setHorizontalAlignment(JLabel.RIGHT);
txtFileSize.setBorder(BorderFactory.createEmptyBorder());
txtNumSplits.setBorder(BorderFactory.createEmptyBorder());
btnBrowseFileDir.addActionListener(this);
btnBrowseSplitDir.addActionListener(this);
btnSplit.addActionListener(this);
btnJoin.addActionListener(this);
btnHelp.addActionListener(this);
btnExit.addActionListener(this);
JPanel c = new JPanel();
c.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridwidth = 1;
gbc.fill = gbc.NONE;
gbc.anchor = gbc.EAST;
c.add(lblFileDir, gbc);
gbc.gridwidth = gbc.RELATIVE;
c.add(txtFileDir, gbc);
gbc.gridwidth = gbc.REMAINDER;
c.add(btnBrowseFileDir, gbc);
gbc.gridwidth = 1;
c.add(lblSplitDir, gbc);
gbc.gridwidth = gbc.RELATIVE;
c.add(txtSplitDir, gbc);
gbc.gridwidth = gbc.REMAINDER;
c.add(btnBrowseSplitDir, gbc);
gbc.gridwidth = 1;
c.add(lblSplitSize, gbc);
gbc.anchor = gbc.WEST;
gbc.gridwidth = gbc.REMAINDER;
c.add(txtSplitSize, gbc);
gbc.gridwidth = 1;
gbc.anchor = gbc.EAST;
c.add(lblFileSize, gbc);
gbc.anchor = gbc.WEST;
gbc.gridwidth = gbc.REMAINDER;
c.add(txtFileSize, gbc);
gbc.gridwidth = 1;
gbc.anchor = gbc.EAST;
c.add(lblNumSplits, gbc);
gbc.anchor = gbc.WEST;
gbc.gridwidth = gbc.REMAINDER;
c.add(txtNumSplits, gbc);
gbc.anchor = gbc.CENTER;
JPanel p = new JPanel();
p.add(btnSplit);
p.add(btnJoin);
p.add(btnHelp);
p.add(btnExit);
c.add(p, gbc);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(c);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
pack();
}
public void actionPerformed(ActionEvent evt) {
JButton src = (JButton)evt.getSource();
if (src == btnExit) {
dispose();
System.exit(0);
} else if (src == btnBrowseFileDir) {
// set directory of file chooser dialog to what is in txtFileDir
fc.setCurrentDirectory(new File(txtFileDir.getText()));
// show files and directories in file chooser
fc.setFileSelectionMode(fc.FILES_AND_DIRECTORIES);
int action = fc.showDialog(FileSplitterFrame.this, "Select");
if (action == fc.APPROVE_OPTION) {
String name = fc.getSelectedFile().getAbsolutePath();
txtFileDir.setText(name);
String path = fc.getCurrentDirectory().getPath();
txtSplitDir.setText(path);
txtFileSize.setText(fc.getSelectedFile().length()+" byte(s)");
txtSplitSize.setText("1");
computeNSplits();
computeNSplits();
}
} else if (src == btnBrowseSplitDir) {
// set directory of file chooser dialog to what is in txtSplitDir
fc.setCurrentDirectory(new File(txtSplitDir.getText()));
// show directories only in file chooser dialog
fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
int action = fc.showDialog(FileSplitterFrame.this, "Select");
if (action == fc.APPROVE_OPTION) {
String path = fc.getSelectedFile().getPath();
txtSplitDir.setText(path);
}
} else if (src == btnJoin) {
long before = System.currentTimeMillis();
long retval = Splitter.join(txtFileDir.getText());
long after = System.currentTimeMillis();
System.out.println("Time elapsed: "+((after-before)/1000L));
if (retval == -1) {
msgbox("File is invalid. Must be a SFL file.",
"Error", JOptionPane.ERROR_MESSAGE);
} else if (retval == -2) {
msgbox("One of the split files is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
msgbox("Join Process Done!", "Join",
JOptionPane.INFORMATION_MESSAGE);
}
} else if (src == btnSplit) {
String s = txtSplitSize.getText();
String f = txtFileDir.getText();
String d = txtSplitDir.getText();
long size = 0;
boolean problem = false;
try {
size = Long.parseLong(s);
if (size < 0L)
problem = true;
} catch (NumberFormatException nfx) {
problem = true;
}
if (problem) { // was split size valid?
msgbox("Invalid Split Size: "+s, "Error",
JOptionPane.ERROR_MESSAGE);
txtSplitSize.requestFocus();
txtSplitSize.selectAll();
return; // exit this method
}
int retval = Splitter.split(f, d, size);
if (retval == -1) {
msgbox("File/Directory does not exist/is invalid.",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
msgbox("Split Process Done! Make sure not to lose"+
" any of the files!", "Split",
JOptionPane.INFORMATION_MESSAGE);
}
} else if (src == btnHelp) {
msgbox(HELP_MSG, "Help", JOptionPane.INFORMATION_MESSAGE);
}
}
public void keyPressed(KeyEvent e) {computeNSplits();}
public void keyReleased(KeyEvent e) {computeNSplits();}
public void keyTyped(KeyEvent e) { }
private void computeNSplits() {
File f = fc.getSelectedFile();
if (f != null) {
long fileSize = f.length();
long splitSize = 0L;
try {
System.out.println(splitSize);
splitSize = Long.valueOf(txtSplitSize.getText()).longValue();
} catch (NumberFormatException nfx) { splitSize = 1L; }
txtNumSplits.setText(Splitter.computeNSplits(fileSize, splitSize)+"");
}
}
public void msgbox(String msg, String title, int msgtype) {
JOptionPane.showMessageDialog(FileSplitterFrame.this, msg, title,
msgtype);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
new FileSplitterFrame().setVisible(true);
}
}
import java.io.*;
public class Splitter {
// buffer size
private static final int BUF_SIZE = 2048;
// buffer - where bytes from read operations will be stored
private static byte[] buffer = new byte[BUF_SIZE];
public static long computeNSplits(long fileSize, long splitSize) {
long nsplits = (long)Math.ceil((double)fileSize/splitSize);
return nsplits;
}
public static int split(String file, String dir, long splitSize) {
File f = new File(file);
File d = new File(dir);
// make sure file is a file and directory/folder is a
// directory/folder and both exists
if (!f.isFile() || !d.isDirectory())
return -1;
RandomAccessFile in = null, out = null, zro = null;
File f0, fn;
long fileSize = f.length();
// compute number of split files produced
int nSplits = (int)computeNSplits(fileSize, splitSize);
long acc = 0; // counts how many bytes have been written
int ctr = 1; // file counter
int n = (nSplits+"").length();
String s0 = null;
System.out.println(dir+" "+f.getName());
if (dir.endsWith(File.separator))
s0 = dir+f.getName();
else
s0 = dir+File.separator+f.getName();
System.out.println(s0);
f0 = new File(s0+".sfl");
try {
// create file (.sfl) containing list of split files
f0.createNewFile();
// open file for writing
zro = new RandomAccessFile(f0, "rw");
// open source file (to be split) for reading
in = new RandomAccessFile(f, "r");
// write source file's filename to .sfl file
zro.writeUTF(s0);
// write the source file's size
zro.writeLong(fileSize);
long bytesLeft = 0, // bytes left in buffer from last read
bytesRead = 0, // bytes from last read to buffer
offset, // index in buffer where writing start's from
len, // bytes to be written to a file
bytesToGo, // bytes left to be written to split file
bytesWritten; // counts bytes written to split file
while (acc < fileSize) {
// create a file with a numbered extension name
// number depends on ctr variable
String filename = s0+"."+padLeft(ctr+"", '0', n);
// open this file
out = new RandomAccessFile(filename, "rws");
// write the name of this file to .sfl file
zro.writeUTF(filename);
bytesWritten = 0;
while (bytesWritten < splitSize && acc < fileSize) {
if (bytesLeft <= 0) {
bytesRead = in.read(buffer);
bytesLeft = bytesRead;
offset = 0;
} else {
offset = bytesRead - bytesLeft;
}
bytesToGo = splitSize - bytesWritten;
if (bytesToGo > bytesLeft)
len = bytesLeft;
else
len = bytesToGo;
out.write(buffer, (int)offset, (int)len);
bytesLeft -= len;
bytesWritten += len;
acc += len;
}
// write the size of the split file
zro.writeLong(bytesWritten);
// close newly created file
out.close();
// increment file counter
ctr++;
}
} catch (IOException iox) {
iox.printStackTrace();
} finally { // makes sure to do the ff:
try {
// close source file (the file to be split)
if (in != null)
in.close();
// close .sfl file
if (zro != null)
zro.close();
// close last split file opened
if (out != null)
out.close();
} catch (IOException iox) {
iox.printStackTrace();
}
}
// return how many files made
return ctr;
}
public static long join(String src) {
File f = new File(src);
// did user enter a filename not a folder name or drive?
if (!f.isFile())
return -1;
// does the file end with .sfl
String name = f.getPath();
int idx = name.lastIndexOf(".");
String extname = name.substring(idx);
System.out.println(extname);
if (!extname.equalsIgnoreCase(".sfl"))
return -1; // has no .sfl extension name
RandomAccessFile zro = null, fn = null, out = null;
File temp = null, orig = null;
long fsctr = 0; // file size counter
long fileSize = 0;
try {
zro = new RandomAccessFile(f, "r");
// read the original filename of the split-ed files
String fname = zro.readUTF();
System.out.println("Filename: "+fname);
// read the original file's size
fileSize = zro.readLong();
System.out.println("size: "+fileSize);
// compare this filename to filename supplied to join()
// without the sfl extension name
String f0 = name.substring(0, idx);
System.out.println("f0 = "+f0);
if (!f0.equals(fname))
return -1; // invalid .sfl file
// create File object for original file
orig = new File(fname);
// create and open temporary file
String tmpname = src.substring(0, src.indexOf(File.separator)+1)+"split"+((int)
(Math.random()*99999))+".tmp";
// System.out.println(tmpname);
temp = new File(tmpname);
temp.createNewFile();
out = new RandomAccessFile(temp, "rw");
// read a filename of split file
fname = zro.readUTF();
while (fsctr < fileSize) {
// read split file's size
long fsize = zro.readLong();
// check if file exists
File file = new File(fname);
if (!file.exists()) {
out.close(); // close temporary file
temp.delete(); // delete temporary file
return -2; // missing file
}
// open file
fn = new RandomAccessFile(file, "r");
long i = 0;
int bytesRead = 0;
while (i < fsize) {
// read from split file file
bytesRead = fn.read(buffer);
// write byte to original file
// start constructing original file
out.write(buffer, 0, bytesRead);
// count bytes written to this file
fsctr+=bytesRead;
// count total bytes read from split file
i+=bytesRead;
}
// close this split file
fn.close();
// see if we've completely constructed the file
if (fsctr == fileSize)
break; // jump out off this loop
// read another split file filename
fname = zro.readUTF();
}
} catch (IOException iox) {
iox.printStackTrace();
} catch (Exception x) {
x.printStackTrace();
} finally { // make sure they're closed
try {
if (fn != null) fn.close();
// close zero file
if (zro != null) zro.close();
// close original file
if (out != null) out.close();
} catch (IOException iox) {
iox.printStackTrace();
}
}
// rename temporary file and rename to original file
temp.renameTo(orig);
return fsctr; // return file size
}
// pads a String with a character on its leftside
private static String padLeft(String s, char pad, int len) {
if (s.length() >= len)
return s;
StringBuffer ns = new StringBuffer(s);
while (ns.length() < len)
ns.insert(0, pad);return ns.toString()
OUTPUTS
CONCLUSION
This particular project that is “FILE SPLITTER” is of great use in general and will help reduce
the space complexities being faced by the users. Program complexities being faced by developers
today are main concern because huge files which in general take a lot amount of space add to
different problems in general and today time allotment is the main concern for the development
of any kind of project. It is necessary that less space is occupied and the work is done in short
span of time.
File splitter follows a simple and practical approach for removing this flaw, an input given in any
form with is compatible with the platform being used that is java can be given and the user is
asked how many splits are to be made n in response the splits are made which can be joined in
courde of time.
Nowadays its use can be seen in many forms in general. The applications of FILE SPLIITER are
vast and hence worth.
REFERENCES :
www.google.co.in
www.altavista.com
www.howstuffworks.com
http://www.cplusplus.com
Complete refrence for java programming.
BIBLIOGRAPHY
JAVA:
THE COMPLETE REFERENCE
Writer: Mr. Herbert Schildt
JAVA How to program?
Writer: DEITEL
JAVA NETWORKING FUNDAMENTALS