I/O Example

I/O operation is important part in programming. Many time we have to read from file or files. Sometime we have to write down information or error message when executing program. Thou, database usage is high, still I/O operation is important.
To read input from user :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SimpleIOExample {

    public static void main(String[] args) throws IOException {

        InputStreamReader inp = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(inp);
        System.out.println("Enter text : ");
        String str = br.readLine();
        System.out.println("Your string was : "+str);

        FileInputStream fstream = new FileInputStream("20.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader bread = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = bread.readLine()) != null) {
            System.out.println(strLine);
        }
        in.close();
    }
}

The output will look something like :

Enter text : 
Java
Your string was : Java
Hello Java!

To write to the file :

 public static void main(String[] args) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter the file name to create : ");
        String file_name = in.readLine();
        File file = new File(file_name);
        boolean exist = file.createNewFile();

        if (!exist) {
            System.out.println("File already exists.");
            System.exit(0);
        } else {
            FileWriter fstream = new FileWriter(file_name);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(in.readLine());
            out.close();
            System.out.println("New file " + file_name + " has been created to the current directory");

            FileWriter appendStream = new FileWriter(file_name, true);
            BufferedWriter appendOut = new BufferedWriter(appendStream);
            appendOut.write("Hello Java");
            appendOut.close();
        }
    }

The output will look something like :

Please enter the file name to create : 2011.txt
New file 2011.txt has been created to the current directory

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.