310 likes | 461 Views
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.
E N D
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 different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Source: java.sun.com
Output Stream Source:java.sun.com
File 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.
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.
Creating 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.
Manipulating 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.
Manipulating 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.
Working 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.
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.
Using Byte Streams • You can use FileInputStream and FileOutputStream as the following in = new FileInputStream(“input.txt"); out = new FileOutputStream("output.txt");
Important note • Always close streams! • This practice helps avoid serious resource leaks. • Byte streams should only be used for the most primitive I/O.
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.
Example • What is the difference between this • and previous example?
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.
Random Accessing Files • he java.io.RandomAccessFile class implements both the DataInput and DataOutput interfaces that can be used for both reading and writing files.
PrintWriter 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.
Formatting • 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.
The 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.
Example 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); } }
Conversions • 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. • ...
Conversions • 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.
Summary • 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.
Questions • 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