Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.

Similar presentations


Presentation on theme: "Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects."— Presentation transcript:

1

2 Chapter - 11 Introduction to File and Streams

3 This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects  Modifying File Objects and Files  Understanding Streams  Stream Input/Output  The Classes for Input and Output  FileInputStream  FileOutputStream

4  A File object represents a pathname to a physical file or directory on your hard drive  When creating File Objects, you have a choice of three constructors.  The simplest Constructor File myDir= new File ( “F:/jdk1.3/bin”); File sourceFile = new File (“F:/jdk1.3/bin/test.java”);  The second constructor of File class accepts two arguments. File myDir = new File ( “F:/jdk1.3/bin”); File myFile= new File(mydir, “test.java”); Defining a File File Object For a Folder For a Folder

5  The third constructor File myFile = new File (“F:/jdk1.3/bin”, “test.java”); The File class provides a whole bunch of methods that you can apply to File objects. Testing and Checking File Objects MethodDescription exists()Returns true if the file or directory referred to by the File object exists and false otherwise. isDirectory()Returns true if the File object refers to a directory and false otherwise. isFile()Returns true if the File object refers to a file and false otherwise.

6  Let us try the above methods. import java.io.*; import javax.swing.*; public class TryFile{ public static void main (String args[]){ File myDir=new File ( “F:/jdk1.3/bin”); if (myDir.isDirectory()==true) JOptionPane.showMessageDialog(null,myDir+”is a directory”); else JOptionPane.showMessageDialog(null,myDir+”is not a directory”); canRad()Returns true if you are permitted to read the file referred to by the File object and false otherwise canWrite()Returns true if you are permitted to writethe file referred to by the File object and false otherwise

7 File myFile=new File (myDir, “test.java”); if (myFile.exists()==true) JOptionPane.showMessageDialog(null, myFile+”does exist”); else JOptionPane.showMessageDialog(null, myFile+”does not exist”); if (myFile.canRead()==true) JOptionPane.showMessageDialog(null, “You can read “+myFile); else JOptionPane.showMessageDialog(null, “You can not read ”+myFile); if (myFile.canWrite()==true) JOptionPane.showMessageDialog(null, “You can write “+myFile); else JOptionPane.showMessageDialog(null, “You can not write ”+myFile);  On my machine, the above example produces the output: F:/jdk1.3/bin is a directory F:/jdk1.3/bin/test.java does exist You can read F:/jdk1.3/bin/test.java You can write F:/jdk1.3/bin/test.java

8  We can get information about a File object by using the following methods. Accessing File Objects MethodDescription getName()Returns a String object containing the name of the file without the path. For a File Object representing a directory, just the directory name is returned. getPath()Returns a String object containing the path for the File object including the file or directory name. length()Returns a value of type long that is the length in bytes of the file represented by the current File object. list()If the current File object represents a directory, a String array is returned containing the names of the members of the directory. listFiles()If the current File object represents a directory, it returns an array of File objects corresponding to the files and directories in that directory. listRoots()This static returns an array of File objects, each element in the array corresponding to a root directory in the file system.

9  You can list all the root directories on a system with the code: File [] roots =File.listRoots(); for (int i=0;i<roots.length;i++) System.out.println(“Root directory “+i+”: “+roots[i]);  We can list all the files in a directory and when they were last modified with the following program: import java.io.*; import java.util.*; import javax.swing.*; class tryFile2{ public static void main (String args[]) { String name = JOptionPane.showInputDialog(“Directory Name:”); lastModified()Returns a value of type long that represents the time that the directory or file was last modified. This time is the number of milliseconds since midnight on 1 st January 1970 GMT. We can use this value to construct an object of Date class (in java.util package) and represent in date format

10 File myDir = new File (name); if (myDir.isDirectory()==true) JOptionPane.showMessageDialog(null,myDir+” is a directory”); else JOptionPane.showMessageDialog(null,myDir+” is not a directory”); File contents [ ] = myDir.listFiles(); if(contents != null){ String output=“”; output=output+ “The “+ contents.length+” items in the directory “+myDir.getName() +” are:”; for (int i=0;i<contents.length ; i++){ if (contents[i].isDirectory()) output=output+contents[i]+” is a directory”; else output=output+contents[i]+” is a file”; Date d = new Date( contents[i].lastModified()); output=output+” last modified “ + d); } JOptionPane.showMessageDialog(null, output);

11 } else JOptionPane.showMessageDialog(null, myDir.getName()+” is not a directory”); System.exit(0); } Modifying File Objects and Files  There are several methods defined in the File class that you can use to change a File objects. Some of heavily used methods are listed below

12 MethodDescription delete()This will delete the file or directory represented by the current File object and return true if the delete was successful. It won’t delete directories that are not empty. renameTo(File Path) The file represented by the current object will be renamed to the path represented by the File object, passed as an argument to the method. If the operation is successful, true will be returned. Otherwise, false will be returned. mkDir()Creates a directory with the path specified by the current File object. The method returns true if it is successful and false otherwise.  Let us write a program that will take a filename as input and will delete it, then it will take another file name and will rename it to a given name and finally it will take a directory name and will create the directory. import java.io.*; import javax.swing.*;

13 class filetest{ public static void main (String args[]){ String name=JOptionPane.showInputDialog(“Which file to delete”); File f =new File(name); boolean b = f.delete(); if (b==true) JOptionPane.showMessageDialog(null, f + “is deleted successfully”); else JOptionPane.showMessageDialog(null, f + “ was not deleted”); String name1= JOptionPane.showInputDialog(“Which file to rename”); String name2= JOptionPane.showInputDialog(“New name”); File f1 = new File (name1); File f2 = new File(name2); boolean b2= f1.renameTo(f2); if (b==true) JOptionPane.showMessageDialog(null, “Rename successful”); else JOptionPane.showMessageDialog(null, “ Rename unsuccessful”);

14 String name3=JOptionPane.showInputDialog(“Directory to create”); File f3 =new File(name3); boolean b3 = f.mkdir(); if (b==true) JOptionPane.showMessageDialog(null, f + “is created successfully”); else JOptionPane.showMessageDialog(null, f + “ was not created”); System.exit(0); }

15  Often programs need to bring in information from an external source or send out information to an external destination.  The information can be anywhere: in a file, on disk, somewhere on the network, in memory, or in another program.  Also, it can be of any type: objects, characters, images, or sounds. Streams Stream Input/Output  To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information serially, like this:  Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out serially, like this:

16  No matter where the information is coming from or going to and no matter what type of data is being read or written, the algorithms for reading and writing data is pretty much always the same.  Reading open a stream while more information read information close the stream  Writing open a stream while more information write information close the stream Reading and Writing a Stream

17  The java.io package contains a collection of stream classes that support these algorithms for reading and writing. java.io  These classes are divided into two class hierarchies based on the data type (either characters or bytes) on which they operate.  Character Streams  Byte Streams The Classes for Input/Output  Data sink streams read from or write to specialized data sinks such as strings, files, or pipes. Typically, for each reader or input stream intended to read from a specific kind of input source, java.io contains a parallel writer or output stream that can create it. The following table gives java.io 's data sink streams. Using the Data Sink Streams Sink TypeCharacter StreamsByte Streams MemoryCharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream StringReader StringWriter StringBufferInputStream

18 Sink TypeCharacter StreamsByte Streams PipePipeReader PipeWriter PipedInputStream PipedOutputStream FileFileReader FileWriter FileInputStream FileOutputStream How to use File Streams  File streams are perhaps the easiest streams to understand. Simply put, the file streams-- FileReader, FileWriter, FileInputStream, and FileOutputStream --each read or write from a file on the native file system.FileReader FileWriter FileInputStream FileOutputStream

19  The following Copy program uses FileReader and FileWriter to copy the contents of a file named farrago.txt into a file called outagain.txt:Copyfarrago.txt import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }

20  Same Previous program CopyBytes, which uses FileInputStream and FileOutputStream in place of FileReader and FileWriter.CopyBytes import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }


Download ppt "Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects."

Similar presentations


Ads by Google