Wednesday, August 2, 2023

Java STREAMS AND FILES - I

 

STREAMS AND FILES  - I

FILE:

Permanent Storage of data.

          File (String directoryPath)

          File(String directoryPath,String filename)

         File (File dirObj,String filename)

File f1=new File(“/”);

File f2=new File(“/”,”autoexec.bat”);

File f3=new File(f1,“autoexec.bat”);

 

Methods of file class:

                 Methods

           Description

        getName()

Returns the name of the file,

        getParent()

Return the name of the parent directory

      exists()

Return true if called on a file and false if called on a directory. Also, is File() returns false for some special files, such as device drivers and named pipes, so this method can be used to make sure the file will behave as a file.

    isAbsolute()

Returns true if the file has an absolute  path and false if its path is relative.

 

Þ     Example

First create a new file called COPYRIGHT under a new folder called java.

//Demonstrate File.

import java.io.File;

class FileDemo{

     static void p(String s){

         System.out.println(s);

}

public static void main(String args[]){

File f1=new File("C:/Program Files/Java/jdk1.8.0_181/COPYRIGHT");

p("File Name:"+f1.getName());

p("Path:"+f1.getPath());

p("Abs Path:"+f1.getAbsolutePath());

p("Parent:"+f1.getParent());

p(f1.exists()?"exists":"does not exist");   

p(f1.canWrite()?"isWriteable": "is not readable ");

p(f1.canRead()?"isreadable":"is not readable");

p("is"+(f1.isDirectory()?"":"not"+"a directory"));

p(f1.isFile()?"is normal file":"might be a named pipe");

p(f1.isAbsolute()?"is absolute":"is not absolute");

p("File last modified:"+f1.lastModified());

p("File size:"+f1.length()+"Bytes");

    }

}


Þ     The output appears as given below:

If not exists output will be


If file is exists output will be



Þ     Example

File name: FileMethods2.java

import java.io.*;

class FileMethods2{

  public static void main(String args[]){

String dirname="E:/ja/file";

File a=new File(dirname);

     for(int i=0;i<args.length;i++){

          File f=new File(args[i]);

         File f1=new File("E:/ja/renfile.txt");

if(a.exists()){

 System.out.println(a+"does exists.");

 System.out.println("Its size is"+a.length()+"bytes"); 

a.renameTo(f1);

System.out.println("Renamed file name:"+"bytes");

System.out.println("deleting the renamed file"+f1);

        System.out.println("=====================");

       f1.delete();

}

else

     System.out.println(a+"does not exists");

}

  }

    }

ÞExample

//Using directories to list the contents of a directory

//Insted of"java"use"."to view current directory

File name: DirList.java

import java.io.File;

class DirList{

    public static void main (String args[]){

     String dirname="C:/Program Files/Java";

     File f1=new File(dirname);

 

if(f1.isDirectory()){

 System.out.println("Directory of"+dirname);

String s[]=f1.list();

for(int i=0;i<s.length;i++){

  File f= new File (dirname+"/"+s[i]);

if(f.isDirectory()){

  System.out.println(s[i]+"is a directory");

}else{

     System.out.println(s[i]+"is a file");

       }

}

}   else{

System.out.println(dirname+"is not a directory");

    }

 }

}

The output you see Wil be different, based on what is in your directory:

 

CREATING DIRECTORIES:

The mkdir()method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. To create a directory for which no path exists, use the mkdir() method. It creates both a directory both a directory and all the parents of the directory.

Example

File name: FileDemo.java

import java.io.File;

import java.io.IOException;

import java.util.Scanner;

public class FileDemo {

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

        Scanner reader = new Scanner(System.in);

        boolean success = false;

        System.out.println("Enter path of directory to create");

        String dir = reader.nextLine();

 

        // Creating new directory in Java, if it doesn't exists

        File directory = new File(dir);

        if (directory.exists()) {

            System.out.println("Directory already exists ...");

        } else {

            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();

            if (success) {

                System.out.printf("Successfully created new directory : %s%n", dir);

            } else {

                System.out.printf("Failed to create new directory: %s%n", dir);

            }

        }

        // Creating new file in Java, only if not exists

        System.out.println("Enter file name to be created ");

        String filename = reader.nextLine();

        File f = new File(filename);

        if (f.exists()) {

            System.out.println("File already exists");

        } else {

            System.out.println("No such file exists, creating now");

            success = f.createNewFile();

            if (success) {

                System.out.printf("Successfully created new file: %s%n", f);

            } else {

                System.out.printf("Failed to create new file: %s%n", f);

            }

        }

