Java IO Tutorial
Java IO Tutorial
Java IO Tutorial
File................................................................................................................... 6
1.1
1.2
1.2.1
File.separator....................................................................................... 7
1.2.2
new File()............................................................................................. 8
1.2.3
1.3
1.3.1
1.4
1.5
1.6
1.7
1.8
1.8.1
1.8.2
Result................................................................................................ 16
1.9
1.9.1
Example............................................................................................ 16
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
2.1.1
Address.java...................................................................................... 40
2.1.2
Serializer.java.................................................................................... 41
2.2
2.2.1
3
File Compression............................................................................................ 42
3.1
3.1.1
3.1.2
3.2
3.2.1
3.3
3.4
GZIP Example.................................................................................... 49
3.6.1
GZIP example.................................................................................... 50
3.6.2
Output............................................................................................... 51
Temporary File................................................................................................ 51
4.1
4.1.1
Example............................................................................................ 51
4.1.2
Result................................................................................................ 52
4.2
4.2.1
4.3
4.4
Example............................................................................................ 52
4.3.1
Gzip example..................................................................................... 48
3.5.1
3.6
GZip example.................................................................................... 47
3.4.1
3.5
3.3.1
Deserializer.java................................................................................ 42
Example............................................................................................ 53
4.4.1
Example............................................................................................ 53
4.4.2
Result................................................................................................ 54
Directory........................................................................................................ 54
5.1
5.1.1
5.2
5.2.1
5.2.2
Result................................................................................................ 57
5.3
5.3.1
Example............................................................................................ 57
5.3.2
Result................................................................................................ 59
5.4
5.4.1
Example............................................................................................ 59
5.4.2
Output............................................................................................... 59
5.5
5.5.1
5.6
Example............................................................................................ 60
5.6.1
6
Example............................................................................................ 55
Example............................................................................................ 60
Console IO...................................................................................................... 61
6.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
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();
}
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
} catch (IOException e) {
e.printStackTrace();
}
Output
Final filepath :
/Users/mkyong/Documents/workspace/maven/fileUtils/newFile.txt
File is created!
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!
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
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.
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.4
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;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
1.5
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;
1.6
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();
}
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;
}
}
1.8
} catch (IOException e) {
e.printStackTrace();
}
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);
java.io.File;
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
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
1.9
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 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;
}
}
}
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;
}
}
}
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");
}
}
}
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
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;
}
}
}catch(IOException e){
e.printStackTrace();
}
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
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;
}catch(IOException e){
e.printStackTrace();
}
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
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
08:05
14 logfile.log
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
package com.mkyong.file;
import java.io.File;
import java.text.SimpleDateFormat;
1.16.2
Result
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;
}
}
1.17.1
Result
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
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);
}
}
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
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());
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
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
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
1
2
3
4
Line
Line
Line
Line
Line
Line
5
6
7
8
9
10
java.io.File;
java.io.FileReader;
java.io.IOException;
java.io.LineNumberReader;
}catch(IOException e){
e.printStackTrace();
}
}
}
1.21.2
Result
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!");
}
}
}
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
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;
}
}
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;
}
}
}
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
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
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
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
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();
}
}
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();
}
}
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;
java.io.BufferedReader;
java.io.ByteArrayInputStream;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
Output
file content..blah blah
Done
Example
package com.mkyong;
import
import
import
import
import
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStream;
java.io.PrintStream;
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();
1.32.2
Demo
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
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");
Output
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
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;
}
}
2.2
}catch(Exception ex){
ex.printStackTrace();
}
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
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
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.ZipEntry;
java.util.zip.ZipOutputStream;
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;
* 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
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;
* 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);
}
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
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
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.GZIPOutputStream;
}catch(IOException ex){
ex.printStackTrace();
}
}
}
3.4
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
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.util.zip.GZIPInputStream;
}catch(IOException ex){
ex.printStackTrace();
}
}
3.5
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);
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;
}catch(Exception ex){
ex.printStackTrace();
}
}
3.6
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();
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;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
3.6.2 Output
Street : wall street Country : united state
Temporary File
4.1.2 Result
Temp file : C:\Users\mkyong\AppData\Local\Temp\temp-file-name623426.tmp
4.2
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;
4.3
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
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
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
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);
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
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;
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
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
5.6
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