Sie sind auf Seite 1von 36

Core Java Programming

12/29/08 1
List of Contents

 Java I/O
 File
Class
 Character and Byte Streams

 Working with File Streams


 Using FileReader and FileWriter
 Using FileInputStream and FileOutputStream

12/29/08 2
java.io.File

 An abstract representation of file and


directory pathnames.
 User interfaces and operating systems
use system-dependent pathname strings
to name files and directories. This class
presents an abstract, system-
independent view of hierarchical
pathnames.

12/29/08 3
… Continued

 An abstract pathname has two


components:
 An optional system-dependent prefix string,
such as a disk-drive specifier, "/" for the
UNIX root directory, or "\\" for a Win32 UNC
pathname, and
 A sequence of zero or more string names.

12/29/08 4
MyFileTest.java
 import java.io.*;

 public class MyFileTest


 {
 public static void main(String[] args) throws IOException
 {
 if (args.length==0)
 {
 System.out.println("Usage Syntax: java
MyFileTest <Dir/File Name>");
 }
 else
 {
 File inputFile = new File(args[0]);
 System.out.println("The File Name: " +
inputFile.getName());
 System.out.println("The File Path: " +
inputFile.getAbsolutePath());
 System.out.println("Is Directory?: " +
inputFile.isDirectory());

12/29/08 5
… Continued
 if (inputFile.isDirectory())
 {
 System.out.println("\nFile
Contents:");
 String[] files =
inputFile.list();
 for(String file: files)
 {
 System.out.println(file);
 }
 }
 }
 }
 }

12/29/08 6
Testing the MyFileTest program
 C:\>javac MyFileTest.java

 C:\>java MyFileTest
 Usage Syntax: java MyFileTest <Dir/File Name>

 C:\>java MyFileTest SONGS


 The File Name: SONGS
 The File Path: C:\\SONGS
 Is Directory?: true

 File Contents:
 FIDA
 Mohabbatein
 Saaya
 ShankarDada_MBBS
 Yuva

 C:\>

12/29/08 7
Java I/O
 I/O Streams
A program opens a stream on an information
source (a file, memory, a socket) and reads the
information sequentially, as shown here:

12/29/08 8
… Continued
 Similarly, a program can send information to
an external destination by opening a stream to
a destination and writing the information out
sequentially, like this:

12/29/08 9
… Continued
 No matter where the data is coming from or going to and no
matter what its type, the algorithms for sequentially reading and
writing data are basically 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

12/29/08 10
… Continued
 The java.io package contains a collection of
stream classes that support these algorithms
for reading and writing.
 To use these classes, a program needs to
import the java.io package.
 The stream classes are divided into two class
hierarchies, based on the data type (either
characters or bytes) on which they operate.
 Character Streams
 Byte Streams

12/29/08 11
Character Streams

12/29/08 12
… Continued

12/29/08 13
Byte Streams

12/29/08 14
… Continued

12/29/08 15
Understanding the I/O Superclasses

 Reader and InputStream define


similar APIs but for different data types.
 For example, Reader contains these
methods for reading characters and
arrays of characters:
 int read()
 int read(char cbuf[])
 int read(char cbuf[], int
offset, int length)

12/29/08 16
… Continued
 InputStream defines the same methods but
for reading bytes and arrays of bytes:
 int read()
 int read(byte cbuf[])

 int read(byte cbuf[], int offset, int


length)
 Also, both Reader and InputStream provide
methods for marking a location in the stream,
skipping input, and resetting the current
position.

12/29/08 17
… Continued

Writer and OutputStream are


similarly parallel.
Writer defines these methods for
writing characters and arrays of
characters:
 int write(int c)
 int write(char cbuf[])
 int write(char cbuf[], int
offset, int length)

12/29/08 18
… Continued
 And OutputStream defines the same methods but
for bytes:
 int write(int c)
 int write(byte cbuf[])
 int write(byte cbuf[], int offset, int
length)
 All of the streams - readers, writers, input streams,
and output streams - are automatically opened when
created.
 You can close any stream explicitly by calling its close
method. Or the garbage collector can implicitly close it,
which occurs when the object is no longer referenced.

12/29/08 19
How to Use File Streams

 The file streams - FileReader,


FileWriter, FileInputStream , and
FileOutputStream - each read or
write from a file on the native file system.
 The following program uses
FileReader to read the contents of a
file named intest.txt:

12/29/08 20
ReadContent.java
 import java.io.*;

 class ReadContent
 {
 public static void main(String[] args) throws
IOException
 {
 File inputFile = new File("intest.txt");
 FileReader in = new FileReader(inputFile);
 int c;

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


 System.out.println((char)c);

 in.close();
 }
 }

12/29/08 21
intest.txt

 This is a simple text file used, which


contains a single line of data as follows:
 Srujan raju

12/29/08 22
Testing the ReadContent program
 C:\>javac ReadContent.java

 C:\>java ReadContent
 A
 m
 z
 a
 d

 B
 a
 s
 h
 a

 C:\>

12/29/08 23
WriteContent.java
 import java.io.*;

 class WriteContent
 {
 public static void main(String[] args) throws
IOException
 {
 FileOutputStream out = new
FileOutputStream("myfile.txt");
 PrintStream p = new PrintStream(out);

 p.println ("This is written to a file");

 p.close();
 out.close();
 }
 }

12/29/08 24
Testing the WriteContent program

 C:\>javac WriteContent.java

 C:\>java WriteContent

 C:\>
 Test the program as shown above and
check the file “myfile.txt” is created
or not.

12/29/08 25
FileInputTest.java
 import java.io.*;

 class FileInputTest
 {
 public static void main(String args[])
 {
 // args.length is equivalent to argc in C
 if (args.length == 1)
 {
 try
 {
 // Open the file that is the first
 // command line parameter
 FileInputStream fstream = new
 FileInputStream(args[0]);

 // Convert our input stream to a


 // DataInputStream
 DataInputStream in =
 new DataInputStream(fstream);

12/29/08 26
… Continued
 // Continue to read lines while
 // there are still some left to read
 while (in.available() !=0)
 {
 // Print file line to screen
 System.out.println(in.readLine());
 }

 in.close();
 }
 catch (Exception e)
 {
 System.err.println("File input error");
 }
 }
 else
 System.out.println("Invalid parameters");
 }
 }

12/29/08 27
Testing the FileInputTest program
 C:\>javac FileInputTest.java
 Note: FileInputTest.java uses or overrides a
deprecated API.
 Note: Recompile with -Xlint:deprecation for details.

 C:\>java FileInputTest
 Invalid parameters

 C:\>java FileInputTest FIS.txt


 File input error

 C:\>java FileInputTest intest.txt


 Srujan raju

 C:\>

12/29/08 28
FileCopy.java
 import java.io.*;

 class FileCopy
 {
 public static void main(String[] args) throws
IOException
 {
 File inputFile = new File("intest.txt");
 File outputFile = new File("outtest.txt");

 FileReader in = new FileReader(inputFile);


 FileWriter out= new FileWriter(outputFile);
 int c;

12/29/08 29
… Continued
 while ((c = in.read()) != -1)
 out.write(c);

 in.close();
 out.close();

 System.out.println("The content
of " + inputFile.toString() + " is
copied to " + outputFile.toString() + "
successfully..");
 }
 }

12/29/08 30
Testing the FileCopy program
 C:\>javac FileCopy.java

 C:\>java FileCopy
 The content of intest.txt is
copied to outtest.txt
successfully..

 C:\>

12/29/08 31
FileCopyBytes.java
 import java.io.*;

 public class FileCopyBytes


 {
 public static void main(String[] args) throws
IOException
 {
 File inputFile = new File("intest.txt");
 File outputFile = new File("outtest.txt");

 FileInputStream in = new
FileInputStream(inputFile);
 FileOutputStream out = new
FileOutputStream(outputFile);
 int c;

12/29/08 32
… Continued
 while ((c = in.read()) != -1)
 out.write(c);

 in.close();
 out.close();

 System.out.println("The content
of " + inputFile.toString() + " is
copied to " + outputFile.toString() + "
successfully..");
 }
 }

12/29/08 33
Testing the FileCopyBytes program

 C:\>javac FileCopyBytes.java

 C:\>java FileCopyBytes
 The content of intest.txt is
copied to outtest.txt
successfully..

 C:\>

12/29/08 34
URLs
 http://www.javacoffeebreak.com/java103/java
 http://java.sun.com/docs/books/tutorial/essen
 http://javaboutique.internet.com/tutorials/Files
 http://www.particle.kth.se/~lindsey/JavaCours

12/29/08 35

Thank You…
12/29/08 36

Das könnte Ihnen auch gefallen