Presentation is loading. Please wait.

Presentation is loading. Please wait.

SE-1020 Dr. Mark L. Hornick 1 File Input and Output.

Similar presentations


Presentation on theme: "SE-1020 Dr. Mark L. Hornick 1 File Input and Output."— Presentation transcript:

1 SE-1020 Dr. Mark L. Hornick 1 File Input and Output

2 SE-1020 Dr. Mark L. Hornick 2 A program typically reads the data it manipulates from a file, or writes the data it has manipulated to a file File output is the action of writing data to a file. File input is the action of reading data from a file.

3 CS-1020 Dr. Mark L. Hornick 3 The File class from java.io …provides an abstraction of a physical file (or file directory) on a local (or network) filesystem File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”); Opens (associates) the file sample.dat in the current directory. Opens the file test.dat in the directory C:\SamplePrograms using the universal file separator / and providing the full pathname.

4 CS-1020 Dr. Mark L. Hornick 4 Some File methods and their functions methodfunction canReadTests whether the application can read the file canWriteTests whether the application can modify the file deleteDeletes the file or directory existsTests whether the file or directory exists isDirectoryTests whether the file is a directory isFileTests whether the file is a normal file isHiddenTests whether the file is a hidden file lengthReturns the length of the file (in bytes) list Returns an array of abstract pathnames denoting the files in the directory renameToRenames the file

5 CS-1020 Dr. Mark L. Hornick 5 File method examples if ( inFile.exists( ) ) { if ( inFile.isFile() ) { File directory = new File("C:/JavaPrograms/Ch12"); // list() returns an array of Strings String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } To see if inFile is associated to a real file correctly. To see if inFile is associated to a file or not. If false, it is a directory. List the name of all files in the directory C:\JavaProjects\Ch12

6 CS-1020 Dr. Mark L. Hornick 6 Note that there are no read() or write() methods in the File class To read data from or write data to a file, a Java stream object must be created and attached to the file A stream is a sequence of data items

7 SE-1020 Dr. Mark L. Hornick 7 First - The Big Question: How should we store data in a file?

8 SE-1020 Dr. Mark L. Hornick 8 Let’s say we have numeric (e.g. integer) data to be stored. How can integer data be stored??? Integers (in Java) occupy 4 bytes (32 bits)… …so we can store any integer value as 4 raw bytes of data: -2000000000 -10000 0 250000 450000000

9 SE-1020 Dr. Mark L. Hornick 9 Here’s an example of a file containing raw integer binary data when viewed with Notepad Q: What do these characters represent??

10 SE-1020 Dr. Mark L. Hornick 10 Instead of storing primitive data values as binary data in a file, they can be converted to their character representation and stored as string data This is known as text file IO This allows the file content to be viewed using any text editor To output data (regardless of datatype) as a text to file, a PrintWriter object is used

11 SE-1020 Dr. Mark L. Hornick 11 PrintWriter is a class for outputting data in text format The ‘out’ field in System.out is actually a PrintWriter object: class System { // Java’s System class public static PrintWriter out; … } The PrintWriter class contains the print() and println() methods The System class associates a PrintWriter object named out with the console

12 SE-1020 Dr. Mark L. Hornick 12 To use PrintWriter for creating file output: PrintWriter pw = new PrintWriter( file ); The file parameter is a String containing the name of a file to be created If file=“output.txt”, the file is created in the current directory Otherwise, a full directory path can be specified “C:\\temp\\output.txt” creates the file in C:\temp You can use / instead of \\ in the file path specification: “C:/temp/output.txt” Note: we’re using the simplest of 8 different PrintWriter constructors here; this constructor accepts a single String argument specifying the filename.

13 SE-1020 Dr. Mark L. Hornick 13 Any existing file with the name specified as the PrintWriter argument will be overwritten However, the specified file must be creatable! A NoSuchFileException is thrown if There is not enough disk space The file path specified does not exist Is marked “readonly” If the file belongs to some other user (a security violation) and you don’t have permission to access it

14 SE-1020 Dr. Mark L. Hornick 14 To write using the PrintWriter: pw.println(“This string will go in the file”); Use the print() and println() methods just as you would when using System.out

15 To append to an existing file, another version of the overloaded PrintWriter constructor is used This version of PrintWriter accepts a single argument – a reference to a FileWriter object FileWriter is a “helper” class that PrintWriter uses to append characters to an existing file. //create a FileWriter, true specifies append FileWriter fw = new FileWriter( file, true ); PrintWriter pw = new PrintWriter( fw ); pw.println(“This string will go at the end of the file”); SE-1020 Dr. Mark L. Hornick 15

16 SE-1020 Dr. Mark L. Hornick 16 Conversely, for reading data stored as text in a file, we use the familiar Scanner class: Recall the use of the Scanner class in conjunction with System.in: Scanner reader = new Scanner( System.in ); int i = reader.nextInt();

17 SE-1020 Dr. Mark L. Hornick 17 To use the Scanner class for reading text data from a file, use the “helper” class FileReader String file = “output.txt”; FileReader fr = new FileReader(filename); Scanner reader = new Scanner( fr ); The filename parameter is a String containing the name of a file to be read The fr parameter is a FileReader object that is associated with the physical file on the filesystem. FileNotFoundException is thrown if the specified file does not exist. Don’t confuse creating a FileReader object with creating an actual physical file on disk!!!

18 SE-1020 Dr. Mark L. Hornick 18 The default behavior for next() is to read from the input stream until whitespace is encountered … Scanner reader = new Scanner( fr ); String s = reader.next(); // read next String “token” int i = reader.nextInt(); // try to read an int... Whitespace is any non-printing character Newline Tab Space The useDelimiter() method can be invoked on a Scanner to change the default scanning behavior: reader.useDelimiter(“,”); // scan until comma reader.useDelimiter(“[,;\\s]+”); // scan until one or more occurrences of comma, semicolon, or whitespace (tab, return, linefeed, formfeed)

19 SE-1020 Dr. Mark L. Hornick 19 Q: What do these characters represent??

20 SE-1020 Dr. Mark L. Hornick 20 ASCII Encoding of characters


Download ppt "SE-1020 Dr. Mark L. Hornick 1 File Input and Output."

Similar presentations


Ads by Google