130 likes | 303 Views
Streams and Files: Input & Output. Files and Stream. Files can be used to: Store Java classes, programs. Store pictures, music, videos. Can also use files to store program Input/Output. Stream is a flow of input or output data: Characters. Numbers. Bytes. Concept of a Stream.
E N D
Files and Stream • Files can be used to: • Store Java classes, programs. • Store pictures, music, videos. • Can also use files to store program Input/Output. • Streamis a flow of input or output data: • Characters. • Numbers. • Bytes.
Concept of a Stream • Streams are implemented as objects of special stream classes: • Class Scanner • Object System.out
Why Use Files for I/O • Input of the keyboard and also screen output deal with temporarydata: • In other words, when program ends, data is gone. • E.g., consider a java program that sorts an array. • Data in a file remains after program ends: • Can be used next time when program runs. • Can be also used by another program.
Text Files and Binary Files • All data in files stored as binary digits: • That is, long series of zeros and ones. • Files treated as a sequence of characters called text files, e.g., Java program source code: • They can be viewed and edited with text editors. • All the other files are called binary files, e.g., movie and music files: • The access requires a specialized program.
you must import package java.io “PrintWriter” is a keyword declare stream variable for referencing the stream always need the try & catch block class PrintWriter defines methods needed to create &write to a text file file name can be also defined by the user • file can be written to with method println • data initially goes to the memory buffer and then goes to the file closing file empties buffer and disconnectsthe stream
Some Points • When creating a file: • Inform the user of ongoing I/O events, program should not be silent. • A file has two names in the program: • The file name used by the OS, e.g., “out.txt”. • The stream namevariable, e.g., “outputStream”. • Opening and writing to a file overwrites pre-existing file in a directory.
you must import package java.io “Scanner” is a keyword declare stream variable for referencing the stream class Scannerdefines methods needed to read from a text file always need the try & catch block hasNextLine() returns true if more input data is available nextLine()reads one more line from the file closing file empties buffer and disconnectsthe stream
here we first read the file name and then we read the file the user enters the name of the file that we intend to read from these 3 lines are a replacement for the following statement: String fileName = ‘’out.txt’’;