        // close Scanner to prevent resource leak

        reader.close();

 

    }

}

Output

 


Program

File name: OnlyExt.java

import java.io.*;

public class OnlyExt implements FilenameFilter{

 String ext;

public OnlyExt(String ext){

    this.ext="."+ext;

}

 public boolean accept(File dir,String name){

        return name.endsWith(ext);

  }

}

The modified directory listing program is shown here. Now it will only display file that use the.html extension.

          //Directory of.java files.

File name: DirListOnly.java

import java.io.*;

class DirListOnly{

   public static void main (String args[]){

         String dirname=".";

          File f1=new File(dirname);

           FilenameFilter only=new OnlyExt("java");

            String s[]=f1.list(only);

             for (int i=0; i<s.length;i++){

                 System.out.println(s[i]);

                     }

               }

}

 

Output

 


The listFiles() Alternative

File[] listFiles()

File[] listFiles(FilenameFilter FFObj)

File[] listFiles (FileFilter FObj)

The Stream Classes

TYPES OF INPUT STREAM

 CLASS

FUNCTION

CONSTRUCTOR ARGUMENTS

ByteArrayInputStream

Allows a buffer in memory Input Stream

How to use it The buffer from which to extract the bytes.

StringBufferInputStream

Converts a String into an

Input Stream

A String. The underlying implementation actually uses a String Buffer. As a source of data. Connect it to a Filter Input Stream object to provide a useful interface

FileInputStream

For reading information from a file

A String representing the file name, or a File or File Descriptor Object As a source of data. Connect it to a Filter Input Stream Object to provide a useful interface.

 

 

File Stream

File Stream consists of the File Input Stream and File Out Stream

File Input Stream

The File Input Stream class creates an Input Stream that you can use to read bytes from a file. Its two most common constructors are shown here:

File InputStream(String filepath)

File InputStream (File fileObj)

//WRITING BYTES FROM A FILE

File name: WriteBytes.java

import java.io.*;

class  WriteBytes

{

           public static void main (String args[])

           {

                 //Declare and initialize a byte array

byte cities[]={'D','e','l','h','i','\n','C','h','e','n','n','a','i','\n','L','o','n','d','o','n','\n'};

                 //Create an output file stream

                  FileOutputStream ofile=null;

                   try

                {

                         //Connect the out file stream to "city.txt"

                          ofile = new FileOutputStream("city.txt");

                          //Write data to the Stream

                         ofile.write (cities);

                         ofile.close();

              }

             catch(IOException ioe)

              {

                        System.out.println(ioe);

                        System.exit(-1);

              }

         }

}

Output

 


 IN FILE OUTPUT WILL BE



//READING BYTES FROM A FILE

File name: ReadBytes.java

import java.io.*; 

public class ReadBytes { 

     public static void main(String args[]){   

          try{   

            FileInputStream fin=new FileInputStream("E:/ja/city.txt");   

            int i=0;   

            while((i=fin.read())!=-1){   

             System.out.print((char)i);   

            }   

            fin.close();   

          }catch(Exception e){System.out.println(e);}   

         }   

        } 


Output



 

Byte Array Stream

    This stream consists of Byte Array Input Stream and Byte Array Output Stream.

Byte Array Input Stream

Byte Array Input Stream is an implementation of an input stream that uses a byte array as the source. This class has two constructors.

Byte Array Input Stream (byte array[])

Byte Array Input Stream (byte array[], int start, int num Bytes)

 

File Output Stream

File OutputStream(String filePath)

File OutputStream(String fileobj)

File OutputStream(String filePath,boolean append)

Example

File name: ByteArrayInputStreamReset.java

import java.io.*;

class ByteArrayInputStreamReset{

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

String tmp ="abc";

byte b[] = tmp.getBytes();

ByteArrayInputStream in = new ByteArrayInputStream(b);

for (int i=0;i<2;i++){

int c;

while ((c = in.read())!=-1){

if (i==0)

{

System.out.print((char)c);

}

else

{ 

System.out.print(Character.toUpperCase((char)c));

}

}

System.out.println();

in.reset();

}

}

}

OUTPUT



ByteArrayOutputStream:

ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the destination.

Byte Array Output Stream()

Byte Array Output.Stream(int num Bytes)

/*program to accept a specific number of characters as input and convert them into uppercase characters*/

File name: ByteArray.java

import java.io.*;

class ByteArray

