Java
IO Lesion 01
Java
supports the in put and out put through byte stream and file system.
1.
Create a File in Java
It
uses File.createNewFile() method to
create a file in Java, and this returns a boolean value.
2.
To construct the file path
There
is two ways to construct the path.
a.
Check the operating system and create the file separator manually.
String
workingDir = System.getProperty("user.dir");
String
os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("win")
>= 0){
fileAndPath
= workingDir + "\\"
+ filename;
}else
if(os.indexOf(
"nix")
>=0 || your_os.indexOf( "nux")
>=0){
fileAndPath
= workingDir + "/"
+ filename;
}else{
fileAndPath
= workingDir + "{others}"
+ filename;
}
b.
File.separator
(Best Practice)
3.
Give file permission to the file
file.setExecutable(boolean);
– true, allow execute operations; false to disallow it.
file.setReadable(boolean);
– true, allow read operations; false to disallow it.
file.setWritable(boolean);
– true, allow write operations; false to disallow it.
In
*nix system, need to configure more specifies about file permission.
But
Java IO classes do not have ready method for it, but there is a dirty
workaround :
Runtime.getRuntime().exec("chmod
777 file");
4.
Write to file – FileOutputStream
In
Java, FileOutputStream is a bytes stream class that’s 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.
fop
= new
FileOutputStream(file);
//
get the content in bytes
byte[]
contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
5.
Write to file – BuferedWriter
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.
FileWriter
fw = new
FileWriter(file.getAbsoluteFile());
BufferedWriter
bw = new
BufferedWriter(fw);
bw.write(content);
bw.close();
6.
Read from file – BuferedInputStream
Read
a file in Java with BufferedInputStream and DataInputStream classes.
The
readLine() from the type DataInputStream is deprecated. It’s
advised to use BufferedReader.
fis
= new
FileInputStream(file);
bis
= new
BufferedInputStream(fis);
dis
= new
DataInputStream(bis);
while
(dis.available() != 0) {
System.out.println(dis.readLine());
}
7.
Read from file – BufferedReader
The
simplest and most common-used method to read a file –
BufferedReader.
String
sCurrentLine;
br
= new
BufferedReader(new
FileReader(file));
while
((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
}
7.
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,
if 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);
//true
= append file
FileWriter
fileWritter = new
FileWriter(file.getName(),true);
BufferedWriter
bufferWritter = new
BufferedWriter(fileWritter);
bufferWritter.write(appendContent);
bufferWritter.close();
8.
Delete a File
File.delete()
to delete a file, it will return a boolean value to indicate the
delete operation status; true:deleted.
9.
Rename File
Java
comes with renameTo() method to rename a
file.
However
, this method is really platform-dependent: file in *nix success but
failed in Windows.
10.
Get few useful information about file.
//file
name
System.out.println("Name
: " + file.getName());
//file
path
System.out.println("Path
: " + file.getPath());
//file
path
String
absolutePath = file.getAbsolutePath();
System.out.println("AbsolutePath
: " + absolutePath);
String
filePath =
absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("filePath
: " + filePath);
//last
modified date-time
SimpleDateFormat
sdf = new
SimpleDateFormat("MM/dd/yyyy
HH:mm:ss");
System.out.println("lastModified :
" +
sdf.format(file.lastModified()));
//file
size
System.out.println("Size
in bytes : " + file.length());
System.out.println("Size
in kilobytes : " +
file.length()/1024);
//total
number of lines
int
linenumber = 0;
try
{
LineNumberReader
lnr = new
LineNumberReader(new
FileReader(file));
while
(lnr.readLine() != null){
linenumber++;
}
lnr.close();
}
catch
(IOException e) {
e.printStackTrace();
}
System.out.println("Total
number of lines : " +
linenumber);
//file
is a hidden-or-not
System.out.println("Is
Hidden : " + file.isHidden());
Example
-
package
JavaIO;
import
java.io.BufferedInputStream;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.DataInputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.FileReader;
import
java.io.FileWriter;
import
java.io.IOException;
import
java.io.LineNumberReader;
import
java.text.SimpleDateFormat;
public
class
CreateFile {
private
boolean
CREATE_ON_WORKINGDIR
= false;
private
void
createFile(){
try{
//Set
File and path
String
fileAndPath = getfileAndFilePath();
File
file = new
File(fileAndPath);
System.out.println("File
is Exists : " + file.exists());
//delete
if(file.exists())
file.delete();
//create
if(file.createNewFile()){
System.out.println("File
Created.");
}else{
System.out.println("File
already exists!");
}
//write
- FilOutPutStream
if(file.exists())
file = writeByFilOutPutStream(file);
//write
- BufferedWriter
if(file.exists())
file = writeByBufferedWriter(file);
//read
- BufferedInputStream
if(file.exists())
file = readByBufferedInputStream(file);
//appendToFile
if(file.exists())
file = appendToFile(file);
//read
- BufferedReader
if(file.exists())
file = readByBufferedReader(file);
//get
few informations
if(file.exists())
getInformation(file);
if(file.exists())
file = setPermission(file);
}catch
(IOException ioe) {
ioe.printStackTrace();
}
}
private
String getfileAndFilePath(){
String
fileName = "text.txt";
String
filePath = "";
if(CREATE_ON_WORKINGDIR){
//Get the current working directory
String workingDir = System.getProperty("user.dir");
//workingDir | os
"/home/sanjeeva/eclipseworkspace/BasicConcepts"
| linux
filePath = workingDir + File.separator
+ fileName;
}else{
String saveLocation = "/home/sanjeeva/Desktop";
filePath = saveLocation + File.separator
+ fileName;
}
System.out.println("filePath
--> " + filePath);
return
filePath;
}
private
File setPermission(File file){
file.setExecutable(false);
file.setReadable(true);
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());
return
file;
}
private
File writeByFilOutPutStream(File file){
String
content = "I am Sanjeeva Pathirana,
Sri Lankan who is like to learn new technologies";
FileOutputStream
fop = null;
try{
fop
= new
FileOutputStream(file);
//
get the content in bytes
byte[]
contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done
- writeByFilOutPutStream");
}catch
(IOException ioe) {
ioe.printStackTrace();
}finally{
if(null
!= fop){
try
{
fop.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
return
file;
}
private
File writeByBufferedWriter(File file){
String
content = "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.";
try{
FileWriter
fw = new
FileWriter(file.getAbsoluteFile());
BufferedWriter
bw = new
BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done
- writeByBufferedWriter");
}catch
(IOException ioe) {
ioe.printStackTrace();
}
return
file;
}
@SuppressWarnings("deprecation")
private
File readByBufferedInputStream(File file){
FileInputStream
fis = null;
BufferedInputStream
bis = null;
DataInputStream
dis = null;
try
{
fis
= new
FileInputStream(file);
bis
= new
BufferedInputStream(fis);
dis
= new
DataInputStream(bis);
System.out.println("------------------------------ -\n
Read - BufferedInputStream :");
while
(dis.available() != 0) {
System.out.println(dis.readLine());
}
}
catch
(IOException ioe) {
ioe.printStackTrace();
}
finally
{
try
{
fis.close();
bis.close();
dis.close();
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
return
file;
}
private
File readByBufferedReader(File file){
BufferedReader
br = null;
try
{
String
sCurrentLine;
br
= new
BufferedReader(new
FileReader(file));
while
((sCurrentLine = br.readLine()) != null)
{
System.out.println("-------------------------- -----\n
Read - BufferedReader :");
System.out.println(sCurrentLine);
}
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
try
{
if
(br != null)br.close();
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
return
file;
}
private
File appendToFile(File file){
String
appendContent = "\nFileWritter, a
character stream to write characters to file. By default, "
+
"it
will replace all the existing content with new content. However, "
+
"if
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.";
//
\n - this is used to append to a new line.
try{
//true
= append file
FileWriter
fileWritter = new
FileWriter(file,true);
BufferedWriter bufferWritter = new
BufferedWriter(fileWritter);
bufferWritter.write(appendContent);
bufferWritter.close();
System.out.println("Done
- appendToFile");
}catch
(IOException ioe) {
ioe.printStackTrace();
}
return
file;
}
private
void
getInformation(File file){
//file
name
System.out.println("Name
: " + file.getName());
//file
path
System.out.println("Path
: " + file.getPath());
//file
path
String
absolutePath = file.getAbsolutePath();
System.out.println("AbsolutePath
: " + absolutePath);
String
filePath =
absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("filePath
: " + filePath);
//last
modified date-time
SimpleDateFormat
sdf = new
SimpleDateFormat("MM/dd/yyyy
HH:mm:ss");
System.out.println("lastModified :
" +
sdf.format(file.lastModified()));
//file
size
System.out.println("Size
in bytes : " + file.length());
System.out.println("Size
in kilobytes : " +
file.length()/1024);
//total
number of lines
int
linenumber = 0;
try
{
LineNumberReader
lnr = new
LineNumberReader(new
FileReader(file));
while
(lnr.readLine() != null){
linenumber++;
}
lnr.close();
}
catch
(IOException e) {
e.printStackTrace();
}
System.out.println("Total
number of lines : " +
linenumber);
//file is a hidden-or-not
System.out.println("Is
Hidden : " + file.isHidden());
}
private
File renameFile(File file){
File
newfile = new
File("javaIO.txt");
if(file.renameTo(newfile)){
System.out.println("Rename
succesful");
}else{
System.out.println("Rename
failed");
}
return
file;
}
/**
* @param
args
*/
public
static
void
main(String[] args) {
CreateFile
createFile = new
CreateFile();
createFile.createFile();
}
}