31
Files and Streams

Files and Streams

  • Upload
    hung

  • View
    34

  • Download
    0

Embed Size (px)

DESCRIPTION

Files and Streams. Java I/O. File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources and destinations, such as disk files, devices, other programs, and memory arrays. Input Stream. - PowerPoint PPT Presentation

Citation preview

Page 1: Files and Streams

Files and Streams

Page 2: Files and Streams

Java I/OJava I/O File I/O I/O streams provide data input/output

solutions to the programs. A stream can represent many different

kinds of sources and destinations, such as disk files, devices, other programs, and memory arrays.

Page 3: Files and Streams

Input StreamInput Stream

Source: java.sun.com

different kinds of data, including simple bytes, primitive data types, localized characters, and objects.

Page 4: Files and Streams

Output StreamOutput Stream

Source:java.sun.com

Page 5: Files and Streams

File I/OFile I/O File I/O provides a simple model for

reading and writing data from/to files. Streams work with a large variety of data

sources and destinations, including disk files.

Streams don't support all the operations that are common with disk files.

Page 6: Files and Streams

File Objects File Objects File class can be used to write platform-

independent code to examines and manipulates files.

File instances represent file names, not files.

The File object corresponding to the file name might not even exist.

Page 7: Files and Streams

Creating a File objectCreating a File object A File object contains the file name string used to

construct it. e.g.

File f = new File(“sample.txt");File testFile = new File(“c:\\test\\data.txt”);

The file name string never changes throughout

the lifetime of the object. But a file name may have different corresponding

File objects.

Page 8: Files and Streams

ExampleExample

Page 9: Files and Streams

Manipulating FilesManipulating Files If a File object names an actual file, a program

can use it to perform a number of useful operations on the file.

These include passing the object to the constructor for a stream to open the file for reading or writing.

The delete method deletes the file immediately, while the deleteOnExit method deletes the file when the virtual machine terminates.

Page 10: Files and Streams

Manipulating FilesManipulating Files The setLastModified sets the modification

date/time for the file. The renameTo() method renames the file.

Note that the file name string behind the File object remains unchanged, so the File object will not refer to the renamed file.

Page 11: Files and Streams

Working with DirectoriesWorking with Directories You can also use File class to work with

directories. The mkdir method creates a directory. The mkdirs method does the same thing,

after first creating any parent directories that don't yet exist.

The list and listFiles methods list the contents of a directory.

Page 12: Files and Streams

ExampleExample

Page 13: Files and Streams

Byte Streams Byte Streams Programs use byte streams to perform

input and output of 8-bit bytes. All byte stream classes are descended

from InputStream and OutputStream. Two important Streams

FileInputStream FileOutputStream.

Page 14: Files and Streams

Using Byte StreamsUsing Byte Streams You can use FileInputStream and

FileOutputStream as the following

in = new FileInputStream(“input.txt");

out = new FileOutputStream("output.txt");

Page 15: Files and Streams

ExampleExample

Page 16: Files and Streams

Important noteImportant note Always close streams! This practice helps avoid serious resource

leaks. Byte streams should only be used for the

most primitive I/O.

Page 17: Files and Streams

Character Streams Character Streams Characters in Java environment use

Unicode conventions. Character stream I/O automatically

translates this internal format to and from the local character set.

Page 18: Files and Streams

ExampleExample

• What is the difference between this and previous example?

Page 19: Files and Streams

Buffered Streams Buffered Streams To reduce the overhead of multiple request of I/O

access and improve the efficiency of programs , Java platform provides buffered I/O streams.

Buffered input streams read data from a memory area known as a buffer;

the native input API is called only when the buffer is empty.

Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

Page 20: Files and Streams

ExampleExample

Page 21: Files and Streams

Class BufferedInputStreamClass BufferedInputStream

Page 22: Files and Streams

Random Accessing FilesRandom Accessing Files he java.io.RandomAccessFile class

implements both the DataInput and DataOutput interfaces that can be used for both reading and writing files.

Page 23: Files and Streams

ExampleExample

Page 24: Files and Streams

PrintWriter ClassPrintWriter Class Provides better methods to write formatted

data to a text-output stream. But, it does not contain methods for

writing raw bytes, for which a program should use unencoded byte streams.

Page 25: Files and Streams

FormattingFormatting In PrintWriter class two levels of formatting

are provided: print and println format individual values in a

standard way. format formats almost any number of values

based on a format string, with many options for precise formatting.

Page 26: Files and Streams

The format MethodThe format Method The format method formats multiple

arguments based on a format string. The format string consists of static text

embedded with format specifiers; except for the format specifiers, the format string is output unchanged.

Page 27: Files and Streams

ExampleExample

public class Root2 { public static void main(String[] args)

{ int i = 2; double r = Math.sqrt(i); System.out.format("The square

root of %d is %f.%n", i, r); }

}

Page 28: Files and Streams

ConversionsConversions d formats an integer value as a decimal value. f formats a floating point value as a decimal

value. n outputs a platform-specific line terminator. x formats an integer as a hexadecimal value. s formats any value as a string. tB formats an integer as a locale-specific

month name. ...

Page 29: Files and Streams

ConversionsConversions Except for %% and %n, all format

specifiers must match an argument. If they don't, an exception is thrown.

In the Java programming language, the \n escape always generates the linefeed character (\u000A). Don't use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n.

Page 30: Files and Streams

SummarySummary The java.io package contains many classes that your

programs can use to read and write data. Most of the classes implement sequential access streams. The sequential access streams can be divided into two

groups: those that read and write bytes and those that read and write Unicode characters.

Each sequential access stream has a speciality, such as reading from or writing to a file, filtering data as its read or written, or serializing an object.

One class, RandomAccessFile, implements random input/output access to a file. An object of this type maintains a file pointer, which indicates the current location from which data will be read or to which data will be written.

Page 31: Files and Streams

QuestionsQuestions What class would you use to read a few

pieces of data that are at known positions near the end of a large file?

In a format call, what's the best way to indicate a new line?

How would you append data to the end of a file?

Source: java.sun.com