Wednesday, October 17, 2012

Java Tidbits ..........................(File I/O)

File f = new File(string str)

f is an instance of File object . It wont  create or delete any file  with the name  str on DISK.
it can be checked to see if there is any such file with the path name specified by str or not .
f.createNewFile() will craete the file in specified path  throws IOException
f.mkDir() is for making directories

To write into file FileWriter object is required
 FileWriter fow = new FileWriter(file instance , boolean  append );
new FileWriter(file instance );  // by default append  is false  & it will overwrite the file./string
FileWriter fow = new FileWriter(f,true);  // append at last 

FileOutputStream fops = new FileOutputStream(file ) // file or string
FileOutputStream fops = new FileOutputStream(f, append);

ways to write into file 

1) FileWriter fow fow = new FileWriter(f,true);       
       
        fow.append("Hello ");   
        fow.append("\nHow r u ?");
        fow.flush();
        fow.close();

//Note : FileWriter extends FileOutPutStream

2) FileOutputStream fops = new FileOutputStream(f, true);
        fops.write("My name is khan".getBytes());
        fops.flush();
        fops.close();

3) PrintWriter pos = new PrintWriter(file); // or string
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();

4) FileOutPutStream can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fops, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();


5) FileWriter can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fow, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close(); 


6)Pipe OutputStreamWriter to PrintWriter 
OutputStreamWriter opts = new OutputStreamWriter(fops);
        PrintWriter pos = new PrintWriter(opts, true);
        pos.write("Great!");

        pos.flush();
        pos.close();

No comments: