IO File Handling

Input Output File Handling:
  • File that provides the details about file or directory
  • InputStream, FileInputStream, DataInputStream, BufferedInputStream, ByteArrayInputStream, FilterInputStream, PipedInputStream, ObjectInputStream classes are used to read the byte stream of data into text files, byte array, deserialize the objects and various types of data from files.
  • OutputStream, FileOutputStream, DataOutputStream, ByteArrayOutputStream, FilterOutputStream, PipedOutputStream, ObjectOutputStream classes are used to write the byte stream of data into text files, byte array, serialize the objects and various types of data into files.
  • Reader, FileReader, InputStreamReader, BufferedReader, CharArrayReader, FilterReader, PipedReader, StringReader classes are used to read the character stream of data from files, char array and String.
  • Writer, FileWriter, OutputStreamWriter, BufferedWriter, CharArrayWriter, FilterWriter, PipedWriter, StringWriter classes are used to write the character stream of data to files, char array and String.



Example 1: Create a program that explain methods of File class?
package com.java.io;

import java.io.File;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("/home/anish");
        
        System.out.println("isAbsolute()? " + file.isAbsolute());
        System.out.println("isDirectory()? " + file.isDirectory());
        System.out.println("isHidden()? " + file.isHidden());
        System.out.println("isFile()? " + file.isFile());
        System.out.println("exists()? " + file.exists());
        System.out.println(file.getName() + " is a Directory");
        System.out.println(file.getAbsolutePath() + " is a Directory");
        System.out.println(file.getParent() + " is a parent Directory");
        System.out.println("Total space is " + file.getTotalSpace() / (1024 * 1024 * 1024) + " GB");
        System.out.println("Total free space is " + file.getFreeSpace() / (1024 * 1024 * 1024) + " GB");
        System.out.println("Total Usable space is " + file.getUsableSpace() / (1024 * 1024 * 1024) + " GB");
        System.out.println("canRead()? " + file.canRead());
        System.out.println("canWrite()? " + file.canWrite());
        System.out.println("canExecute()? " + file.canExecute());
        System.out.println("The length() in bytes is " + file.length());
        System.out.println("lastModified " + (System.currentTimeMillis() - file.lastModified())/(60*60*1000) + " hours before");
        System.out.println(File.separator + " is the File separator");
        System.out.println("-------------------"+file + " contains list of name of files and folders ------------------------");
        for (String name : file.list()) {
            System.out.print(name + " ");
        }
        
        System.out.println("\n-------------------"+file + " contains list of files and folders ------------------------");
        for (File name : file.listFiles()) {
            System.out.print(name + " ");
        }
    }
}

Output:
isAbsolute()? true
isDirectory()? true
isHidden()? false
isFile()? false
exists()? true
anish is a Directory
/home/anish is a Directory
/home is a parent Directory
Total space is 908 GB
Total free space is 671 GB
Total Usable space is 625 GB
canRead()? true
canWrite()? true
canExecute()? true
The length() in bytes is 4096
lastModified 1 hours before
/ is the File separator
-------------------/home/anish contains list of name of files and folders ------------------------
.gnome .gnupg .mozilla .oracle_jre_usage Public Videos workspace git .pki Hello.java .gimp-2.8 .gksu.lock .dmrc .dropbox .swt examples.desktop .local .mysql Music .xsession-errors.old .synaptic .xsession-errors Desktop .ICEauthority .config .bash_history Dropbox .adobe .Xauthority .gconf .compiz Hello.class Templates Downloads .cache .profile .dbus .gvfs .bashrc .sudo_as_admin_successful VirtualBox VMs .dropbox-dist .eclipse .bash_logout .java Documents .macromedia Pictures
-------------------/home/anish contains list of files and folders ------------------------
/home/anish/.gnome /home/anish/.gnupg /home/anish/.mozilla /home/anish/.oracle_jre_usage /home/anish/Public /home/anish/Videos /home/anish/workspace /home/anish/git /home/anish/.pki /home/anish/Hello.java /home/anish/.gimp-2.8 /home/anish/.gksu.lock /home/anish/.dmrc /home/anish/.dropbox /home/anish/.swt /home/anish/examples.desktop /home/anish/.local /home/anish/.mysql /home/anish/Music /home/anish/.xsession-errors.old /home/anish/.synaptic /home/anish/.xsession-errors /home/anish/Desktop /home/anish/.ICEauthority /home/anish/.config /home/anish/.bash_history /home/anish/Dropbox /home/anish/.adobe /home/anish/.Xauthority /home/anish/.gconf /home/anish/.compiz /home/anish/Hello.class /home/anish/Templates /home/anish/Downloads /home/anish/.cache /home/anish/.profile /home/anish/.dbus /home/anish/.gvfs /home/anish/.bashrc /home/anish/.sudo_as_admin_successful /home/anish/VirtualBox VMs /home/anish/.dropbox-dist /home/anish/.eclipse /home/anish/.bash_logout /home/anish/.java /home/anish/Documents /home/anish/.macromedia /home/anish/Pictures

