Вы находитесь на странице: 1из 60

Java I/O Tutorial

Table des matires


Java I/O Tutorial........................................................................................................ 6
1

File................................................................................................................... 6
1.1

How to create a file in Java........................................................................6

1.2

How to construct a file path in Java...........................................................6

1.2.1

File.separator....................................................................................... 7

1.2.2

new File()............................................................................................. 8

1.2.3

Manual file separator...........................................................................8

1.3

How to set the file permission in Java........................................................9

1.3.1

File permission example....................................................................10

1.4

How to read file in Java BufferedInputStream........................................11

1.5

How to read file in Java BufferedReader................................................12

1.6

How to write to file in Java FileOutputStream........................................13

1.7

How to write to file in Java BufferedWriter............................................14

1.8

How to append content to file in Java......................................................15

1.8.1

Append file example..........................................................................15

1.8.2

Result................................................................................................ 16

1.9

How to delete file in Java.........................................................................16

1.9.1

Example............................................................................................ 16

1.10 How to delete files with certain extension only.......................................17


1.11 How to find files with certain extension only...........................................18
1.12 How to rename file in Java.......................................................................19
1.12.1 File.renameTo() Example...................................................................19
1.13 How to copy file in Java............................................................................19
1.13.1 File copy example.............................................................................. 20
1.14 How to move file to another directory in Java..........................................21
1.14.1 File.renameTo().................................................................................. 21
1.14.2 Copy and Delete................................................................................ 21
1.15 How to get the file creation date in Java..................................................22
1.15.1 How it work........................................................................................ 22
1.15.2 Example............................................................................................ 22
1.15.3 Result................................................................................................ 23
1.16 How to get the file last modified date in Java..........................................23
1.16.1 File Last Modified............................................................................... 24

1.16.2 Result................................................................................................ 24
1.17 How to change the file last modified date in Java....................................24
1.17.1 Result................................................................................................ 25
1.18 How to make a file read only in Java........................................................25
1.18.1 Example............................................................................................ 25
1.18.2 Output............................................................................................... 25
1.19 How to get file size in Java.......................................................................26
1.19.1 Example............................................................................................ 26
1.19.2 Result................................................................................................ 26
1.20 How to get the filepath of a file in Java....................................................27
1.20.1 Get file path example........................................................................27
1.20.2 Result................................................................................................ 27
1.21 How to get the total number of lines of a file in Java...............................28
1.21.1 Example............................................................................................ 28
1.21.2 Result................................................................................................ 29
1.22 How to check if a file exists in Java..........................................................29
1.23 How to check if a file is hidden in Java.....................................................29
1.24 How to read UTF-8 encoded data from a file Java.................................30
1.24.1 Result................................................................................................ 31
1.25 How to write UTF-8 encoded data into a file Java..................................31
1.25.1 Result................................................................................................ 32
1.26 How to assign file content into a variable in Java....................................32
1.26.1 Example............................................................................................ 32
1.26.2 Output............................................................................................... 33
1.27 How to generate a file checksum value in Java.......................................33
1.27.1 Result................................................................................................ 34
1.28 How to convert File into an array of bytes...............................................34
1.29 How to convert array of bytes into File....................................................35
1.30 How to convert String to InputStream in Java..........................................35
1.31 How to convert InputStream to String in Java..........................................36
1.32 How to convert File to Hex in Java...........................................................37
1.32.1 Example............................................................................................ 37
1.32.2 Demo................................................................................................. 38
1.33 How to get free disk space in Java...........................................................39
1.33.1 Example............................................................................................ 39

1.33.2 Output............................................................................................... 39
2

File Serialization............................................................................................. 40
2.1

How to write an Object to file in Java.......................................................40

2.1.1

Address.java...................................................................................... 40

2.1.2

Serializer.java.................................................................................... 41

2.2

How to read an Object from file in Java....................................................41

2.2.1
3

File Compression............................................................................................ 42
3.1

How to compress files in ZIP format........................................................42

3.1.1

Simple ZIP example...........................................................................43

3.1.2

Advance ZIP example Recursively..................................................43

3.2

How to decompress files from a ZIP file...................................................45

3.2.1
3.3
3.4

GZIP Example.................................................................................... 49

How to decompress serialized object from a Gzip file..............................50

3.6.1

GZIP example.................................................................................... 50

3.6.2

Output............................................................................................... 51

Temporary File................................................................................................ 51
4.1

How to create temporary file in Java........................................................51

4.1.1

Example............................................................................................ 51

4.1.2

Result................................................................................................ 52

4.2

How to write data to temporary file in Java.............................................52

4.2.1
4.3
4.4

Example............................................................................................ 52

How to delete temporary file in Java........................................................53

4.3.1

Gzip example..................................................................................... 48

How to compress serialized object into file..............................................49

3.5.1
3.6

GZip example.................................................................................... 47

How to decompress file from GZIP file.....................................................48

3.4.1
3.5

Decompress ZIP file example............................................................45

How to compress a file in GZIP format.....................................................47

3.3.1

Deserializer.java................................................................................ 42

Example............................................................................................ 53

How to get the temporary file path in Java..............................................53

4.4.1

Example............................................................................................ 53

4.4.2

Result................................................................................................ 54

Directory........................................................................................................ 54
5.1

How to create directory in Java................................................................54

5.1.1
5.2

How to delete directory in Java................................................................55

5.2.1

Directory recursive delete example...................................................55

5.2.2

Result................................................................................................ 57

5.3

How to copy directory in Java..................................................................57

5.3.1

Example............................................................................................ 57

5.3.2

Result................................................................................................ 59

5.4

How to traverse a directory structure in Java...........................................59

5.4.1

Example............................................................................................ 59

5.4.2

Output............................................................................................... 59

5.5

How to check if directory is empty in Java...............................................60

5.5.1
5.6

Example............................................................................................ 60

How to get the current working directory in Java.....................................60

5.6.1
6

Example............................................................................................ 55

Example............................................................................................ 60

Console IO...................................................................................................... 61
6.1

How to get the standard input in Java......................................................61

Java I/O Tutorial


Java comes with many handy I/O classes to support the input and output through bytes stream
and file system. Heres a list of the Java I/O examples including file, temporary file and
directory manipulation, encoding, serialized and also compression with zip or Gzip.
1

File

List of the File examples to show the use of Java I/O to create, read, write, modify file and get
the files information.
1.1

How to create a file in Java

The File.createNewFile() method is used to create a file in Java, and return a boolean value :
true if the file is created successful; false if the file is already exists or the operation failed.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}

}
}

1.2

} catch (IOException e) {
e.printStackTrace();
}

How to construct a file path in Java

In this tutorial, we will show you three Java examples to construct a file path :
1. File.separator or System.getProperty(file.separator) (Recommended)
2. File file = new File(workingDir, filename); (Recommended)
3. Create the file separator manually. (Not recommend, just for fun)

1.2.1 File.separator

Classic Java example to construct a file path, using File.separator or


System.getProperty("file.separator"). Both will check the OS and returns the file
separator correctly, for example,
1. Windows = \
2. *nix or Mac = /
FilePathExample1.java
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class FilePathExample1 {
public static void main(String[] args) {
try {
String filename = "newFile.txt";
String workingDirectory = System.getProperty("user.dir");
//****************//
String absoluteFilePath = "";
//absoluteFilePath = workingDirectory +
System.getProperty("file.separator") + filename;
absoluteFilePath = workingDirectory + File.separator +
filename;
System.out.println("Final filepath : " + absoluteFilePath);
//****************//
File file = new File(absoluteFilePath);
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File is already existed!");
}

} catch (IOException e) {
e.printStackTrace();
}

Output
Final filepath :
/Users/mkyong/Documents/workspace/maven/fileUtils/newFile.txt
File is created!

1.2.2 new File()

Some developers are using new File() API to construct the file path.

FilePathExample2.java
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class FilePathExample2 {
public static void main(String[] args) {
try {
String filename = "newFile.txt";
String workingDirectory = System.getProperty("user.dir");
//****************//
File file = new File(workingDirectory, filename);
//****************//
System.out.println("Final filepath : " +
file.getAbsolutePath());
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File is already existed!");
}
} catch (IOException e) {
e.printStackTrace();
}
}

Output
Final filepath :
/Users/mkyong/Documents/workspace/maven/fileUtils/newFile.txt
File is created!

1.2.3 Manual file separator

Check the system OS and create file path manually, just for fun, not recommend.
FilePathExample3.java
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class FilePathExample3 {
public static void main(String[] args) {
try {
String filename = "testing.txt";
String workingDir = System.getProperty("user.dir");
String absoluteFilePath = "";
//****************//

String your_os =
System.getProperty("os.name").toLowerCase();
if (your_os.indexOf("win") >= 0) {
//if windows
absoluteFilePath = workingDir + "\\" + filename;
} else if (your_os.indexOf("nix") >= 0 ||
your_os.indexOf("nux") >= 0 ||
your_os.indexOf("mac") >= 0) {
//if unix or mac
absoluteFilePath = workingDir + "/" + filename;
}else{
//unknow os?
absoluteFilePath = workingDir + "/" + filename;
}
System.out.println("Final filepath : " + absoluteFilePath);
//****************//
File file = new File(absoluteFilePath);
if (file.createNewFile()) {
System.out.println("Done");
} else {
System.out.println("File already exists!");
}

} catch (IOException e) {
e.printStackTrace();
}

Output
Final filepath :
/Users/mkyong/Documents/workspace/maven/fileUtils/newFile.txt
File is created!

1.3

How to set the file permission in Java

In Java, file permissions are very OS specific: *nix , NTFS (windows) and FAT/FAT32, all
have different kind of file permissions. Java comes with some generic file permission to deal
with it.
Check if the file permission allow :
1. file.canExecute(); return true, file is executable; false is not.
2. file.canWrite(); return true, file is writable; false is not.

3. file.canRead(); return true, file is readable; false is not.

Set the file permission :


1. file.setExecutable(boolean); true, allow execute operations; false to
disallow it.
2. file.setReadable(boolean); true, allow read operations; false to disallow it.
3. file.setWritable(boolean); true, allow write operations; false to disallow it.

In *nix system, you may need to configure more specifies about file permission, e.g set a 777
permission for a file or directory, however, Java IO classes do not have ready method for it,
but you can use the following dirty workaround :
Runtime.getRuntime().exec("chmod 777 file");

1.3.1 File permission example


package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class FilePermissionExample
{
public static void main( String[] args )
{
try {
File file = new File("/mkyong/shellscript.sh");
if(file.exists()){
System.out.println("Is Execute allow : " +
file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
}
file.setExecutable(false);
file.setReadable(false);
file.setWritable(false);
System.out.println("Is Execute allow : " +
file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}

1.4

How to read file in Java BufferedInputStream

Here is another example to show how to read a file in Java with BufferedInputStream and
DataInputStream classes.
The readLine() from the type DataInputStream is deprecated. Sun officially
announced this method can not convert property from bytes to characters. Its
advised to use BufferedReader.

You may interest to read this How to read file from Java BufferedReader
package com.mkyong.io;
import
import
import
import
import

java.io.BufferedInputStream;
java.io.DataInputStream;
java.io.File;
java.io.FileInputStream;
java.io.IOException;

public class BufferedInputStreamExample {


public static void main(String[] args) {
File file = new File("C:\\testing.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {

fis = new FileInputStream(file);


bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}

}
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

1.5

How to read file in Java BufferedReader

In Java, there are many ways to read a file, here we show you how to use the simplest and
most common-used method BufferedReader.
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new
FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

See updated example in JDK 7, which use try-with-resources new feature to close file
automatically.
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("C:\\testing.txt")))
{
String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {


System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}

1.6

How to write to file in Java FileOutputStream

In Java, FileOutputStream is a bytes stream class thats used to handle raw binary data. To
write the data to file, you have to convert the data into bytes and save it to file. See below full
example.
package com.mkyong.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("c:/newfile.txt");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

An updated JDK7 example, using new try resource close method to handle file easily.
package com.mkyong.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");

}
}

1.7

} catch (IOException e) {
e.printStackTrace();
}

How to write to file in Java BufferedWriter

In Java, BufferedWriter is a character streams class to handle the character data. Unlike
bytes stream (convert data into bytes), you can just write the strings, arrays or characters data
directly to file.
package com.mkyong;
import
import
import
import

java.io.BufferedWriter;
java.io.File;
java.io.FileWriter;
java.io.IOException;

public class WriteToFileExample {


public static void main(String[] args) {
try {
String content = "This is the content to write into
file";
File file = new File("/users/mkyong/filename.txt");

// if file doesnt exists, then create it


if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new
FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");

}
}

1.8

} catch (IOException e) {
e.printStackTrace();
}

How to append content to file in Java

FileWritter, a character stream to write characters to file. By default, it will replace all the
existing content with new content, however, when you specified a true (boolean) value as the
second argument in FileWritter constructor, it will keep the existing content and append the
new content in the end of the file.
1. Replace all existing content with new content.
new FileWriter(file);

2. Keep the existing content and append the new content in the end of the file.
new FileWriter(file,true);

1.8.1 Append file example

A text file named javaio-appendfile.txt and contains the following content.


ABC Hello

Append new content with new FileWriter(file,true)


package com.mkyong.file;
import
import
import
import

java.io.File;
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;

public class AppendToFileExample


{
public static void main( String[] args )
{
try{
String data = " This content will append to the end of the
file";
File file =new File("javaio-appendfile.txt");
//if file doesnt exists, then create it
if(!file.exists()){

file.createNewFile();
}
//true = append file
FileWriter fileWritter = new
FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new
BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");

}catch(IOException e){
e.printStackTrace();
}

1.8.2 Result

Now, the text file javaio-appendfile.txt content is updated


ABC Hello This content will append to the end of the file

1.9

How to delete file in Java

No nonsense, just issue the File.delete() to delete a file, it will return a boolean value to
indicate the delete operation status; true if the file is deleted; false if failed.
1.9.1 Example

In this example, it will delete a log file named c:\\logfile20100131.log.


package com.mkyong.file;
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}

1.10 How to delete files with certain extension only

In Java, you can implements the FilenameFilter, override the accept(File dir, String name)
method, to perform the file filtering function.
In this example, we show you how to use FilenameFilter to list out all files that are end
with .txt extension in folder c:\\folder, and then delete it.
package com.mkyong.io;
import java.io.*;
public class FileChecker {
private static final String FILE_DIR = "c:\\folder";
private static final String FILE_TEXT_EXT = ".txt";
public static void main(String args[]) {
new FileChecker().deleteFile(FILE_DIR,FILE_TEXT_EXT);
}
public void deleteFile(String folder, String ext){
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
//list out all the file name with .txt extension
String[] list = dir.list(filter);
if (list.length == 0) return;
File fileDelete;
for (String file : list){
String temp = new StringBuffer(FILE_DIR)
.append(File.separator)
.append(file).toString();
fileDelete = new File(temp);
boolean isdeleted = fileDelete.delete();
System.out.println("file : " + temp + " is deleted : " +
isdeleted);
}
}
//inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}

}
}

public boolean accept(File dir, String name) {


return (name.endsWith(ext));
}

1.11 How to find files with certain extension only

A FilenameFilter example, it will only display files that use .jpg extension in folder
c:\\folder.
package com.mkyong.io;
import java.io.*;
public class FindCertainExtension {
private static final String FILE_DIR = "c:\\folder";
private static final String FILE_TEXT_EXT = ".jpg";
public static void main(String args[]) {
new FindCertainExtension().listFile(FILE_DIR,
FILE_TEXT_EXT);
}
public void listFile(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);

FILE_DIR);

if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " +
}

return;

// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new
StringBuffer(FILE_DIR).append(File.separator)
.append(file).toString();
System.out.println("file : " + temp);
}
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}

}
}

