Programmer Coding

Java – Files and I/O

The java.io package insure  nearly every class you might ever need to apply input and output (I/O) in Java. All these flows represent an input source and an output destination. The flow in the java.io package pillars a lot of data such as primitives, object, localized characters, etc.

Flow

A flow can be circle as a sequence of data. There are two kinds of Flows −

 

  • InPutFlow − The Input Flow is used to read data from a

 

  • OutPutFlow − The Output Flow is used for writing data to a

 

 

Java gives strong but changeability  pillar for I/O related to files and networks but this tutorial covers very basic convenience related to flows and I/O. We will see the most commonly used examples one by one −

Byte Flows

Java byte flows are used to apply input and output of 8-bit bytes. Though there are a lot of classes     related     to     byte     flows     but     the      most       often     used      classes are, FileInput Flow and FileOutputFlow. Following is an example which makes use of these two classes to copy an input file into an output file −

Example
import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException { FileInputFlow in = null;

FileOutputFlow out = null; try {

in = new FileInputFlow(“input.txt”);

out = new FileOutputFlow(“output.txt”); int c;

while ((c = in.read()) != -1) {

 

out.write(c);

}

}finally {

if (in != null) {

in.close();

}

if (out != null) { out.close();

}} }}

 

Now let’s have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and apply it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put the above code in CopyFile.java file and do the following −

$javac CopyFile.java

$java CopyFile

Character Flows

Java Byte flows are used   to    apply   input    and   output   of   8-bit    bytes,    whereas Java Character flows are used to apply input and output for 16-bit unicode. Though there are a lot of classes related to character flows   but   the   most    often   used    classes are, FileReader and FileWriter. Though innerly FileReader uses FileInputFlow and FileWriter uses FileOutputFlow but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −

Example
import java.io.*;

public class CopyFile {

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

 

FileReader in = null; FileWriter out = null; try {

in = new FileReader(“input.txt”); out = new FileWriter(“output.txt”); int c;

while ((c = in.read()) != -1) { out.write(c);}

}finally {

 

if (in != null) {

 

in.close();}

 

if (out != null) { out.close();

}} }}

 

Now let’s have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and apply it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put the above code in CopyFile.java file and do the following −

$javac CopyFile.java

$java CopyFile

Typical Flows

All the programming languages provide pillar for typical I/O where the user’s program can take input from a keyboard and then produce an output on the computer screen. Java gives the following three typical flows −

  • Typical Input − This is used to feed the data to user’s program and usually a keyboard is used as typical input flow and identifi asin.

 

  • Typical Output − This is used to output the data produced by the user’s program and usually a computer screen is   used   for   typical   output   flow and   identifi as out.
  • Typical Error − This is used to output the error data produced by the user’s program and usually a computer screen is used for typical error flow and identifi as err.

Following is a simple program, which produces InputFlowReader to read typical input flow until the user types a ”

Example

import java.io.*;

public class ReadConsole {

 

public static void main(String args[]) throws IOException { InputFlowReader cin = null;

try {

 

cin = new InputFlowReader(System.in); System.out.println(“Enter characters, ‘q’ to quit.”); char c;

do {

 

c = (char) cin.read(); System.out.print(c);

} while(c != ‘q’);

 

}finally {

 

if (cin != null) {

 

cin.close();

 

} } }}

 

This program continues to read and output the same character until we press ‘q’ −

$javac ReadConsole.java

$java ReadConsole

 

Enter characters, ‘q’ to quit. 1

1

e e q q

Reading and Writing Files

As described shortly, a flow can be circle as a sequence of data. The InputFlow is used to read data from a source and the OutputFlow is used for writing data to a destination.

Here is a ranking of classes to deal with Input and Output flows.

 

The two important flows are FileInputFlow and FileOutputFlow

 

FileInputFlow

This flow is used for reading data from the files. Objects can be produced using the keyword new and there are some types of creaters free-for-all.

InputFlow f = new FileInputFlow(“C:/java/hello”);

Following creater takes a file name as a string to produce an input flow object to read the file −

 

File f = new File(“C:/java/hello”); InputFlow f = new FileInputFlow(f);

Following creater takes a file object to produce an input flow object to read the file. First we produce a file object using File() way(method)  as follows −

Once you have InputFlow object in hand, then there is a list of helper way(method) s which can be  used to read to flow or to do other missions on the flow.

 

