Programming | Android | Tips N Tricks

Post Page Advertisement [Top]

Hey Guys, here i present simple example that reads and prints a simple string to test file in java. There are many ways to do that but the simplest way that i like is using "BufferedReader class" for reading and "BufferedWriter class" for writing to the text file.

Why this way is simple? (Simplest way to perform Reading and Writing to text file)

The traditional way is to first set the file path using File class and make object. Then set input/output stream for character and finally using character Streams class perform read and write to the text file.

But in this Buffered way we perform that all task in single line :
Example:  Read a line from text file.

                        BufferedReader br = new BufferedReader(new FileReader("b.txt"));
System.out.println(br.readLine());
br.close();

Example: Write a Single line to a  text file.

                        BufferedWriter f = new BufferedWriter(new FileWriter("b.txt"));
f.write("Hello how are you Raj ?? !");
f.close();


  • Here in above example b.txt is the file name that in current working directory.
  • this example read and write only single line into specified text file.

To read multiple lines form text file you can use "while loop" like this : 


                          while((s = br.readLine()) != null){
                         //String[] c = s.split(",");
                           System.out.println(s);
                          } 

Note : When you perform file operation in java there is possibility to throw IOException or file not find Exception. So in java when you perform File operation or reading/writing You must have to include exception handling other wise it will gives you Error and code not be compiled.

*) To perform File reading/writing operation you must have ti import IO library first.
"import java.io.*;" 

The Full Example To read and Write to a text file in java with Exception handling. 
  • copy code make .java file
  • compile the code using javac command.
  • run the class file with java command.
Example : : :


import java.io.*;

class File{
public static void main(String[] args) throws IOException
{
//try{
BufferedWriter f = new BufferedWriter(new FileWriter("b.txt"));
f.write("Hello how are you Raj ?? !");
f.close();
BufferedReader br = new BufferedReader(new FileReader("b.txt"));
System.out.println(br.readLine());
br.close();
//}
//catch (IOException ex)
//{
//System.out.println("error");
//}
}
}

Output :





1 comment:

  1. If you find any error comment if i am here to solve it

    ReplyDelete

Comments

Bottom Ad [Post Page]

| Designed by Colorlib