{

public static void main (String args[])throws Exception

{

ByteArrayOutputStream  f=new ByteArrayOutputStream(12);

System.out.println("Enter 10 characters and press the enter key");

System.out.println("These will be converted to uppercase and displayed");

while(f.size()!=10)

{

  f.write(System.in.read());

  }

 System.out.println("Accepted characters into an array");

 byte b[]= f.toByteArray();

 System.out.println("Displaying characters in the array");

 for(int l= 0;l<b.length;l++)

 {

 System.out.println((char)b[l]);

 }

ByteArrayInputStream inp=new ByteArrayInputStream(b);

int c;

 System.out.println("Converted to uppercase characters");

 for (int i=0;i<1;i++)

 {

while ((c = inp.read())!=-1)

{

System.out.println(Character.toUpperCase((char)c));

}

System.out.println();

 inp.reset();

 }

 }

        }

OUTPUT



Buffered Byte Stream

Buffered Input Stream

Example for Concatenating and Buffering:

File name: SequenceBuffer.java

import java.io.*;

class SequenceBuffer {

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

         //Declare file streams

          FileInputStream file1=null;

          FileInputStream file2=null;

         //Declare file 3 to store combined files

        SequenceInputStream file3 = null;

        //Open files to be Concatenated

         file1 = new FileInputStream ("text1.txt");

           file2 = new FileInputStream ("text2.txt"); 

         //Concatenate file 1 and file 2 into file 3

          file3 = new SequenceInputStream(file1,file2);

         //create buffered input and output streams

        BufferedInputStream inBuffer = new BufferedInputStream(file3);

        BufferedOutputStream outBuffer = new  BufferedOutputStream(System.out);

        //Read and write till the end of buffers

        int ch;

        while ((ch = inBuffer.read())!=-1)

        {

                 outBuffer.write((char)ch);

      }

     inBuffer.close();

     outBuffer.close();

     file1.close();

     file2.close();

       }

  }


Output



Data Output Stream

Example for Concatenating and Buffering

File name: DataStream.java

import java.io.*;

class DataStream{

   public static void main (String args[]){

       //declare data Streams    

         DataInputStream dis = null;  //Input Stream

                   DataOutputStream dos = null;  //output Stream

      //Construct a file

      File intfile=new File("rand.dat");

      //Writing integers to rand.dat

      try

{

     //create output stream for intfile file

    dos=new DataOutputStream(new FileOutputStream(intfile));

    for(int i=0;i<20;i++)

           dos.writeInt((int)(Math.random()*100));

}

catch(IOException ioe)

{

       System.out.println(ioe.getMessage());

}

finally

{

      try

      {

                  dos.close();

      }

catch(IOException ioe){}

}

//Reading integers from rand.dat file

try

{

//create input stream for intfile file

dis=new DataInputStream(new FileInputStream(intfile));

for(int i=0;i<20;i++)

  {

      int n=dis.readInt();

      System.out.print(n+"");

  }

}

catch(IOException ioe)

{

System.out.println(ioe.getMessage());

}

finally

{

      try

      {

               dis.close();

      }

      catch(IOException ioe) {}

      }

}

}

Output

 


Print Stream

         The methods of this class widely used in java applications. the two methods that are very familiar to use as are system.out.println()

and system.out.print().the system.err method is used to print error messages and system.in

is an input stream

Random Access File

 Random Access File(File fileobj,string access)throws IOException

Random Access File(String filename,string access)throws IOException

void seek(long newPos)throws IOException

EXAMPLE:1      

File name: RandomAccess.java

import java.io.*;

class RandomAccess

{

  public static void main(String[] args)

 {

 RandomAccessFile rfile;

  try

 {

 rfile=new RandomAccessFile("city.txt","rw");

rfile.seek(rfile.length());

rfile.writeBytes("Mumbai\n");

rfile.writeBytes("Chennai\n");

rfile.writeBytes("Coimbatore\n");

rfile.close();

}

catch(IOException io)

{

             System.out.println(io);

}

}

}

 

Output

 




Stream Tokenizer

  stream Tokenizer break up the InputStream into tokens that are delimited by sets of Character. It has this constructor.

 

EXAMPLE:2

File name: WordCounter.java

import java.io.*;

public class WordCounter{

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

FileReader fr=new FileReader("E:/ja/city.txt");

StreamTokenizer input=new StreamTokenizer(fr);

int tok;

int count=0;

while((tok=input.nextToken() ) !=StreamTokenizer.TT_EOF)

if(tok==StreamTokenizer.TT_WORD){

        System.out.println("Word Found :"+input.sval);

        count++;

}

System.out.println("Found"+count+" words in temp.txt");

}

}

Output

 


0 comments:

Post a Comment