public boolean accept(File dir, String name) {


return (name.endsWith(ext));
}

1.12 How to rename file in Java

Java comes with renameTo() method to rename a file. However , this method is really
platform-dependent: you may successfully rename a file in *nix but failed in Windows. So,
the return value (true if the file rename successful, false if failed) should always be checked to
make sure the file is rename successful.
1.12.1

File.renameTo() Example

package com.mkyong.file;
import java.io.File;
public class RenameFileExample
{
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}

1.13 How to copy file in Java

Java didnt comes with any ready make file copy function, you have to manual create the file
copy process. To copy file, just convert the file into a bytes stream with FileInputStream and
write the bytes into another file with FileOutputStream.
The overall processes are quite simple, just do not understand why Java doesnt include this
method into the java.io.File class.
1.13.1

File copy example

Heres an example to copy a file named Afile.txt to another file named Bfile.txt. If the
Bfile.txt is exists, the existing content will be replace, else it will create with the content of
the Afile.txt.
package com.mkyong.file;
import
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;

public class CopyFileExample


{
public static void main(String[] args)
{
InputStream inStream = null;

OutputStream outStream = null;


try{
File afile =new File("Afile.txt");
File bfile =new File("Bfile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");

}
}

}catch(IOException e){
e.printStackTrace();
}

1.14 How to move file to another directory in Java

Java.io.File does not contains any ready make move file method, but you can workaround
with the following two alternatives :
1. File.renameTo().
2. Copy to new file and delete the original file.

In the below two examples, you move a file C:\\folderA\\Afile.txt from one directory to
another directory with the same file name C:\\folderB\\Afile.txt.
1.14.1

File.renameTo()

package com.mkyong.file;
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}

1.14.2

Copy and Delete

package com.mkyong.file;
import
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;

public class MoveFileExample


{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");

File bfile =new File("C:\\folderB\\Afile.txt");


inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");

}catch(IOException e){
e.printStackTrace();
}

1.15 How to get the file creation date in Java

There are no official way to get the file creation date in Java. However, you can use the
following workaround to get the file creation date in Windows platform.
1.15.1

How it work

In Windows command prompt, type the command to list the file creation date.
C:\>cmd /c dir c:\logfile.log /tc
Volume in drive C has no label.
Volume Serial Number is 0410-1EC3
Directory of c:\
31/05/2010

08:05
14 logfile.log
1 File(s)
14 bytes
0 Dir(s) 35,389,460,480 bytes free

The 31/05/2010 08:05 is what you need. The idea is use the Java
Runtime.getRuntime().exec to execute the above command, hold the output, and parse it
by lines until you get the date and time.
1.15.2

Example

In this example, it will get the creation date of file (c:\\logfile.log).


package com.mkyong.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.StringTokenizer;
public class GetFileCreationDateExample
{
public static void main(String[] args)
{
try{
Process proc =
Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log
/tc");
BufferedReader br =
new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String data ="";
//it's quite stupid but work
for(int i=0; i<6; i++){
data = br.readLine();
}
System.out.println("Extracted value : " + data);
//split by space
StringTokenizer st = new StringTokenizer(data);
String date = st.nextToken();//Get date
String time = st.nextToken();//Get time
System.out.println("Creation Date
System.out.println("Creation Time

: " + date);
: " + time);

}catch(IOException e){
e.printStackTrace();
}
}
}

1.15.3

Result

Extracted value : 31/05/2010


Creation Date : 31/05/2010
Creation Time : 08:05

08:05

14 logfile.log

1.16 How to get the file last modified date in Java

In Java, you can use the File.lastModified() to get the files last modified timestamps. This
method will returns the time in milliseconds (long value), you may to format it with
SimpleDateFormat to make it a human readable format.
1.16.1

File Last Modified

package com.mkyong.file;
import java.io.File;
import java.text.SimpleDateFormat;

public class GetFileLastModifiedExample


{
public static void main(String[] args)
{
File file = new File("c:\\logfile.log");
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("After Format : " +
sdf.format(file.lastModified()));
}
}

1.16.2

Result

Before Format : 1275265349422


After Format : 05/31/2010 08:22:29

1.17 How to change the file last modified date in Java

Heres an example to show the use of File.setLastModified() to change the files last
modified date. This method accept the new modified date in milliseconds (long type), some
data type conversion are required.
package com.mkyong.file;
import
import
import
import

java.io.File;
java.text.ParseException;
java.text.SimpleDateFormat;
java.util.Date;

public class ChangeFileLastModifiedExample


{
public static void main(String[] args)
{
try{
File file = new File("C:\\logfile.log");
//print the original last modified date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Last Modified Date : "
+ sdf.format(file.lastModified()));
//set this date
String newLastModified = "01/31/1998";
//need convert the above date to milliseconds in long value
Date newDate = sdf.parse(newLastModified);
file.setLastModified(newDate.getTime());
//print the latest last modified date
System.out.println("Lastest Last Modified Date : "
+ sdf.format(file.lastModified()));
}catch(ParseException e){
e.printStackTrace();

}
}

1.17.1

Result

Original Last Modified Date : 05/31/2010


Lastest Last Modified Date : 01/31/1998

1.18 How to make a file read only in Java

A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file
read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be
writable again.
1.18.1

Example

package com.mkyong;
import java.io.File;
import java.io.IOException;
public class FileReadAttribute
{
public static void main(String[] args) throws IOException
{
File file = new File("c:/file.txt");
//mark this file as read only, since jdk 1.2
file.setReadOnly();
if(file.canWrite()){
System.out.println("This file is writable");
}else{
System.out.println("This file is read only");
}
//revert the operation, mark this file as writable, since jdk 1.6
file.setWritable(true);
if(file.canWrite()){
System.out.println("This file is writable");
}else{
System.out.println("This file is read only");
}
}

1.18.2

Output

This file is read only


This file is writable

1.19 How to get file size in Java

In Java, you can use the File.length() method to get the file size in bytes.
1.19.1

Example

Get an image file (c:\\java_xml_logo.jpg) 14KB, and display the file size.

package com.mkyong.file;
import java.io.File;
public class FileSizeExample
{
public static void main(String[] args)
{
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double
double
double
double
double
double
double
double
double

bytes = file.length();
kilobytes = (bytes / 1024);
megabytes = (kilobytes / 1024);
gigabytes = (megabytes / 1024);
terabytes = (gigabytes / 1024);
petabytes = (terabytes / 1024);
exabytes = (petabytes / 1024);
zettabytes = (exabytes / 1024);
yottabytes = (zettabytes / 1024);

System.out.println("bytes : " + bytes);


System.out.println("kilobytes : " + kilobytes);
System.out.println("megabytes : " + megabytes);
System.out.println("gigabytes : " + gigabytes);
System.out.println("terabytes : " + terabytes);
System.out.println("petabytes : " + petabytes);
System.out.println("exabytes : " + exabytes);
System.out.println("zettabytes : " + zettabytes);
System.out.println("yottabytes : " + yottabytes);
}else{

System.out.println("File does not exists!");

}
}

1.19.2

Result

bytes : 13900.0
kilobytes : 13.57421875
megabytes : 0.013256072998046875
gigabytes : 1.2945383787155151E-5
terabytes : 1.2641976354643703E-8
petabytes : 1.234568003383174E-11
exabytes : 1.205632815803881E-14
zettabytes : 1.1773757966834775E-17
yottabytes : 1.1497810514487085E-20

1.20 How to get the filepath of a file in Java

The File.getAbsolutePath() will give you the full complete path name (filepath + filename)
of a file.
For example,
File file = File("C:\\abcfolder\\textfile.txt");
System.out.println("Path : " + file.getAbsolutePath());

It will display the full path : Path : C:\\abcfolder\\textfile.txt.

In most cases, you may just need to get the file path only C:\\abcfolder\\. With the help of
substring() and lastIndexOf() menthods, you can extract the file path easily :
File file = File("C:\\abcfolder\\textfile.txt");
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));

1.20.1

Get file path example

In this example, it create a temporary file, and print out the file path of it.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class AbsoluteFilePathExample
{
public static void main(String[] args)
{
try{
File temp = File.createTempFile("i-am-a-temp-file", ".tmp" );
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("File path : " + filePath);
}catch(IOException e){
e.printStackTrace();
}
}
}

1.20.2

Result

File path : C:\Users\mkyong\AppData\Local\Temp\i-am-a-temp-file69424.tmp


File path : C:\Users\mkyong\AppData\Local\Temp

1.21 How to get the total number of lines of a file in Java

The LineNumberReader class is a useful class to handle the lines of a file, you can loop the
LineNumberReader.readLine() method and accumulate it as the total number of lines. A
line is considered a line if it ends with a line feed (\n) or a carriage return (\r).
1.21.1

Example

A text file named c:\\ihave10lines.txt, contains 10 lines


Line
Line
Line
Line

1
2
3
4

Line
Line
Line
Line
Line
Line

5
6
7
8
9
10

Counts the line


package com.mkyong.file;
import
import
import
import

java.io.File;
java.io.FileReader;
java.io.IOException;
java.io.LineNumberReader;

public class LineNumberReaderExample


{
public static void main(String[] args)
{
try{
File file =new File("c:\\ihave10lines.txt");
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
linenumber++;
}
System.out.println("Total number of lines : " +
linenumber);
lnr.close();
}else{
}

System.out.println("File does not exists!");

}catch(IOException e){
e.printStackTrace();
}
}
}

1.21.2

Result

Total number of lines : 10

1.22 How to check if a file exists in Java

To determine whether a file is exist in your file system, use the Java IO File.exists().
package com.mkyong.io;

import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}

1.23 How to check if a file is hidden in Java

A Java program to demonstrate the use of java.io.File isHidden() to check if a file is hidden.
package com.mkyong;
import java.io.File;
import java.io.IOException;
public class FileHidden
{
public static void main(String[] args) throws IOException
{
File file = new File("c:/hidden-file.txt");
if(file.isHidden()){
System.out.println("This file is hidden");
}else{
System.out.println("This file is not hidden");
}
}

Note
The isHidden() method is system dependent, on UNIX platform, a file is
considered hidden if its name is begins with a dot symbol (.); On Microsoft
Windows platform, a file is considered to be hidden, if its marked as hidden in
the file properties.
1.24 How to read UTF-8 encoded data from a file Java

A text file with UTF-8 encoded data

P.S File is created by this article How to write UTF-8 encoded data into a file
Heres the example to demonstrate how to read UTF-8 encoded data from a file in Java
package com.mkyong;
import
import
import
import
import
import

java.io.BufferedReader;
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStreamReader;
java.io.UnsupportedEncodingException;

public class test {


public static void main(String[] args){
try {

File fileDir = new File("c:\\temp\\test.txt");


BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}

}
}

in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

1.24.1

Result

Website UTF-8
?? UTF-8
??????? UTF-8

Do not worry about the symbol ???, this is because my output console is not support the
UTF-8 data. The variable str is storing exactly same UTF-8 encoded data as showed in
the text file.
1.25 How to write UTF-8 encoded data into a file Java

Heres the Java example to demonstrate how to write UTF-8 encoded data into a text file
c:\\temp\\test.txt
P.S Symbol ?? is some UTF-8 data in Chinese and Japanese
package com.mkyong;
import
import
import
import
import
import
import

java.io.BufferedWriter;
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.OutputStreamWriter;
java.io.UnsupportedEncodingException;
java.io.Writer;

public class test {


public static void main(String[] args){
try {
File fileDir = new File("c:\\temp\\test.txt");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir), "UTF8"));
out.append("Website UTF-8").append("\r\n");
out.append("?? UTF-8").append("\r\n");
out.append("??????? UTF-8").append("\r\n");
out.flush();
out.close();

}
}

}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

