DOC PREVIEW
WVU CS 110 - File Input/output using Loops

This preview shows page 1-2-3-4 out of 11 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

File Input/output using LoopsReading input from a FileExample of reading an input file;Writing Data to an output fileClass File, and file operationsExample 1:File Input/output using Loops Frequently a program will require more input data than can simply be input by a user at the keyboard. Data files can be prepared ahead of time using a text editor, stored on disk, and accessed via an executing program. Also, instead of writing output to the screen, a program can direct that that output be stored in a fileand saved to disk. There are many classes provided by Java that help us read from & write to files. The simplest are classes Scanner and PrintWriter. Before we cover these classes in detail, we need to review some terms and concepts involved with files:- Binary and Text Files: A binary file stores data in the format that it is stored in memory, in an internal format. A text file stores data as ASCII values, in a human readable format. When data is stored in binary format it does not need to be translated to or from ASCII and therefore data transfer is more efficient and optimized. - Stream I/O: This refers to the manner in which data is stored in ( or output to) a file. With stream I/O data is read as a series of continuous characters or bytes. This is how input from the keyboard is read. Two classes FileInputStream and FileOutputStream are used to access streams of bytes. Classes Reader and Writer and their descendents (FileReader and PrintWriter) are used to access streams of characters. We will learn to use class PrintWriter to write data to an output file, and class FileReader to allow Scanner to read input from a file.- Buffered Stream: rather than read one character/byte at a time from the input stream (or write one character/byte at a time to the output stream), we can create a “buffered stream” in memory whereby a “block” of stream data is written to (or read from) the buffer, before any actual access to the input/output device occurs. We can think of the buffer, as a container in memory into which our data is written. When the buffer is full, it’s contents are written to the device. This allows multiple reads/writes to occur from the buffer, between actual accesses to the device, thus speeding up the process of I/O again.Reading input from a FileTo read data from a file, the programmer needs to have an understanding of the format of the data stored in the file, and its meaning. Often each physical line will contain multiple values which together form a logical record. A logical record is a set of values which together describe one unique entity in our problem space. For example if we have a data file containing information about employees and their hours worked it might look like the following:Smith John 37.5 7.35 s bLewis Larry 45.0 5.50 s nJones James 55.0 8.20 m bIn this example, the first string represents the employee’s last name, followed by first name, number of hours worked, hourly wage, whether single or married, and whether or not they are benefits eligible.So the first line would translate into:John Smith, who worked 37.5 hours, at $7.35 per hour, single, and is benefits eligible.We would write our program to read and process the data one line at a time.Class Scanner offers many methods that you can use with loops to read multiple “lines” of data from a data file. In addition to the methods that accomplish input, nextInt(), nextFloat() etcetera that would be used to access individual values, Class Scanner offers others that manipulate and test the contents of a file so that we do not attempt to read beyond the end of the physical file, these include: o hasNext(): This method returns true if the data file has more data of any type that has not yet been read. o hasNextInt(): returns true if the next value in the data file can be interpreted as an Integer.o hasNexttFloat(): returns true if the next value in the data file can be interpreted as an floating point number.o hasNextBoolean(): returns true if the next value in the data file can be interpreted as a Boolean value.o hasNextLine(): returns true if there is another line of input in the file.Using one of these methods, as we can create a loop to read data from a file, until all of that data is exhausted.For example, if we have defined a Scanner instance, called console the logic of our program would look like: while (console.hasNext()) {//READ THE DATA FROM THAT LINE// PROCESS THE DATA}We could also use the method hasNextLine()To allow Scanner to access a physical file, we must use class FileReader. Instances of this class are used to create a connection between out program and a physical file:Scanner infile = new Scanner(new FileReader(“c:\\mydata.txt”);Any methods from Scanner that are invoked for “infile” are now applied to the data file, rather than the console. In the previous example the instance of FileReader is created when we create the instance of scanner, there are other ways:FileReader name = new FileReader(“path and file name”);We can define instance of FileReader separately, the filename given may or may not include the full path, if only a file name is given ie: “mydata.txt” then the file is assumed to be in the current working directory. You will notice something unusual in the first example which included a path name. The character \ is a control character in Java, as in \n which is the new line character. If it is part of a path name, then we must use two \\. So for example: “c:\\cs110\\inputdata\\mydata.txt”.Our Programmydata.txtOnce the instance of FileReader is declared, we can then use it in the declaration of our scanner:FileReader inputFile = new FileReader( “mydata.txt”);Scanner infile = new Scanner(inputFile);Please Note: when declaring an instance of FileReader, the file name can also be specified using a string variable, instead of a quoted literal. Which means it is possible to prompt the user for the name of the input file, read it into a string variable, and then create our connection to the file.String filename;Scanner console = new Scanner(System.in);System.out.println(“Please enter the name of the file to be read. “);filename = console.nextLine();FileReader inputFile = new FileReader(filename);Scanner input = new Scanner(inputFile);There is a possible error condition for which we must account in case the file we are accessing does not exist.This is a “file


View Full Document

WVU CS 110 - File Input/output using Loops

Download File Input/output using Loops
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view File Input/output using Loops and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view File Input/output using Loops 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?