FILE HANDLING

The File class is essentially a file descriptor which allows you to get a handle on the file, but doesn't in and of itself have methods to read the information from the file.

That is where the InputStreamReader comes in. An InputStreamReader (and more easily its subclass the FileReader) will do the reading for you (there are other ways to do it, but this is one of the easiest).

The BufferedReader will wrap the InputStreamReader and will read the file into a buffer (rather than simply converting and returning the bytes after every read invocation) allowing you to more easily read in the data.

   Ex:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
23
24
26
27
import java.io.PrintWriter;
import  java.io.StringWriter;
public static String log(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw,  true);
        exp.printStackTrace(pw);
        pw.flush();
        sw.flush();
        writeLog("exception"+ sw.toString());
    }
public void writeLog(String msg)
    {
        try
            {
                BufferedWriter out = new
                BufferedWriter(new  FileWriter("D:\\log\\stack.log",true));
                out.write(msg+"n");
                out.close();
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
    }

 Ex:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import  java.io.*;
class  HelloWorld2
    {
        // Create BufferedReader class instance
        static InputStreamReader input = new InputStreamReader(System.in);
        static BufferedReader keyboardInput = new BufferedReader(input);
        /* Main method*/
        public static void main(String[] args)  throws IOException
            {
                String name;   
                System.out.print("What is your  name? ");  
                name = keyboardInput.readLine();   
                System.out.print("\nHello " +  name ); 
            }
    }