FileOutputFlow

FileOutputFlow is used to produce a file and write data into it. The flow would produce a file, if it doesn’t already exist, before opening it for output.

Here are two creaters which can be used to produce a FileOutputFlow object.

 

OutputFlow f = new FileOutputFlow(“C:/java/hello”)

Following creater takes a file name as a string to produce an input flow object to write the file −

Following creater takes a file object to produce an output flow object to write the file. First, we produce a file object using File() way(method)  as follows −

File f = new File(“C:/java/hello”); OutputFlow f = new FileOutputFlow(f);

Once you have OutputFlow object in hand, then there is a list of helper way(method) s, which can be used to write to flow or to do other missions on the flow.

 

Example

 

Following is the example to demonstrate InputFlow and OutputFlow −

 

import java.io.*;

 

public class fileFlowTest {

 

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

 

byte bWrite [] = {11,21,3,40,5};

 

OutputFlow os = new FileOutputFlow(“test.txt”); for(int x = 0; x < bWrite.length ; x++) {

os.write( bWrite[x] ); // writes the bytes} os.close();

InputFlow is = new FileInputFlow(“test.txt”); int size = is.available();

for(int i = 0; i < size; i++) { System.out.print((char)is.read() + ” “); }

is.close();

} catch (IOException e) { System.out.print(“Exception”);

}
}}

 

Java.io.RandomEntranceFile Class

The Java.io.RandomEntranceFile class file behaves like a large array of bytes stored in the file system.Instances of this class pillar both reading and writing to a random entrance file.

Class announcement

Following is the announcement for Java.io.RandomEntranceFile class −

public class RandomAccessFile extends Object

implements DataOutput, DataInput, Closeable

Class creaters

S.N.                                                          Creater & Description

 

 

1          RandomEntranceFile(File file, String mode)

This produces a random entrance file flow to read from, and optionally to write to, the file specified by the File argument.

 

 

 

2

 

 

 

RandomEntranceFile(File file, String mode)

 

This produces a random entrance file flow to read from, and optionally to write to, a file with the specified name.

Way(method) sinherited

This class inherits way(method) s from the following classes −

 

·        Java.io.Object

 

 

Java.io.File Class in Java

The File class is Java’s representation of a file or directory path name. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. The File class insure  some way(method) s for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, and determining some frequent attributes of files and directories.

§   It is an conceptual representation of file and directory pathnames.

§   A pathname, whether conceptual or in string form can be either absolute or relative. The root of  of an conceptual pathname may be obtained by invoking the getRoot of () way(method)  of this class.

§   First of all, we should produce the File class object by passing the filename or directory name to it. A file system may implement limitions to certain missions on the actual file- system object, such as reading, writing, and executing. These limitions are collectively known as entrance permissions.

§   Instances of the File class are can be change; that is, once produced, the conceptual pathname identifi by a File object will never change.

How to produce a File Object?

A File object is produced by passing in a String that represents the name of a file, or a String or another File object. For example,

File a = new File(“/usr/local/program/geeks”);

 

bounds an conceptual file name for the geeks file in directory /usr/local/ program. This is an absolute conceptual file name.

Program to check if a file or directory daily exist or not.

// In this program, we accepts a file or directory name from

// command line arguments. Then the program will check if

// that file or directory daily  exist or not and

// it displays the property of that file or directory.

*import java.io.File;

 

// Displaying file property class fileProperty

{

public static void main(String[] args) {

 

programmercoding.com

 

//accept file name or directory name through command line args String fname =args[0];

 

//pass the filename or directory name to File object File f = new File(fname);

 

//apply File class way(method) s on File object System.out.println(“File name :”+f.getName()); System.out.println(“Path: “+f.getPath()); System.out.println(“Absolute path:” +f.getAbsolutePath()); System.out.println(“Root of :”+f.getRoot of ()); System.out.println(“Exists :”+f.exists());

if(f.exists())

{

System.out.println(“Is writeable:”+f.canWrite()); System.out.println(“Is legible”+f.canRead()); System.out.println(“Is a directory:”+f.isDirectory()); System.out.println(“File Size in bytes “+f.length());

}

}

}

 

Output:

File name :file.txt Path: file.txt

Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt Parent:null

Exists :true

Is writeable:true Is readabletrue

Is a directory:false File Size in bytes 20

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top