Sunday, September 9, 2012

Streams in Java


Java Streams has following abstract classes:
InputStream , OutputStream , Reader and Writer

IO Streams: Designed for byte streams
Reader and Writer: Character Streams

Writing to File Using Java Programming Language


package com.io;

import java.io.*;
import java.util.Scanner;

public class FileWrite {

public static void main(String args[]){

try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");

//Passing File name to File Class
String file=br.readLine();
File fname = new File(file);

boolean exist=fname.createNewFile();

                       //Verifying file exists or not ..
if(!exist){
System.out.println("File already exists");
System.exit(0);
}
else
{
FileWriter fwrite=new FileWriter(file);
BufferedWriter bwr=new BufferedWriter(fwrite);
bwr.write(br.readLine());
bwr.close();

System.out.println("Successfully created");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:
========
Enter File name
Hello.txt
Hello first file
Successfully created