AIM:
To perform file handling in Java. Take two filenames from user, check the file is present in c:\java folder, if not present, display the message “file not present” , else display the size and file name. Also display the file contents.
THEORY:
Objects of the File class can be created using File Constructors.
Constructors:
File f1=new File(“c:/java/temp.txt “);
File f1 = new File( “c:/java”, “temp.txt “);
File f1 = new File( “java”, “temp.txt “);
Methods are : f.getName( );f.getPath( );f.getAbsolutPath( );f.getParent( );f.exists( ); f.isFile( ); f.isDirectory( );f.canRead( );f.canWrite( );f.lastModified( );f.length( );f.delete( ); f.renameTo(f1); f.list( ); f.mkdir( );
A stream is a path of communication between the source of information and the destination. Methods of InputStream/Reader are : read( );skip( );available( );close( );mark( );reset( ); Methods of OutputStream/ Writer are : write( );flush( );close( );
ByteArrayInputStream class uses a byte array as its input source.
ByteArrayInputStream b = new ByteArrayInputStream(buf [ ]);
ByteArrayOutputStream class implements a buffer, which can be used as an OutputStream
ByteArrayOutputStream o =new ByteArrayOutputStream( );
This creates a buffer of 32 bytes to store the data.
ByteArrayOutputStream o =new ByteArrayOutputStream( int );
import java.io.*;
class prg {
public static void main( String arg [ ] ) throws IOException {
FileInputStream fi = new FileInputStream(“ “);
FileOutputStream fo = new FileOutputStream (“ “);
int size = fi.available( );
for( int i =0; i < size; i++ )
{
int m =fi.read( );
System.out.println( (char) m);
fo.write( m );
}
fo.close( );
fi.close( );
}
// using BuffredInputstream and BuffredOutputstream.
BuffredInputstream bi = new BuffredInputstream (fi);
BuffredOutputstream bo = new BuffredOutputStream( fo);
bo.flush( );
//using DataInputStream and DataOutputStream.
DataInputStream di = new DataInputStream( fi );
DataOutputStream do = new DataOutputStream( fo );
String line;
while( line =di.readLine( ) != null )
{
System.out.println(line);
do.writeBytes(line);
}
//using BufferedReader and BufferdWriter
BufferedReader br =new BufferedReader (new InputStreamReader (fi));
BufferedWriter bw =new BuffredOutputStream (new OutputStreamWriter (fo));
// using BuffredInputstream and BuffredOutputstream.
while (int a = System.in.read ()! = 13)
{
fo.write (a);
}
//using BufferedReader and DataOutputStream.
while (line=br.readLine! = null)
{
if (line. equals (“end”))
break;
else
{
String z;
do.writeBytes (z);
}
}
Leave a Reply