Showing posts with label IOStream. Show all posts
Showing posts with label IOStream. Show all posts

Sunday, September 9, 2012

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

Reading File in Java Using Java Programming


package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}

Output:
==========
Hi,
This is first file for reading
Thanks