Download presentation
Presentation is loading. Please wait.
Published byKristopher Carter Modified over 6 years ago
1
Java Methods ("Chapter %d", 14); Streams and Files A & AB
Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin outputFile.printf ("Chapter %d", 14); The material in this chapter is not tested on the AP CS exams. Streams and Files Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
2
Objectives: Learn the basic facts about Java’s IO package
Understand the difference between text and binary files Understand the concept of an input or output stream Learn about handling exceptions If you want to learn the technical details about Java’s IO package, this chapter is not sufficient. The main objective here is to provide conceptual background on files and streams, with only a glimpse at their implementation in Java. For student projects, Scanner and PrintWriter are adequate. Or use our EasyReader and EasyWriter (Appendix E).
3
Files A 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. To look at or print out a file you must use some program.
4
Files (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. Recall that a file is a software entity. The hardware knows nothing about files. The operating system does.
5
Text Files A 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). The file name may give a hint as to how it “prefers” to be treated. Surely, a file that contains only ASCII characters and has CR+LF every so often is likely to have been created as a text file and is probably intended to be used that way. But nothing in a file’s contents specifically demands a particular treatment.
6
Text Files Examples: Any plain-text file, typically named something.txt Source code of programs in any language (for example, Something.java) HTML documents Data files for certain programs, (for example, fish.dat; any file is a data file for some program.) But not files created with a word processor they contain special headers and formatting commands.
7
Binary Files A “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). There have been reports in the press of terrorists using software that hides secret encoded messages in harmless-looking image files. There is also the matter of displaying a file. For example, an HTML file is an ASCII file and may be presented as such in a plain-text editor, but it appears differently in a browser.
8
Binary Files Examples:
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). The reverse is true, too: you can treat a binary file as a text file. Whenever you encounter a byte that contains a value corresponding to LF, the program will decide that this is the end of a line. In the early releases of MS DOS, files contained a special EOF (end of file) marker at the end. The only problem was that a binary file could have this value in the middle by accident, and the copy command would stop at that place. You needed to add a command switch /b (for binary) to tell the program to treat the file as a binary file.
9
Text as Binary: ASCII display rose.txt A rose is a rose Hex “dump”
The hex dump of a text file in this slide has been produced by the ancient program debug (c. 1982, still included with Windows). The display on the right shows those values that correspond to printable ASCII characters. CR + LF
10
Streams A 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. The advantage of streams is that they provide a uniform way of treating files and devices. For example, in Unix and other operating systems it is easy to “redirect” screen output to a file.
11
Streams (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. For text files it is especially important to be able to treat various data sources (a file, an Internet data stream, etc.) uniformly. It is also more common to read or search text files sequentially, from the beginning.
12
Random-Access Files A 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. Thus you can open the same file as a stream in one situation and as a random-access file in another.
13
Random-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-access Random-access is convenient. That’s why people have switched from tapes to CDs and from videotapes to DVDs.
14
File Types: Summary File Text Binary Stream Random-Access common use
In other words, it is not common to treat a text file as a random-access file. common use possible, but not as common
15
java.io How do I read an int from a file?
BufferedInputStream 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? Java IO is not for the faint at heart. It looks like Java developers went all out to confuse programmers. That’s why programmers are such well-paid specialists.
16
java.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. The developer of the RandomAccessFile class probably was not a “team player,” as they say in the industry. Or this part of the project was assigned to a different group. Scanner is an afterthought (Java 5). Scanner got rid of checked exceptions (except in the constructor). It still won’t let you read one character.
17
java.io.File The 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); A File object does not have to be associated with an open file. In fact, it can represent a directory entry for a file that does not exist yet.
18
Reading 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 file You have used the same Scanner class to read from the keyboard.
19
Scanner Methods boolean hasNextLine() String nextLine()
boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Reads one word You can check whether a particular token (an int, a word) exists in the stream, then read it.
20
Writing 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(); Once a PrintWriter has been created, you can write to it using print, println, and printf methods, the same way you write to the console screen. Required to flush the output buffer
21
Review: 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? Name a few types of files that are normally treated as text files. .txt files from various sources, program source files, HTML files. Can you open the same file as a text file and as a binary file in different programs? Yes. For example, an program may send all attachments as binary. Can you open a text file as a random-access file? Yes Do you think .jar (Java archives) files that contain compiled library classes are treated as streams or random-access files? Streams would make it too inefficient to find a particular class. They are indexed random-access files.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.