Let’s now see some I/O streams that are used to perform reading and writing operation in a file. Java supports the following I/O file streams.
This class is a subclass of Inputstream class that reads bytes from a specified file name. The read () method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as :
//syntex FileInputstream (File filename);
This class is a subclass of OutputStream that writes data to a specified file name. The write () method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as :
//Syntex FileOutputstream (File filename);
This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as :
//Syntex DataInputStream (FileOutputstream finp);
The following program demonstrates how contains are read from a file.
import java.io.*; public class ReadFile { public static void main(String[] args) throws IOException { File f; f=new File("myfile.txt"); if(!f.exists()&& f.length()<0) System.out.println("The specified file is not exist"); else{ FileInputStream finp=new FileInputStream(f); byte b; do{ b=(byte)finp.read(); System.out.print((char)b); } while(b!=-1); finp.close(); } } //Output of the Program: C:\>javac ReadFile.java C:\>java ReadFile this is a text file? C:\>
This program reads the bytes from file and displays it to the user.
Now we will learn how to write data to a file. As discussed, the FileOutputStream class is used to write data to a file.
Let’s see an example that writes the data to a file converting into the bytes.
This program first checks the existence of the specified file. If the file exists, the data is written to the file through the object of the FileOutputStream class.
import java.io.*; public class WriteFile { public static void main(String[] args) throws IOException { File f=new File ("textfile1.txt"); FileOutputStream fop=new FileOutputStream (f); if (f.exists ()) { String str="This data is written through the program"; fop.write (str.getBytes ()); fop.flush (); fop.close (); System.out.println ("The data has been written"); } else System.out.println ("This file is not exist"); } //Output of the Program C:\>javac WriteFile.java C:\>java WriteFile The data has been written C:\>
Now, you will learn how to count the availability of text lines in the particular file. A file is read before counting lines of a particular file. File is a collection of stored information that is arranged in string, rows, columns and lines etc. Try it for getting the lines through the following program
Description of program :
The following program helps you in counting lines of a particular file. At the execution time of this program, it takes a file name with its extension from a particular directory and checks it using exists () method. If the file exists, it will count lines of a particular file otherwise it will display a message “File does not exists!”
Here is the code of program :
import java.io.*; public class NumberOfLine{ public static void main(String[] args) { try{ System.out.println("Getting line number of a particular file exam ple!"); BufferedReader bf = new BufferedReader(new InputStreamRea der(System.in)); System.out.println("Please enter file name with extension:"); String str = bf.readLine(); File file = new File(str); if (file.exists()){ FileReader fr = new FileReader(file); LineNumberReader ln = new LineNumberReader(fr); int count = 0; while (ln.readLine() != null){ count++; } System.out.println("Total line no: " + count); ln.close(); } else{ System.out.println("File does not exists!"); } } catch(IOException e){ e.printStackTrace(); } } } //Output of program: Getting line number of a particular file example! Please enter file name with extension: AddTwoBigNumbers.shtml Total line no: 58
Java provides the facility for changing a file timestamp according to the user reliability.
This program helps you in changing a file timestamp or modification time in Java. After running this program it will take a file name and its modification date in 'dd-mm-yyyy' format. Then it will check the given file is exist or not using exists () method. When the file exists, this program will change the date of given file and it will display a message "Modification is successfully!" otherwise it will show “File does not exists!”
setLastModified(long time) :
This is the method that sets the last modification time of a file or directory and returns Boolean types values either 'true' or 'false'. If it will return a 'true' only when the modification is completely successfully otherwise, it will return 'false'. This method takes following long type data :
time :
This is the time that has to be modified or set.
getTime () :
This is the method that returns the number of milliseconds in GMT format like : 23-04-2007.
Here is the code of program :
import java.io.*; import java.util.*; import java.text.*; public class ChangeFileDate{ public static void main(String[] args) { try{ System.out.println("Change file timestamp example!"); BufferedReader bf = new BufferedReader(new InputStreamRea der(System.in)); System.out.println("Enter file name with extension:"); String str = bf.readLine(); System.out.println("Enter last modified date in “dd-mmyyyy” format:"); String strDate = bf.readLine(); SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.parse(strDate); File file = new File(str); if (file.exists()){ file.setLastModified(date.getTime()); System.out.println("Modification is successfully!"); } else{ System.out.println("File does not exists!"); } } catch(Exception e){ e.printStackTrace(); } } //Output of program: Change file timestamp example! Enter file name with extension: StrStartWith.shtml Enter last modified date in “dd-mmyyyy” format: 23-04-2007 Modification is successfully
To find a file or directory it is very necessary to know the path of the file or directory so that you can access it. If you know the path then it is very easy to work on it. Suppose a situation where a problem comes in front you where you don't know the path of the file, then what will you do? This problem can be solved by using a method getAbsolutePath ().The method getAbsolutePath () should be used where we don't know the exact path of the file.
To find an absolute path of a file, Firstly we have to make a class GetAbsolutePath. Inside this class, define the main method. Inside this method define a File class of java.io package. Inside the constructor of a File class pass the name of the file whose absolute path you want to know. Now call the method getAbsolutePath () of the File class by the reference of File class and store it in a String variable. Now print the string, you will get an absolute path of the file.
In this class we have make use of the following things by which this problem can be solved.
File : It is class in java.io package. It implements Comparable and Serializable interface.
getAbsolutePath () : It returns the absolute path name in the form of string.
Code of the program is given below :
import java.io.*; public class GetAbsolutePath { public static void main(String[ ] args) { String str = args[0]; File file = new File(str); String absolutePathOfFirstFile = file.getAbsolutePath(); System.out.println(" The absolute path in first form is " + absolutePathOfFirstFile); file = new File( "Happy" + File.separatorChar+ str); String absolutePathOfSecondFile = file.getAbsolutePath(); System.out.println(" The absolute path is " + absolutePathOfSec ondFile); file = new File("Happy" + File.separator + ".." + File.separator + str); String absolutePathOfThirdFile = file.getAbsolutePath (); System.out.println (" The absolute path is” + absolutePathOfThirdFile); } Output of the program Happy The absolute path in first form is C:\admin\Happy The absolute path is C:\admin\Happy\Happy The absolute path is C:\Admin\Happy\..\Happy
All Rights Reserved. © 2024 BookOfNetwork