This example shows how to read objects that has been serialized to a file with an ObjectOutputStream.
We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.
The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached.
One could as well write 'while (true)' but as that is not good practice we won't do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop.
What this code example does instead is to catch the EOFException and just print out that the end of file is reached.
The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectInputStream class
*/
public void readPersons(String filename) {
ObjectInputStream inputStream = null;
try {
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new FileInputStream(filename));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Person) {
System.out.println(((Person)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().readPersons("myFile.txt");
}
}
The output from the code above looks like this:
James
Ryan
19
Obi-wan
Kenobi
30
End of file reached.
Wednesday, May 27, 2009
Writing objects to file with ObjectOutputStream
You can use the ObjectOutputStream class to write objects to an underlying stream.
In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor.
The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface.
Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.
This is what the Person class looks like:
import java.io.Serializable;
/**
*
* @author chintan patel
*/
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
/**
* Creates a new instance of Person
*/
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
}
----------------------------------------------------------------------------------
This is the code for creating instances of the Person class and writing them to an ObjectOuputStream:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectOutputStream class
*/
public void writePersons(String filename) {
ObjectOutputStream outputStream = null;
try {
//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
outputStream.writeObject(person);
person = new Person();
person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);
outputStream.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writePersons("myFile.txt");
}
}
In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor.
The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface.
Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.
This is what the Person class looks like:
import java.io.Serializable;
/**
*
* @author chintan patel
*/
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
/**
* Creates a new instance of Person
*/
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
}
----------------------------------------------------------------------------------
This is the code for creating instances of the Person class and writing them to an ObjectOuputStream:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectOutputStream class
*/
public void writePersons(String filename) {
ObjectOutputStream outputStream = null;
try {
//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
outputStream.writeObject(person);
person = new Person();
person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);
outputStream.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writePersons("myFile.txt");
}
}
List file structure within folder or hard drive
This code example lists the files and folders and also the content in all subfolders.
With recursive calls the file/directory tree can be listed with
a relatively small amount of code.
The purpose of the getTabs method and the variable tabCounter is only to
make the output more viewable with indenting for each level.
import java.io.File;
public class FileStructure {
int tabCounter = 0;
public void listFilesAndFolders(String folder) {
File file = new File(folder);
if (!file.exists() !file.isDirectory()) {
System.out.println("Parameter is not a directory");
System.exit(1);
}
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
System.out.println(getTabs() + "- " + fileArray[i].getName());
tabCounter++;
listFilesAndFolders(fileArray[i].getAbsolutePath());
}
else {
System.out.println(getTabs() + fileArray[i].getName());
}
}
tabCounter--;
}
private String getTabs() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < tabCounter; i++)
buffer.append("\t");
return buffer.toString();
}
public static void main(String[] args) {
FileStructure fileStructure = new FileStructure();
fileStructure.listFilesAndFolders("C:\\temp");
}
}
With recursive calls the file/directory tree can be listed with
a relatively small amount of code.
The purpose of the getTabs method and the variable tabCounter is only to
make the output more viewable with indenting for each level.
import java.io.File;
public class FileStructure {
int tabCounter = 0;
public void listFilesAndFolders(String folder) {
File file = new File(folder);
if (!file.exists() !file.isDirectory()) {
System.out.println("Parameter is not a directory");
System.exit(1);
}
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
System.out.println(getTabs() + "- " + fileArray[i].getName());
tabCounter++;
listFilesAndFolders(fileArray[i].getAbsolutePath());
}
else {
System.out.println(getTabs() + fileArray[i].getName());
}
}
tabCounter--;
}
private String getTabs() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < tabCounter; i++)
buffer.append("\t");
return buffer.toString();
}
public static void main(String[] args) {
FileStructure fileStructure = new FileStructure();
fileStructure.listFilesAndFolders("C:\\temp");
}
}
Create a temporary file
Sometimes it come in handy to create a temporary file.
Here we create a temporary file with the prefix "temp_" as shown by the first parameter.
The second parameter is an optional suffix, if it\'s null as in the example, .tmp will be
used by default.
Optionally a third parameter can be defined pointing out the directory in which the file will
be created. If not specified (as below), the default temporary directory will be used.
import java.io.File;
import java.io.IOException;
public class FileUtil {
public void createTemporaryFile(String filename) {
try {
//Create the temp file
File f = File.createTempFile("temp_", null);
//Check where the default temp dir is located
System.out.println(f.getAbsolutePath());
//Delete the file when the program exists
f.deleteOnExit();
//Place any processing of the file here
// ...
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.createTemporaryFile("myfile.txt");
}
}
Here we create a temporary file with the prefix "temp_" as shown by the first parameter.
The second parameter is an optional suffix, if it\'s null as in the example, .tmp will be
used by default.
Optionally a third parameter can be defined pointing out the directory in which the file will
be created. If not specified (as below), the default temporary directory will be used.
import java.io.File;
import java.io.IOException;
public class FileUtil {
public void createTemporaryFile(String filename) {
try {
//Create the temp file
File f = File.createTempFile("temp_", null);
//Check where the default temp dir is located
System.out.println(f.getAbsolutePath());
//Delete the file when the program exists
f.deleteOnExit();
//Place any processing of the file here
// ...
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.createTemporaryFile("myfile.txt");
}
}
Read each line in a comma separated file into an array
In this example we read the lines of a comma separated file and split the values into an array.
This is done fairly easy with the split() method, which takes a separator as an argument and returns
an array of Strings.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CsvTest {
public void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("thefile.csv"));
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//Do necessary work with the values, here we just print them out
for (String str : values) {
System.out.println(str);
}
System.out.println();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
CsvTest test = new CsvTest();
test.readFile();
}
}
This is done fairly easy with the split() method, which takes a separator as an argument and returns
an array of Strings.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CsvTest {
public void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("thefile.csv"));
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//Do necessary work with the values, here we just print them out
for (String str : values) {
System.out.println(str);
}
System.out.println();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
CsvTest test = new CsvTest();
test.readFile();
}
}
List files of a certain type
To list files of a certain type, create an instance of the FileFilter
class and override it\'s accept method. Use that instance when calling
the list method of the File class.
import java.io.File;
import java.io.FilenameFilter;
public class FileUtil {
public void listFiles(String dir) {
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};
String[] filenames = directory.list(filefilter);
for (String name : filenames) {
System.out.println(name);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listFiles("C:\\\\temp");
}
}
class and override it\'s accept method. Use that instance when calling
the list method of the File class.
import java.io.File;
import java.io.FilenameFilter;
public class FileUtil {
public void listFiles(String dir) {
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};
String[] filenames = directory.list(filefilter);
for (String name : filenames) {
System.out.println(name);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listFiles("C:\\\\temp");
}
}
Remove a line from a text file
This example shows how to delete a line from a file.
The method removeLineFromFile takes two parameters, the first parameter is the file to remove from and the second parameter is the content of the line to remove.
A tempfile is created and written to, except for the content that matches the second parameter.
This way very large files can be handled without demanding so much internal memory.
The original file is then deleted and the tempfile is renamed to the original filename.
For example, the file test.txt is located in the current directory and contains three lines, and we will remove the second line "bbbbb".
aaaaa
bbbbb
ccccc
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
The file test.txt now looks like this:
aaaaa
ccccc
The method removeLineFromFile takes two parameters, the first parameter is the file to remove from and the second parameter is the content of the line to remove.
A tempfile is created and written to, except for the content that matches the second parameter.
This way very large files can be handled without demanding so much internal memory.
The original file is then deleted and the tempfile is renamed to the original filename.
For example, the file test.txt is located in the current directory and contains three lines, and we will remove the second line "bbbbb".
aaaaa
bbbbb
ccccc
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
The file test.txt now looks like this:
aaaaa
ccccc
How to create a zip file
This code example shows how to create a zip file.
What we do is to create an input stream from the file we want to compress, and while we read from it we write the contents to an output stream.
This output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
Next we have to add a zip entry to the output stream before we start writing to it.
We will also clean up by closing the zip entry and both the input stream and output stream when we are done.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Creates a zip file
*/
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().createZipFile();
}
}
What we do is to create an input stream from the file we want to compress, and while we read from it we write the contents to an output stream.
This output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
Next we have to add a zip entry to the output stream before we start writing to it.
We will also clean up by closing the zip entry and both the input stream and output stream when we are done.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Creates a zip file
*/
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().createZipFile();
}
}
How to list the contents of a zip file
To list the contents of a zip file you need to get the entries of the file since every file in a zip file is represented by an entry.
In this case we assume that the filename of the zip file is 'testfile.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file.
Note that we have to cast each element in the Enumeration to a ZipEntry.
Normally some more extensive processing of the entries would probably be done, but here we just print out the name of each entry (i.e the name of the file or directory in the zip file).
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author chintan patel
*/
public class Main {
public void listContentsOfZipFile() {
try {
ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().listContentsOfZipFile();
}
}
In this case we assume that the filename of the zip file is 'testfile.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file.
Note that we have to cast each element in the Enumeration to a ZipEntry.
Normally some more extensive processing of the entries would probably be done, but here we just print out the name of each entry (i.e the name of the file or directory in the zip file).
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author chintan patel
*/
public class Main {
public void listContentsOfZipFile() {
try {
ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().listContentsOfZipFile();
}
}
Extract contents of a zip file
This example shows how to extract a zipfile containing one file (or entry).
The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'.
We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Extracts a zip file
*/
public void extractZipFile() {
try {
String zipFileName = "compressed.zip";
String extractedFileName = "extracted.txt";
//Create input and output streams
ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
OutputStream outStream = new FileOutputStream(extractedFileName);
ZipEntry entry;
byte[] buffer = new byte[1024];
int nrBytesRead;
//Get next zip entry and start reading data
if ((entry = inStream.getNextEntry()) != null) {
while ((nrBytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, nrBytesRead);
}
}
//Finish off by closing the streams
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().extractZipFile();
}
}
The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'.
We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Extracts a zip file
*/
public void extractZipFile() {
try {
String zipFileName = "compressed.zip";
String extractedFileName = "extracted.txt";
//Create input and output streams
ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
OutputStream outStream = new FileOutputStream(extractedFileName);
ZipEntry entry;
byte[] buffer = new byte[1024];
int nrBytesRead;
//Get next zip entry and start reading data
if ((entry = inStream.getNextEntry()) != null) {
while ((nrBytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, nrBytesRead);
}
}
//Finish off by closing the streams
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().extractZipFile();
}
}
Subscribe to:
Posts (Atom)
