wellnwill Marathahalli Bangalore

Input/Output Practice Sheet


import java.io.*;
class Test1
{
 public static void main(String args[]) throws Exception
 {
  File f1=new File("dheeraj.txt");
  System.out.println(f1.exists());
 }
}

import java.io.*;
class Test2
{
 public static void main(String args[]) throws Exception
 {
  File f1=new File("dheeraj.txt");
  f1.createNewFile();//need try catch or throws
  System.out.println(f1.exists());
  }
}


import java.io.*;
class Test3
{
 public static void main(String args[]) throws Throwable
 {
  File f1=new File("code");
  f1.mkdir();
  File f2=new File(f1,"program1");
  f2.createNewFile();
  System.out.println(f1.exists());
  System.out.println(f2.exists());
 }
}


import java.io.*;
class Test4{
 public static void main(String args[]) throws Throwable
 {
  FileWriter f1=new FileWriter("file1.txt",true);
  f1.write("dheeraj bajpai");
  f1.write("neeraj bajpai");
  f1.flush();
  f1.close();
 }
}
O/P- dheeraj bajpaidheeraj bajpaineeraj bajpai
FileWriter object is used to write character data to the file.
Note-here we have to use line separator(\n) explicitly. We use BufferedWriter and PrintWriter 
classes to overcome this issue.

import java.io.*;
import java.io.*;
class Test
{
 public static void main(String args[]) throws IOException
 {
  FileWriter f1=new FileWriter("file2.txt",true);
  f1.write("dheeraj bajpai\\n");
  f1.write('\n');
  f1.write("neeraj bajpai");
  char ch[]=new char[100];
  for(int i=65;i<70;i++)
	  ch[i]=(char)i;

  f1.write(ch);
  f1.flush();
  f1.close();
 }
}


import java.io.*;
class Test
{
 public static void main(String args[]) throws IOException
 {
  File f1=new File("file2.txt");
  FileReader f=new FileReader(f1);
  char ch[]=new char[(int)f1.length()];
  f.read(ch);
  for(char temp:ch)
  {
   System.out.println(temp);
  }
 }
}

import java.io.*;
class Test1
{
 public static void main(String args[]) throws IOException
 {
  File f1=new File("file2.txt");
  FileReader f=new FileReader(f1);
  int i=f.read();
  while(i!=-1)
  {
   System.out.println((char)i);
    i=f.read();
  }
}
}

import java.io.*;
class Test1
{
 public static void main(String args[]) throws IOException
 {
  File f1=new File("file2.txt");
  FileReader f=new FileReader(f1);
  int i;    
          while((i=fr.read())!=-1)    
          System.out.print((char)i);    
          fr.close();
 }
}

Note-FileReader object read the data character 
by character not line by line.

Footer with Map

Top