1.25.1

Result

1.26 How to assign file content into a variable in Java

Most people will read the file content and assign to StringBuffer or String line by line. Heres
another trick that may interest you how to assign whole file content into a variable with one
Javas statement, try it :)
1.26.1

Example

In this example, you will use DataInputStreamto convert all the content into bytes, and
create a String variable with the converted bytes.
package com.mkyong.io;
import java.io.DataInputStream;
import java.io.FileInputStream;
public class App{
public static void main (String args[]) {
try{
DataInputStream dis =
new DataInputStream (
new FileInputStream ("c:\\logging.log"));
byte[] datainBytes = new byte[dis.available()];
dis.readFully(datainBytes);
dis.close();
String content = new String(datainBytes, 0,
datainBytes.length);
System.out.println(content);
}catch(Exception ex){
ex.printStackTrace();
}
}
}

1.26.2

Output

This will print out all the logging.log file content.

10:21:29,425
10:21:29,441
10:21:29,441
10:21:29,456
10:21:29,456
handling
............

INFO
INFO
INFO
INFO
INFO

Version:15 - Hibernate Annotations 3.3.0.GA


Environment:509 - Hibernate 3.2.3
Environment:542 - hibernate.properties not found
Environment:676 - Bytecode provider name : cglib
Environment:593 - using JDK 1.4 java.sql.Timestamp

1.27 How to generate a file checksum value in Java