Example 2: Create a program that explains FileInputStream and FileOutputStream classes?
package com.java.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileIOStream {
    public static void main(String[] args) {
        File file = new File("fileiostream.txt");
        FileOutputStream fos = null;;
        try {
            fos = new FileOutputStream(file);
            fos.write(97);
            fos.write('\n');
            
            String s = "Writing to text file";
            byte[] b = s.getBytes();
            fos.write(b);
            fos.write(10);
            
            byte[] a = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57};
            fos.write(a, 3, 5);
            System.out.println(file.getName() + " is updated successfully");
        } catch (IOException e) {
            System.out.println(file.getAbsolutePath() + " is not updated");
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("Exception occured while closing the files");
            }
        }
        
        System.out.println("--------------------Reading File Type 1------------------------");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            int ch;
            System.out.println(fis.available() + " bytes are available to read");
            System.out.println("is mark and reset is support or not? " + fis.markSupported());
            while((ch = fis.read()) != -1){
                System.out.print((char)ch);
            }
            //System.out.println(fis.available());
            System.out.println("\nReading " + file.length() + " bytes stream of data");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        System.out.println("--------------------Reading File Type 2------------------------");
        try {
            fis = new FileInputStream(file);
            byte[] b = new byte[(int)file.length()];
            int count = fis.read(b);
            if(count != -1){
                for (byte c : b) {
                    System.out.print((char)c);
                }
                System.out.println("\nReading " + count + " bytes stream of data");
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        System.out.println("--------------------Reading File Type 3------------------------");
        try {
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            int size = fis.read(b, 6, b.length - 6);
            if(size != -1){
                for (byte c : b) {
                    if(c != 0){
                        System.out.print((char)c);
                    }else{
                        System.out.print('*');
                    }
                }
                System.out.println("\nReading " + size + " bytes stream of data");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Output:
fileiostream.txt is updated successfully
--------------------Reading File Type 1------------------------
28 bytes are available to read
is mark and reset is support or not? false
a
Writing to text file
34567
Reading 28 bytes stream of data
--------------------Reading File Type 2------------------------
a
Writing to text file
34567
Reading 28 bytes stream of data
--------------------Reading File Type 3------------------------
******a
Writing to text file
Reading 22 bytes stream of data

Example 3: Create a program that explains BufferedInputStream and BufferedOutputStream classes?
package com.java.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BufferedIOStream {
    public static InputStream is;
    public static OutputStream os;
    public static BufferedInputStream bis;
    public static BufferedOutputStream bos;
    public static File file;
    
    public static void main(String[] args) throws IOException {
        os = new FileOutputStream("bufferio.txt");
        bos = new BufferedOutputStream(os);
        
        bos.write(48);
        bos.write(new byte[]{49, 50, 51, 52, 53, 54, 55, 56, 57});
        bos.write(new byte[]{97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108}, 3, 6);
        bos.flush();
        System.out.println("file is written successfully");
        os.close();
        bos.close();
        
        System.out.println("---------------Reading Type 1--------------");
        file = new File("bufferio.txt");
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        
        int b;
        while( (b = bis.read()) != -1 ){
            System.out.print((char) b);
        }
        
        is.close();
        bis.close();
        
        System.out.println("\n---------------Reading Type 2--------------");
        file = new File("bufferio.txt");
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        
        byte[] buf = new byte[bis.available()];
        bis.read(buf);
        for (byte c : buf) {
            System.out.print((char) c);
        }
        is.close();
        bis.close();
        
        System.out.println("\n---------------Reading Type 3--------------");
        file = new File("bufferio.txt");
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        
        byte[] buff = new byte[bis.available()];
        bis.read(buff, 3, 7);
        for (byte c=0; c < buff.length; c++) {
            if(buff[c] == 0){
                System.out.print('*');
            } else{
                System.out.print((char) buff[c]);
            }
        }
        
        System.out.println("\n" + bis.available() + " bytes are still available");
        System.out.println(bis.skip(3) + " bytes are skipped");
        byte[] arr = new byte[bis.available()];
        bis.read(arr);
        for (byte c : arr) {
            System.out.print((char) c);
        }
        is.close();
        bis.close();    
    }
}

Output:
file is written successfully
---------------Reading Type 1--------------
0123456789defghi
---------------Reading Type 2--------------
0123456789defghi
---------------Reading Type 3--------------
***0123456******
9 bytes are still available
3 bytes are skipped
defghi

Example 4: Create a program that explains FileReader and FileWriter classes?
package com.java.io;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriter {
    public static FileReader fr;
    public static FileWriter fw;
    public static File file;
    public static void main(String[] args) {
        
        try {
            file = new File("filerw.txt");
            if(!file.exists()){
                file.createNewFile();
            }
            //fw = new FileWriter("a.txt");
            fw = new FileWriter(file);
            fw.write(65);
            fw.append("\n");
            fw.write("xyz");
            fw.write(10);
            fw.write(new char[]{'p''q''r''s''t'});
            fw.append('\n');
            fw.append("abcdefgh", 2, 5);
            fw.write(10);
            fw.write(new char[]{'j''k''l''m''n''o''p''q''r'},  3, 5);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        try {
            fr = new FileReader(file);
            int ch;
            while((ch = fr.read()) != -1){
                System.out.print((char)ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        System.out.println("\n---------------Reading Type 2--------------");
        try {
            fr = new FileReader(file);
            char[] ch = new char[(int)file.length()];
            fr.read(ch);
            System.out.print(ch);
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        System.out.println("\n---------------Reading Type 3--------------");
        try {
            fr = new FileReader(file);
            char[] ch = new char[(int)file.length()];
            fr.read(ch, 2, 19);
            for (byte c=0; c < ch.length; c++) {
                if(ch[c] == 0){
                    System.out.print('*');
                } else{
                    System.out.print((char) ch[c]);
                }
            }
            System.out.println("\nCharacter encoding is " + fr.getEncoding());
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:
A
xyz
pqrst
cde
mnopq
---------------Reading Type 2--------------
A
xyz
pqrst
cde
mnopq
---------------Reading Type 3--------------
**A
xyz
pqrst
cde
mno
Character encoding is UTF8

Example 5: Create a program that explains BufferedReader and BufferedWriter classes?
package com.java.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderWriter {
    private static File file;
    private static BufferedReader br;
    private static BufferedWriter bw;
    
    public static void main(String[] args) throws IOException {
        file = new File("/home/anish/workspace/Java Basics/bufferedrw.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        bw = new BufferedWriter(new FileWriter(file), 10);
        bw.write(new char[]{'A''B''C''D''E''F''G''H''I''J''K''L''M''N''O'});
        bw.close();
        
        InputStream in = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(in);
        br = new BufferedReader(isr,10);
        char[] ch = new char[in.available()];
        br.read(ch);
        for (char c : ch) {
            System.out.print(c);
        }
    }
}

Output: 
ABCDEFGHIJKLMNO

Example 6: Create a program that explains Serialization and Deserialization of objects?
package com.java.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationDeserialization {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileOutputStream fos = new FileOutputStream("abc.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        
        oos.writeObject(new String("abcd1234"));
        oos.writeByte(49);
        oos.writeBoolean(true);
        oos.writeShort(280);
        oos.writeInt(456678911);
        oos.writeLong(123456789654789L);
        oos.writeFloat(68.6f);
        oos.writeDouble(123.45);
        byte[] buff = {'a''b''c''d''e''f'};
        oos.write(buff);
        oos.write(buff, 2, 4);
        oos.write(122);
        
        System.out.println("-----------------Serialization completed---------");
        oos.close();
        
        FileInputStream fis = new FileInputStream("abc.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        System.out.println("-----------------Deserialization-----------------");
        System.out.println("readObject() -> " + ois.readObject());
        System.out.println("readByte() -> " + ois.readByte());
        System.out.println("readBoolean() -> " + ois.readBoolean());
        System.out.println("readShort() -> " + ois.readShort());
        System.out.println("readInt() -> " + ois.readInt());
        System.out.println("readLong() -> " + ois.readLong());
        System.out.println("readFloat() -> " + ois.readFloat());
        System.out.println("readDouble() -> " + ois.readDouble());
        byte[] b = new byte[6];
        ois.read(b);
        System.out.print("read(b) -> ");
        for (byte c : b) {
            System.out.print( (char)c);
        }
        System.out.println();
        
        b = new byte[6];
        ois.read(b, 1, 2);
        System.out.print("read(b, 1, 2) -> ");
        for (byte c : b) {
            if(c==0)
                System.out.print("*");
            else
                System.out.print( (char)c);
        }
        System.out.println();
        
        System.out.println(ois.skip(2) + " bytes is skipped");
        System.out.println("read() -> " + (char)ois.read());
        
        ois.close();
    }
}

Output:
-----------------Serialization completed---------
-----------------Deserialization-----------------
readObject() -> abcd1234
readByte() -> 49
readBoolean() -> true
readShort() -> 280
readInt() -> 456678911
readLong() -> 123456789654789
readFloat() -> 68.6
readDouble() -> 123.45
read(b) -> abcdef
read(b, 1, 2) -> *cd***
2 bytes is skipped
read() -> z

Example 7: Create a program that explains reading and writing Properties file?
package com.java.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class PropertiesDemo {
    private static File file;
    private static OutputStream  os;
    private static Reader reader;
    private static Properties prop;
    public static void main(String[] args) throws IOException {
        file = new File("output.properties");
        os = new FileOutputStream(file);
        prop = new Properties();
        prop.setProperty("user""admin");
        prop.setProperty("password""test123");
        prop.setProperty("mobile""7866525544");
        prop.setProperty("email""abcdef@gmail.com");
        prop.setProperty("city""Bengaluru");
        prop.store(os, "");
        os.close();

        System.out.println("------------Reading Properties File type 1----------------");
        reader = new FileReader(file);
        prop.load(reader);
        Enumeration en = prop.elements();
        while(en.hasMoreElements()){
            System.out.println(en.nextElement());
        }
        
        System.out.println("------------Reading Properties File type 2----------------");
        Set keys = prop.keySet();
        Iterator itr = keys.iterator();
        while(itr.hasNext()) {
            String key = (String)itr.next();
            System.out.println(key + " = " + prop.getProperty(key));
        }
    }
}

Output:
------------Reading Properties File type 1----------------
admin
abcdef@gmail.com
7866525544
test123
Bengaluru
------------Reading Properties File type 2----------------
user = admin
email = abcdef@gmail.com
mobile = 7866525544
password = test123
city = Bengaluru

Example 8: Create a program that explains reading and writing Image file using ImageIO and BufferedImage?
package com.java.io;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

public class ReadingImage {
    private static File file;
    private static InputStream is;
    public static void main(String[] args) throws IOException {
        file = new File("Taj.jpeg");
        is = new FileInputStream(file);
        byte[] ch = new byte[80];
        while( is.read(ch) != -1 ){
            for (byte b : ch) {
                System.out.print((char)b);
            }
            System.out.println();
        }
        is.close();
        
        is = new FileInputStream(file);
        BufferedImage img = ImageIO.read(is);
        int width = img.getWidth();
        int height = img.getHeight();
        
        int p, a, r, g, b, avg;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                p = img.getRGB(i, j);
                
                a = (p >> 24) & 0xff;
                r = (p >> 16) & 0xff;
                g = (p >> 8) & 0xff;
                b = (p >> 0) & 0xff;
                
                avg = (r + g + b)/3;
                
                p = (a << 24) | (avg << 16) | (avg << 8) | (avg << 0);
                
                img.setRGB(i, j, p);
            }
        }
        File f = new File("GrayScaleTaj.jpeg");
        ImageIO.write(img, "jpeg", f);
        System.out.println(f + " is successfully created");
        is.close();
    }
}

Example 9: Create a program that explains reading and writing HTML file?
package com.java.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ReadingWebURL {
    static URL url;
    static InputStream in;
    public static void main(String[] args) throws IOException {
        url = new URL("https://www.google.co.in/");
        
        File file = new File("Hello.html");
        if(!file.exists()){
            file.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write("<html>\n<head>\n<title>Hello World in Html</title>\n</head>");
        bw.write("\n<body>\n<h1>Hello World!</h1>\n</body>\n</html>");

        bw.close();
        url = new URL("https://facebook.com");
        url = new URL("file:///home/anish/workspace/Java Basics/Hello.html");
        
        in = (InputStream)url.openStream();
        int b;
        while( (b = in.read()) != -1){
            System.out.print( (char) b);
        }
    }
}


Output: 
<html>
<head>
<title>Hello World in Html</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

No comments:

Post a Comment