Modifying File Objects and Files

Download Report

Transcript Modifying File Objects and Files

Chapter - 11
Introduction to File and Streams
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
Defining a File
 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.
File Object
 The simplest Constructor
For a Folder
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”);
For a
Folder
 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
Method
Description
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.
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
 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”);
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
Accessing File Objects
 We can get information about a File object by using the following methods.
Method
Description
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.
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 1st January 1970 GMT. We can
use this value to construct an object of Date class (in java.util
package) and represent in date format
 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:”);
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);
}
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
Method
Description
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 The file represented by the current object will be renamed to
Path)
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.*;
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”);
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);
}
}
Streams
 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.
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:
Reading and Writing a Stream
 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
The Classes for Input/Output
 The java.io package contains a collection of stream classes that support these
algorithms for reading and writing.
 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
Using the Data Sink Streams
 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.
Sink Type
Character Streams
Byte Streams
Memory
CharArrayReader
CharArrayWriter
ByteArrayInputStream
ByteArrayOutputStream
StringReader
StringWriter
StringBufferInputStream
Sink Type
Character Streams
Byte Streams
Pipe
PipeReader
PipeWriter
PipedInputStream
PipedOutputStream
File
FileReader
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.
The following Copy program uses FileReader and FileWriter to copy the
contents of a file named farrago.txt into a file called outagain.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();
}
}
Same Previous program CopyBytes, which uses FileInputStream and
FileOutputStream in place of FileReader and FileWriter.
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();
}
}