Here is a simple example to demonstrate how to generate a file checksum value with SHA1 mechanism in Java.
import java.io.FileInputStream;
import java.security.MessageDigest;
public class TestCheckSum {
public static void main(String args[]) throws Exception {
String datafile = "c:\\INSTLOG.TXT";
MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(datafile);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100,
16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}

1.27.1

Result

Digest(in hex format):: bf35fa420d3e0f669e27b337062bf19f510480d4

The INSTLOG.TXT file has a bf35fa420d3e0f669e27b337062bf19f510480d4 SHA-1


checksum value.
For checksum value in MD5 format , you need to change the MessageDigest :
MessageDigest md = MessageDigest.getInstance("MD5");

1.28 How to convert File into an array of bytes

The Java.io.FileInputStream can used to convert a File object into an array of bytes. In this
example, you read a file from C:\\testing.txt, convert it into an array of bytes and print out
the content.
package com.mkyong.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileToArrayOfBytes
{
public static void main( String[] args )
{
FileInputStream fileInputStream=null;
File file = new File("C:\\testing.txt");
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++) {
System.out.print((char)bFile[i]);
}
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}

1.29 How to convert array of bytes into File

The Java.io.FileOutputStream can used to convert an array of bytes into a file. In this
example, you read a file from C:\\testing.txt, and convert it into an array of bytes, and
write it into another file C:\\testing2.txt.
package com.mkyong.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ArrayOfBytesToFile
{
public static void main( String[] args )
{
FileInputStream fileInputStream=null;
File file = new File("C:\\testing.txt");
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream("C:\\testing2.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}

1.30 How to convert String to InputStream in Java

A simple Java program to convert a String to InputStream, and use BufferedReader to read
and display the converted InputStream.
package com.mkyong;
import
import
import
import
import

java.io.BufferedReader;
java.io.ByteArrayInputStream;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;

public class StringToInputStreamExample {


public static void main(String[] args) throws IOException {
String str = "This is a String ~ GoGoGo";
// convert String into InputStream

InputStream is = new ByteArrayInputStream(str.getBytes());


// read it with BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}

1.31 How to convert InputStream to String in Java

In Java, you can use BufferedReader + InputStreamReader to convert InputStream to


String.
InputStreamToStringExample.java
package com.mkyong.core;
import
import
import
import
import

java.io.BufferedReader;
java.io.ByteArrayInputStream;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;

public class InputStreamToStringExample {


public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah
blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();

} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

Output
file content..blah blah
Done

1.32 How to convert File to Hex in Java

A simple Java program to demonstrate the use of String formatter(%02X ) to convert a


File into Hex value. The attached comments should be self-explanatory.
1.32.1

Example

package com.mkyong;
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStream;
java.io.PrintStream;

public class File2Hex


{
public static void convertToHex(PrintStream out, File file) throws
IOException {
InputStream is = new FileInputStream(file);
int bytesCounter =0;
int value = 0;
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
//convert to hex value with "X" formatter
sbHex.append(String.format("%02X ", value));
//If the chracater is not convertable, just print a dot symbol
"."

if (!Character.isISOControl(value)) {
sbText.append((char)value);
}else {
sbText.append(".");
}
//if 16 bytes are read, reset the counter,
//clear the StringBuilder for formatting purpose only.

if(bytesCounter==15){
sbResult.append(sbHex).append("
").append(sbText).append("\n");
sbHex.setLength(0);
sbText.setLength(0);
bytesCounter=0;
}else{
bytesCounter++;
}
}
//if still got content
if(bytesCounter!=0){
//add spaces more formatting purpose only
for(; bytesCounter<16; bytesCounter++){
//1 character 3 spaces
sbHex.append("
");
}
sbResult.append(sbHex).append("
").append(sbText).append("\n");
}
out.print(sbResult);
is.close();

public static void main(String[] args) throws IOException


{
//display output to console
convertToHex(System.out, new File("c:/file.txt"));
//write the output into a file
convertToHex(new PrintStream("c:/file.hex"), new
File("c:/file.txt"));
}
}

1.32.2

Demo

A File with some dummy content


ABCDEFG
12345678
!@#$%^&*()
Testing only

After processed by above class, will display the following Hex values :
41 42 43 44 45 46 47 0D 0A 31 32 33 34 35 36 37
38 0D 0A 21 40 23 24 25 5E 26 2A 28 29 0D 0A 54
65 73 74 69 6E 67 20 6F 6E 6C 79

ABCDEFG..1234567
8..!@#$%^&*()..T
esting only

1.33 How to get free disk space in Java

In Java old days, it lacks of method to determine the free disk space on a partition. But this is
changed since JDK 1.6 released, a few new methods getTotalSpace(), getUsableSpace()
and getFreeSpace(), are bundled with java.io.File to retrieve the partition or disk space detail.
1.33.1

Example

package com.mkyong;

import java.io.File;
public class DiskSpaceDetail
{
public static void main(String[] args)
{
File file = new File("c:");
long totalSpace = file.getTotalSpace(); //total disk space in
bytes.
long usableSpace = file.getUsableSpace(); ///unallocated / free
disk space in bytes.
long freeSpace = file.getFreeSpace(); //unallocated / free disk
space in bytes.
System.out.println(" === Partition Detail ===");
System.out.println(" === bytes
System.out.println("Total size
System.out.println("Space free
System.out.println("Space free

mb");
mb");
mb");
}
}

1.33.2

===");
: " + totalSpace + " bytes");
: " + usableSpace + " bytes");
: " + freeSpace + " bytes");

System.out.println(" === mega bytes ===");


System.out.println("Total size : " + totalSpace /1024 /1024 + "
System.out.println("Space free : " + usableSpace /1024 /1024 + "
System.out.println("Space free : " + freeSpace /1024 /1024 + "

Output

Display the disk space detail in c: partition.


=== Partition Detail ===
=== bytes ===
Total size : 52428795904 bytes
Space free : 33677811712 bytes
Space free : 33677811712 bytes
=== mega bytes ===
Total size : 49999 mb
Space free : 32117 mb
Space free : 32117 mb

Note
Both getFreeSpace() and getUsableSpace() methods are return the same
total free disk space of a given partition. But the real different is not clear, even
in the java doc. Tell me if you know whats the different in between.
2

File Serialization

Take any object that implements the Serialization interface, convert it into bytes and store it
into file; The file can be fully restore back to the original object later.
2.1

How to write an Object to file in Java

Java object can write into a file for future access, this is called serialization. In order to do
this, you have to implement the Serializableinterface, and use ObjectOutputStream to write
the object into a file.
FileOutputStream fout = new FileOutputStream("c:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);

2.1.1 Address.java

Create an Address object and implement Serializable interface. This object is going to
write into a file.
package com.mkyong.io;
import java.io.Serializable;
public class Address implements Serializable{
String street;
String country;
public void setStreet(String street){
this.street = street;
}
public void setCountry(String country){
this.country = country;
}
public String getStreet(){
return this.street;
}
public String getCountry(){
return this.country;
}
@Override
public String toString() {
return new StringBuffer(" Street : ")
.append(this.street)
.append(" Country : ")
.append(this.country).toString();
}
}

2.1.2 Serializer.java

This class will write the Address object and its variable value (wall street, united state)
into a file named address.ser, locate in c drive.
package com.mkyong.io;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serializer {


public static void main (String args[]) {

Serializer serializer = new Serializer();


serializer.serializeAddress("wall street", "united state");

public void serializeAddress(String street, String country){


Address address = new Address();
address.setStreet(street);
address.setCountry(country);
try{
FileOutputStream fout = new
FileOutputStream("c:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);
oos.close();
System.out.println("Done");

}
}

2.2

}catch(Exception ex){
ex.printStackTrace();
}

How to read an Object from file in Java

In previous example, you learn about how to write an Object into a file in Java. In this
example, you will learn how to read an object from the saved file or how to deserialize the
serialized file.
The deserialize process is quite similar with the serialization, you need to use
ObjectInputStream to read the content of the file and convert it back to Java object.
FileInputStream fin = new FileInputStream("c:\\address.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
address = (Address) ois.readObject();

2.2.1 Deserializer.java

This class will read a serialized file c:\\address.ser created in this example, and convert it
back to Address object and print out the saved value.
package com.mkyong.io;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class Deserializer{
public static void main (String args[]) {
Deserializer deserializer = new Deserializer();
Address address = deserializer.deserialzeAddress();

System.out.println(address);
}
public Address deserialzeAddress(){
Address address;
try{
FileInputStream fin = new
FileInputStream("c:\\address.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
address = (Address) ois.readObject();
ois.close();
return address;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}

File Compression

File compression examples, ZIP and GZip.


3.1

How to compress files in ZIP format

Java comes with java.util.zip library to perform data compression in ZIp format. The
overall concept is quite straightforward.
1. Read file with FileInputStream
2. Add the file name to ZipEntry and output it to ZipOutputStream
3.1.1 Simple ZIP example

Read a file C:\\spy.log and compress it into a zip file C:\\MyFile.zip.


package com.mkyong.zip;
import
import
import
import
import

java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.ZipEntry;
java.util.zip.ZipOutputStream;

public class App


{
public static void main( String[] args )
{
byte[] buffer = new byte[1024];
try{

FileOutputStream fos = new


FileOutputStream("C:\\MyFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry("spy.log");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("C:\\spy.log");
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}

3.1.2 Advance ZIP example Recursively

Read all files from folder C:\\testzip and compress it into a zip file C:\\MyFile.zip. It
will recursively zip a directory as well.
package com.mkyong.zip;
import
import
import
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.ArrayList;
java.util.List;
java.util.zip.ZipEntry;
java.util.zip.ZipOutputStream;

public class AppZip


{
List<String> fileList;
private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
private static final String SOURCE_FOLDER = "C:\\testzip";
AppZip(){
fileList = new ArrayList<String>();
}
public static void main( String[] args )
{
AppZip appZip = new AppZip();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
/**

* Zip it
* @param zipFile output ZIP file location
*/
public void zipIt(String zipFile){
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
for(String file : this.fileList){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(SOURCE_FOLDER + File.separator +

file);

int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}

in.close();

zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}

/**
* Traverse a directory and get all files,
* and add the file into fileList
* @param node file or directory
*/
public void generateFileList(File node){
//add file only
if(node.isFile()){
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if(node.isDirectory()){
String[] subNote = node.list();
for(String filename : subNote){
generateFileList(new File(node, filename));
}
}

}
/**
* Format the file path for zip
* @param file file path
* @return Formatted file path
*/
private String generateZipEntry(String file){
return file.substring(SOURCE_FOLDER.length()+1, file.length());
}
}

Output
Output to Zip : C:\MyFile.zip
File Added : pdf\Java-Interview.pdf
File Added : spy\log\spy.log
File Added : utf-encoded.txt
File Added : utf.txt
Done

3.2

How to decompress files from a ZIP file

In previous article, we show you how to compress files to a zip file format. In this article we
will show you how to unzip it.
1. Read ZIP file with ZipInputStream
2. Get the files to ZipEntry and output it to FileOutputStream
3.2.1 Decompress ZIP file example

In this example, it will read a ZIP file from C:\\MyFile.zip, and decompress all zipped files
to C:\\outputzip folder.
package com.mkyong.zip;
import
import
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.List;
java.util.zip.ZipEntry;
java.util.zip.ZipInputStream;

public class UnZip


{
List<String> fileList;
private static final String INPUT_ZIP_FILE = "C:\\MyFile.zip";
private static final String OUTPUT_FOLDER = "C:\\outputzip";
public static void main( String[] args )
{
UnZip unZip = new UnZip();
unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER);
}
/**

* Unzip it
* @param zipFile input zip file
* @param output zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try{
//create output directory is not exists
File folder = new File(OUTPUT_FOLDER);
if(!folder.exists()){
folder.mkdir();
}
//get the zip file content
ZipInputStream zis =
new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while(ze!=null){

fileName);

String fileName = ze.getName();


File newFile = new File(outputFolder + File.separator +
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();

}
zis.closeEntry();
zis.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}

Output
file
file
file
file

unzip
unzip
unzip
unzip

:
:
:
:

C:\outputzip\pdf\Java-Interview.pdf
C:\outputzip\spy\log\spy.log
C:\outputzip\utf-encoded.txt
C:\outputzip\utf.txt

Done

3.3

How to compress a file in GZIP format

Gzip is a popular tool to compress a file in *nix system. However, Gzip is not a ZIP tool, it
only use to compress a file into a .gz format, not compress several files into a single
archive.
3.3.1 GZip example

In this example, it will compress a file /home/mkyong/file1.txt into a gzip file


/home/mkyong/file1.gz.
package com.mkyong.gzip;
import
import
import
import

java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.GZIPOutputStream;

public class GZipFile


{
private static final String OUTPUT_GZIP_FILE = "/home/mkyong/file1.gz";
private static final String SOURCE_FILE = "/home/mkyong/file1.txt";
public static void main( String[] args )
{
GZipFile gZip = new GZipFile();
gZip.gzipIt();
}
/**
* GZip it
* @param zipFile output GZip file location
*/
public void gzipIt(){
byte[] buffer = new byte[1024];
try{
GZIPOutputStream gzos =
new GZIPOutputStream(new
FileOutputStream(OUTPUT_GZIP_FILE));
FileInputStream in =
new FileInputStream(SOURCE_FILE);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
System.out.println("Done");

}catch(IOException ex){
ex.printStackTrace();
}

}
}

3.4

How to decompress file from GZIP file

In previous article, you learn about how to compress a file into a GZip format. In this article,
you will learn how to unzip it / decompress the compressed file from a Gzip file.
3.4.1 Gzip example

In this example, it will decompress the Gzip file /home/mkyong/file1.gz back to


/home/mkyong/file1.txt.
package com.mkyong.gzip;
import
import
import
import

java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.GZIPInputStream;

public class GZipFile


{
private static final String INPUT_GZIP_FILE = "/home/mkyong/file1.gz";
private static final String OUTPUT_FILE = "/home/mkyong/file1.txt";
public static void main( String[] args )
{
GZipFile gZip = new GZipFile();
gZip.gunzipIt();
}
/**
* GunZip it
*/
public void gunzipIt(){
byte[] buffer = new byte[1024];
try{
GZIPInputStream gzis =
new GZIPInputStream(new FileInputStream(INPUT_GZIP_FILE));
FileOutputStream out =
new FileOutputStream(OUTPUT_FILE);
int len;
while ((len = gzis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzis.close();
out.close();
System.out.println("Done");

}catch(IOException ex){
ex.printStackTrace();
}
}

3.5

How to compress serialized object into file

In last section, you learn about how to write or serialized an object into a file. In this
example , you can do more than just serialized it , you also can compress the serialized object
to reduce the file size.
The idea is very simple, just using the GZIPOutputStream for the data compression.
FileOutputStream fos = new FileOutputStream("c:\\address.gz");
GZIPOutputStream gz = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gz);

3.5.1 GZIP Example

In this example, you will create an Address object , compress it and write it into a file
c:\\address.gz.
P.S Address object can refer to this article.
package com.mkyong.io;
import
import
import
import

java.io.FileOutputStream;
java.io.ObjectOutputStream;
java.io.Serializable;
java.util.zip.GZIPOutputStream;

public class Serializer implements Serializable{


public static void main (String args[]) {

Serializer serializer = new Serializer();


serializer.serializeAddress("wall street", "united state");

public void serializeAddress(String street, String country){


Address address = new Address();
address.setStreet(street);
address.setCountry(country);
try{
FileOutputStream fos = new
FileOutputStream("c:\\address.gz");
GZIPOutputStream gz = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gz);
oos.writeObject(address);
oos.close();
System.out.println("Done");

}catch(Exception ex){
ex.printStackTrace();
}
}

3.6

How to decompress serialized object from a Gzip file

In last section, you learn about how to compress a serialized object into a file, now you learn
how to decompress it from a Gzip file.
FileInputStream fin = new FileInputStream("c:\\address.gz");
GZIPInputStream gis = new GZIPInputStream(fin);
ObjectInputStream ois = new ObjectInputStream(gis);
address = (Address) ois.readObject();

3.6.1 GZIP example

In this example, you will decompress a compressed file address.gz, and print it out the
value.
package com.mkyong.io;
import
import
import
import

java.io.FileInputStream;
java.io.ObjectInputStream;
java.io.Serializable;
java.util.zip.GZIPInputStream;

public class Deserializer implements Serializable{


public static void main (String args[]) {
Deserializer deserializer = new Deserializer();
Address address = deserializer.deserialzeAddress();
System.out.println(address);
}
public Address deserialzeAddress(){
Address address;
try{
FileInputStream fin = new
FileInputStream("c:\\address.gz");
GZIPInputStream gis = new GZIPInputStream(fin);
ObjectInputStream ois = new ObjectInputStream(gis);
address = (Address) ois.readObject();
ois.close();
return address;

}catch(Exception ex){
ex.printStackTrace();
return null;
}

3.6.2 Output
Street : wall street Country : united state

Temporary File

List of the temporary file manipulation examples.


4.1

How to create temporary file in Java

Heres an example to create a temporary file in Java.


4.1.1 Example
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateTempFileExample
{
public static void main(String[] args)
{
try{
//create a temp file
File temp = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}
}

4.1.2 Result
Temp file : C:\Users\mkyong\AppData\Local\Temp\temp-file-name623426.tmp

4.2

How to write data to temporary file in Java

Heres an example to write data to temporary file in Java. Actually, there are no different
between normal file and temporary file, what apply to normal text file, will apply to
temporary file as well.
4.2.1 Example

In this example, it will create a temporary file named tempfile.tmp, and write the text This
is the temporary file content inside.
package com.mkyong.file;
import
import
import
import

java.io.BufferedWriter;
java.io.File;
java.io.FileWriter;
java.io.IOException;

public class WriteTempFileExample


{

public static void main(String[] args)


{
try{
//create a temp file
File temp = File.createTempFile("tempfile", ".tmp");
//write it
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write("This is the temporary file content");
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}

4.3

How to delete temporary file in Java

Temporary file is used to store the less important and temporary data, which should always be
deleted when your system is terminated. The best practice is use the File.deleteOnExit() to
do it.
For example,
File temp = File.createTempFile("abc", ".tmp");
temp.deleteOnExit();

The above example will create a temporary file named abc.tmp and delete it when the
program is terminated or exited.
P.S If you want to delete the temporary file manually, you can still use the File.delete().
4.3.1 Example
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class DeleteTempFileExample
{
public static void main(String[] args)
{
try{
//create a temp file
File temp = File.createTempFile("temptempfilefile", ".tmp");
//delete temporary file when the program is exited
temp.deleteOnExit();

//delete immediate
//temp.delete();
}catch(IOException e){
e.printStackTrace();
}
}

4.4

How to get the temporary file path in Java

Heres an example to get the temporary file path in Java.


4.4.1 Example
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class GetTempFilePathExample
{
public static void main(String[] args)
{
try{
//create a temp file
File temp = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
//Get tempropary file path
String absolutePath = temp.getAbsolutePath();
String tempFilePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("Temp file path : " + tempFilePath);
}catch(IOException e){
e.printStackTrace();
}
}
}

4.4.2 Result
Temp file : C:\Users\mkyong\AppData\Local\Temp\temp-file-name79456440.tmp
Temp file path : C:\Users\mkyong\AppData\Local\Temp

Directory

List of the directory manipulation examples.


5.1

How to create directory in Java

To create a directory in Java, uses the following code :

1. Create a single directory.


new File("C:\\Directory1").mkdir();

2. Create a directory named Directory2 and all its sub-directories Sub2 and Sub-Sub2
together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()

Both methods are returning a boolean value to indicate the operation status : true if succeed,
false otherwise.
5.1.1 Example

A classic Java directory example, check if directory exists, if no, then create it.
package com.mkyong.file;
import java.io.File;
public class CreateDirectoryExample
{
public static void main(String[] args)
{
File file = new File("C:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
if (files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are
created!");
} else {
System.out.println("Failed to create multiple
directories!");
}
}
}
}

5.2

How to delete directory in Java

To delete a directory, you can simply use the File.delete(), but the directory must be empty in
order to delete it.
Often times, you may require to perform recursive delete in a directory, which means all its
sub-directories and files should be delete as well, see below example :
5.2.1 Directory recursive delete example

Delete the directory named C:\\mkyong-new, and all its sub-directories and files as well.
The code is self-explanatory and well documented, it should be easy to understand.

package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class DeleteDirectoryExample
{
private static final String SRC_FOLDER = "C:\\mkyong-new";
public static void main(String[] args)
{
File directory = new File(SRC_FOLDER);
//make sure directory exists
if(!directory.exists()){
System.out.println("Directory does not exist.");
System.exit(0);
}else{
try{
delete(directory);

}catch(IOException e){
e.printStackTrace();
System.exit(0);
}

System.out.println("Done");
}
public static void delete(File file)
throws IOException{
if(file.isDirectory()){
//directory is empty, then delete it
if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+ file.getAbsolutePath());
}else{
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);

//recursive delete
delete(fileDelete);

//check the directory again, if empty then delete it

if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+
file.getAbsolutePath());
}
}
}else{
//if file, then delete it
file.delete();
System.out.println("File is deleted : " +
file.getAbsolutePath());
}
}
}

5.2.2 Result
File is deleted : C:\mkyong-new\404.php
File is deleted : C:\mkyong-new\archive.php
...
Directory is deleted : C:\mkyong-new\includes
File is deleted : C:\mkyong-new\index.php
File is deleted : C:\mkyong-new\index.php.hacked
File is deleted : C:\mkyong-new\js\hoverIntent.js
File is deleted : C:\mkyong-new\js\jquery-1.4.2.min.js
File is deleted : C:\mkyong-new\js\jquery.bgiframe.min.js
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\css
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\images
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8
File is deleted : C:\mkyong-new\js\superfish-navbar.css
...
Directory is deleted : C:\mkyong-new
Done

5.3

How to copy directory in Java

Heres an example to copy a directory and all its sub-directories and files to a new destination
directory. The code is full of comments and self-explanatory, left me comment if you need
more explanation.
5.3.1 Example

Copy folder c:\\mkyong and its sub-directories and files to another new folder
c:\\mkyong-new.
package com.mkyong.file;
import
import
import
import
import
import

java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;

public class CopyDirectoryExample


{
public static void main(String[] args)
{
File srcFolder = new File("c:\\mkyong");

File destFolder = new File("c:\\mkyong-new");


//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{

copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}

System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();

out.close();
System.out.println("File copied from " + src + " to " +

dest);
}

5.3.2 Result
Directory copied from c:\mkyong to c:\mkyong-new
File copied from c:\mkyong\404.php to c:\mkyong-new\404.php
File copied from c:\mkyong\footer.php to c:\mkyong-new\footer.php
File copied from c:\mkyong\js\superfish.css to c:\mkyongnew\js\superfish.css
File copied from c:\mkyong\js\superfish.js to c:\mkyong-new\js\superfish.js
File copied from c:\mkyong\js\supersubs.js to c:\mkyong-new\js\supersubs.js
Directory copied from c:\mkyong\images to c:\mkyong-new\images
File copied from c:\mkyong\page.php to c:\mkyong-new\page.php
Directory copied from c:\mkyong\psd to c:\mkyong-new\psd
...
Done

5.4

How to traverse a directory structure in Java

In this example, the program will traverse the given directory and print out all the directories
and files absolute path and name one by one.
5.4.1 Example
package com.mkyong.io;
import java.io.File;
public class DisplayDirectoryAndFile{
public static void main (String args[]) {
displayIt(new File("C:\\Downloads"));
}
public static void displayIt(File node){
System.out.println(node.getAbsoluteFile());
if(node.isDirectory()){
String[] subNote = node.list();
for(String filename : subNote){
displayIt(new File(node, filename));
}
}
}
}

5.4.2 Output
C:\Downloads
C:\Downloads\100 Java Tips.pdf
C:\Downloads\1590599799.rar
C:\Downloads\2009
C:\Downloads\573440.flv
C:\Downloads\575492.flv
C:\Downloads\avira_antivir_personal_en.exe

C:\Downloads\backup-mkyong.com-12-24-2009.tar.gz
......

5.5

How to check if directory is empty in Java

Heres an example to check if a directory is empty.


5.5.1 Example
package com.mkyong.file;
import java.io.File;
public class CheckEmptyDirectoryExample
{
public static void main(String[] args)
{
File file = new File("C:\\folder");
if(file.isDirectory()){
if(file.list().length>0){
System.out.println("Directory is not empty!");
}else{
System.out.println("Directory is empty!");
}
}else{
System.out.println("This is not a directory");
}
}

5.6

How to get the current working directory in Java

The current working directory means the root folder of your current Java project, it can be
retrieved by using the following system property function.
String workingDir = System.getProperty("user.dir");

5.6.1 Example
package com.mkyong.io;
public class App{
public static void main (String args[]) {
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
}
}

Output
Current working directory : E:\workspace\HibernateExample

Console IO

List of the Console IO examples.


6.1

How to get the standard input in Java

A quick example to show how to read the standard input in Java.


package com.mkyong.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class printStdIn{
public static void main (String args[]) {
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input;
while((input=br.readLine())!=null){
System.out.println(input);
}
}catch(IOException io){
io.printStackTrace();
}
}

Вам также может понравиться