Kĩ thuật lập trình - Chương 15: Streams and files

A file can be treated as an input or output stream. In reality file streams are buffered for efficiency: it is not practical to read or write one character at a time from or to mass storage. It is common to treat text files as streams.

ppt21 trang | Chia sẻ: huyhoang44 | Lượt xem: 705 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Chương 15: Streams and files, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Streams and Files outputFile.printf ("Chapter %d", 15); Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.Java MethodsObject-Oriented Programmingand Data StructuresMaria Litvin ● Gary Litvin2nd AP edition  with GridWorld1Objectives:Learn the basic facts about Java’s IO packageUnderstand the difference between text and binary filesUnderstand the concept of an input or output streamLearn about handling exceptions2FilesA file is a collection of data in mass storage.A data file is not a part of a program’s source code.The same file can be read or modified by different programs.The program must be aware of the format of the data in the file.3Files (cont’d)The files are maintained by the operating system.The system provides commands and/or GUI utilities for viewing file directories and for copying, moving, renaming, and deleting files.The operating system also provides basic functions, callable from programs, for reading and writing directories and files.4Text FilesA computer user distinguishes text (“ASCII”) files and “binary” files. This distinction is based on how you treat the file.A text file is assumed to contain lines of text (for example, in ASCII code).Each line terminates with a newline character (or a combination, carriage return plus line feed).5Text FilesExamples:Any plain-text file, typically named something.txtSource code of programs in any language (for example, Something.java)HTML documentsData files for certain programs, (for example, fish.dat; any file is a data file for some program.)6Binary FilesA “binary” file can contain any information, any combination of bytes.Only a programmer / designer knows how to interpret it.Different programs may interpret the same file differently (for example, one program displays an image, another extracts an encrypted message).7Binary FilesExamples:Compiled programs (for example, Something.class)Image files (for example, something.gif)Music files (for example, something.mp3)Any file can be treated as a binary file (even a text file, if we forget about the special meaning of CR-LF).8Text as Binary:A rose is a roseis a roseCR + LFrose.txtHex “dump”ASCII display9StreamsA stream is an abstraction derived from sequential input or output devices.An input stream produces a stream of characters; an output stream receives a stream of characters, “one at a time.”Streams apply not just to files, but also to IO devices, Internet streams, and so on.10Streams (cont’d)A file can be treated as an input or output stream.In reality file streams are buffered for efficiency: it is not practical to read or write one character at a time from or to mass storage.It is common to treat text files as streams.11Random-Access FilesA program can start reading or writing a random-access file at any place and read or write any number of bytes at a time.“Random-access file” is an abstraction: any file can be treated as a random-access file.You can open a random-access file both for reading and writing at the same time.12Random-Access Files (cont’d)A binary file containing fixed-length data records is suitable for random-access treatment.A random-access file may be accompanied by an “index” (either in the same or a different file), which tells the address of each record.Tape : CD == Stream : Random-access13File Types: SummaryTextBinaryStreamRandom-AccessFile common use possible, but not as common14java.ioBufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter InputStream InputStreamReader LineNumberInputStream LineNumberReader ObjectInputStream ObjectInputStream.GetField ObjectOutputStream ObjectOutputStream.PutField ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringBufferInputStream StringReader StringWriter Writer How do I read an int from a file?15java.io (cont’d)Uses four hierarchies of classes rooted at Reader, Writer, InputStream, OutputStream.InputStream/OutputStream hierarchies deal with bytes. Reader/Writer hierarchies deal with chars.Has a special stand-alone class RandomAccessFile.The Scanner class has been added to java.util in Java 5 to facilitate reading numbers and words.16java.io.FileThe File class represents a file (or folder) in the file directory system.Methods:String getName()String getAbsolutePath()long length()boolean isDirectory()File[ ] listFiles()String pathname = "../Data/words.txt“;File file = new File(pathname);17Reading from a Text File String pathname = "words.txt"; File file = new File(pathname); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) { System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program } Tries to open the file18Scanner Methodsboolean hasNextLine()String nextLine()boolean hasNext()String next()boolean hasNextInt()int nextInt()boolean hasNextDouble()double nextDouble()void close() Reads one “word”19Writing to a Text File String pathname = "output.txt"; File file = new File(pathname); PrintWriter output = null; try { output = new PrintWriter(file); } catch (FileNotFoundException ex) { System.out.println("Cannot create " + pathname); System.exit(1); // quit the program } output.println(...); output.printf(...); output.close(); Required to flush the output buffer20Review:Name a few types of files that are normally treated as text files.Can you open the same file as a text file and as a binary file in different programs?Can you open a text file as a random-access file?Do you think .jar (Java archives) files that contain compiled library classes are treated as streams or random-access files?21

Các file đính kèm theo tài liệu này:

  • pptch15_6417.ppt