Reading from a file and writing to a file using Java program
By: Baski
Java provides a number of classes and methods that allow you to read and write files. In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. However, Java allows you to wrap a byte-oriented file stream within a character-based object. This tutorial examines the basics of file I/O.Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. While both classes support additional, overridden constructors, the following are the forms that we will be using:
FileInputStream(String fileName) throws
FileNotFoundException
FileOutputStream(String fileName) throws
FileNotFoundException
Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be created, then FileNotFoundException is thrown. When an output file is opened, any preexisting file by the same name is destroyed.
Note: In earlier versions of Java, FileOutputStream( ) threw an IOException when an output file could not be created. This was changed by Java 2.
When you are done with a file, you should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream, as shown here:
void close( ) throws IOException
To read from a file, you can use a version of read( ) that is defined within FileInputStream. The one that we will use is shown here:
int read( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered. It can throw an IOException.
The following program uses read( ) to input and display the contents of a text file, the name of which is specified as a command-line argument. Note the try/catch blocks that handle the two errors that might occur when this program is used—the specified file not being found or the user forgetting to include the name of the file. You can use this same approach whenever you use command-line arguments.
/* Display a text file.
To use this program, specify the name of the file that you want to see.
For example, to see a file called TEST.TXT, use the following command line.
java ShowFile TEST.TXT
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
To write to a file, you will use the write( ) method defined by FileOutputStream. Its simplest form is shown here:
void write(int byteval) throws IOException
This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example uses write( ) to copy a text file:
/* Copy a text file.
To use this program, specify the name of the source file and the destination file.
For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, use the following
command line.
java CopyFile FIRST.TXT SECOND.TXT
*/
import java.io.*;
class CopyFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
Notice the way that potential I/O errors are handled in this program and in the preceding ShowFile program. Unlike most other computer languages, including C and C++, which use error codes to report file errors, Java uses its exception handling mechanism. Not only does this make file handling cleaner, but it also enables Java to easily differentiate the endof- file condition from file errors when input is being performed. In C/C++, many input functions return the same value when an error occurs and when the end of the file is reached. (That is, in C/C++, an EOF condition often is mapped to the same value as an input error.) This usually means that the programmer must include extra program statements to determine which event actually occurred. In Java, errors are passed to your program via exceptions, not by values returned by read( ). Thus, when read( ) returns –1, it means only one thing: the end of the file has been encountered.
Archived Comments
1. icuyixiuf
View Tutorial By: icuyixiuf at 2017-03-21 22:49:18
2. ajusixapo
View Tutorial By: ajusixapo at 2017-03-21 03:48:17
3. uzisihasesih
View Tutorial By: uzisihasesih at 2017-03-21 03:27:48
4. how to read an input that we are giving to another file plzzz provide code for this in java
View Tutorial By: Lakshmi at 2016-03-12 08:59:36
5. how to read a number from a keyboard and write that number to a file,read number from file ,find sum
View Tutorial By: aiswarya at 2015-09-13 03:48:05
6. Hello there , i am unable to understand read and write example. Will u please send me a simple read
View Tutorial By: deepak at 2014-12-10 14:04:42
7. Friends i m getting error while intrepreting the error is as follows..
could not find or load
View Tutorial By: Hanuman at 2014-02-04 14:14:00
8. How to do the following
Create a class With 3 methods create ,write and read and in another c
View Tutorial By: Anurag at 2014-01-03 10:14:45
9. VERY good info. Providing By YOU Thanx.
View Tutorial By: Ravi singh at 2013-11-14 08:56:34
10. read and write methods given here are for a file which is already created. But how to create a file
View Tutorial By: Tavva Yaswanth at 2012-10-28 08:02:10
11. Very helpful tutorial for me.
Thank you for providing such good content.
View Tutorial By: Mohan at 2012-05-28 00:12:56
12. very useful information from this page.
View Tutorial By: mahadevi at 2012-04-12 04:38:53
13. very useful information from this page.
View Tutorial By: mahadevi at 2012-04-12 04:35:16
14. material is good..
is it possible to read and write a string to a file...??
View Tutorial By: swapaneel at 2012-04-05 09:02:08
15. nice one dear
View Tutorial By: pradeep at 2010-02-15 07:01:49
16. nice one dear
View Tutorial By: pradeep at 2010-02-15 07:01:14
17. nice one dear
View Tutorial By: pradeep at 2010-02-15 07:00:35
18. nice material
View Tutorial By: ravi at 2008-12-24 00:40:12
19. I got some very useful information from this page i realy want these thing very badly.
View Tutorial By: King at 2008-01-08 20:26:21
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program