Uploaded by HI im Swift

IT6008 Unit 07

advertisement
IT6008: Computer Programming 1
Input and Output with Files
Running A Java program outside Netbeans
Lecture Overview
• File class
• Streams
• Read from Text Files
• Write to Text Files
• Summary
• Compile and run a program outside Netbeans
Learning Objectives
On completion of this session you should be able to:
• Read data from a text file
• Write data to a text file
• Build and run a Java program outside Netbeans
Files and the File class
The Java IO package
• Provided as part of the JDK
• Contains classes and interfaces to use when dealing
with different types of input and output
• Includes :
• 12 Interfaces
• 51 Classes
• Required
• import java.io.*;
Java I/O mechanisms
• In Java, I/O is done through a set of classes
• For I/O: no new language construct (just new
classes)
• The classes provide several interfaces to streams
and other IO concepts
• First, we look at the File class
• Next, we look at streams.
Differentiating streams from files
The File class
• Represents information about an existing particular file, or
directory
• Derived directly from class Object
• Uses for this class:
• List existing files and directories
• Check for existence of files and directories
• Used by other input/output objects that handle transferring of
data
• Many other housekeeping capabilities
• Restrictions
• Cannot write data to or read data from any files
Example: Creating a new File instance
new File (String pathname)
Creates a new File instance by converting the given pathname string into an
abstract pathname.
Example:
String fileName = "C:\\ICT2034.txt"
File inFile = new File(fileName);
Example 1: File class methods
public static void main(String [] args)
{
File inFile = new File(“Path and fileName go here”);
if( inFile.isFile() && inFile.canRead() &&
inFile.canWrite() )
System.out.print(“File exists and can be used”);
else
System.out.print(“File no good for purposes”);
}
inFile is a new File instance that represents a file or
a directory that may or may not already exist
File class methods
String getAbsolutePath() - Returns the absolute pathname string of this abstract
pathname.
String getName() - Returns the name of the file or directory denoted by this abstract
pathname.
String getParent() - Returns the pathname string of this abstract pathname's parent, or
null if this pathname does not name a parent directory.
boolean canRead() - Tests whether the application can read the file denoted by this
abstract pathname.
boolean canWrite() - Tests whether the application can modify to the file denoted by this
abstract pathname.
boolean createNewFile() - Automatically creates a new, empty file named by this
abstract pathname if and only if a file with this name does not yet exist.
boolean delete() - Deletes the file or directory denoted by this abstract pathname.
File class methods
boolean exists() - Tests whether the file or directory denoted by this abstract pathname
exists.
boolean isFile() - Tests whether the file denoted by this abstract pathname is a normal
file.
boolean isHidden()
Tests whether the file named by this abstract pathname is a
hidden file.
boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
long lastModified() - Returns the time that the file denoted by this abstract pathname
was last modified.
long length() - Returns the length of the file denoted by this abstract pathname.
static File createTempFile(String prefix, String suffix, File directory) - Creates a new
empty file in the specified directory, using the given prefix and suffix strings to
generate its name.
Streams
How to read, write and append from/to a file
Streams
Program
Program
a stream
reads
source
writes
dest
Text Files: Reading and Writing
• A Text File is a file where the contents are humanly
readable
• a code-file is text file.
• HTML files are text files
• We can use a Scanner object to read the contents of
humanly readable text files
• We can use a PrintStream object to write contents to
humanly readable text files
Writing/Reading Algorithm
Writing
open a stream
while(more information)
write information to stream
close the stream
Reading
open a stream
while(more information)
read information from stream
close the stream
Some java input and output stream classes
BufferedOutputStream
OutputStream
FilterOutputStream
DataOutputStream
FileOutputStream
PrintStream
ByteArrayOutputStream
Object
ByteArrayOutputStream
InputStream
FileInputStream
BufferedInputStream
FilterInputStream
DataInputStream
StringBufferInputStream
PushbackInputStream
SequenceInputStream
The data type of System.out
System.out.println(“Hello World");
Object reference of class
class System
PrintStream
{
public static final PrintStream err;
public static final InputStream in;
public static final PrintStream out;
...
}
System (for historical reasons) uses PrintStreams and
InputStream for I/O.
Opening a text file to read with Scanner
Scanner can be used in two ways.
To read user input:
Scanner scan = new Scanner(System.in);
To read data from a file:
File inFile= new File(“C:\\myfile.txt”);
Scanner input= new Scanner(inFile);
Note: if no file path is specified the file is in the project
directory
Reading from text file
The hasNext property of a Scanner object created
from a File object returns true while the file has more
data
while(input.hasNext())
{
//Read data using methods of Scanner (next, nextInt, etc)
}
FileNotFoundException
When writing code which uses the java.io class library Netbeans requires
exception handling code (code which deals with exceptions – in this case the
exception which would be generated if the file was not found). An error
message will be generated by the code shown below:
FileNotFoundException
If you click the message a list of options is shown.
The minimum requirement is a throws clause which advertises that an exception could be
thrown by this code. To deal with the issue select the throws clause option (exception
handling will be more fully explained in Computer Programming 2)
This will automatically add a throws clause to the main method:
• java.lang.Object
• java.lang.Throwable
• java.lang.Exception
• java.io.IOException
• java.io.FileNotFoundException
Validate to prevent a FilenotFoundException
Good practice: We can write some validation code with if-logic which will prevent any
FileNotFoundException from being thrown, using the exists property of the File class:
Writing to a text file using PrintStream
We are familiar with using System.out to display to the screen.
out is a variable of type PrintStream
To create a PrintStream that writes into a file, we can do the
following:
File outFile= new File(“C:\\myFile.txt” );
PrintStream output= new PrintStream (outFile);
Note: If the file does not exist, it will be created. If the file exists, it
will be overwritten.
Writing to a text file
To write to the file use print or println methods in the same way as
with System.out:
String firstName = "Fred“;
String address = "25 Rocky Road";
String lastName = "Flintstone“;
int postcode = 3800;
File outFile= new File("Details.txt");
PrintStream output = new PrintStream (outFile);
// First line: first and last name, separated by a tab…
output.print(firstName + “\t“);
output.print(lastName + “\n“);
// Second line: the Address
output.println(address);
// Third line: the Postcode (a number, converted to characters)
output.println(postcode);
}
Writing to a text file from an Array
A common scenario will be to write to a text file from an
Array:
while(index<array length)
{
//code to write to file
index++;
}
Appending to a text file
By default, opening a file for writing destroys any existing file
with the same name
To keep the existing file, but to add to the end, the file needs to
be opened in append mode
This can be done using the FileOutputStream class as follows:
File outFile = new File(“H:\\output.txt” );
FileOutputStream outStream = new FileOutputStream (outFile , true);
PrintStream output= new PrintStream (outStream); //appends to existing data
Summary
• I/O takes place through objects representing
streams of bytes to and from physical devices
• The java.io package supports a rich set of
classes which can be used for performing file I/O
• Scanner can read text files, PrintStream can write
text files
• Exceptions are used to catch potential problems in
the code during execution.
Building/Running a Java program outside NetBeans
Build and run a Java program outside NetBeans
• Use NetBeans to generate a .jar file.
• Use DOS commands to do things in a Console
window (Command Prompt).
• Run a Java program in a Console window.
Using DOS commands
Open a Console window using the cmd command
Or you can use WindowsKey + R, type cmd, then click OK.
Using DOS commands
To change from one drive to another, type the drive letter and colon :
Using DOS commands
To navigate to a different folder, type cd (Change Directory) and the
folder name
Using DOS commands
To go back to the previous folder, type cd..
Using DOS commands
To go back to the root folder, type cd\
Using DOS commands
If you make a mistake in typing a folder name, press the F3 function
key to repeat the last instruction and then correct the error:
Using DOS commands
To see the contents of a folder, type dir
Build the Java program to run outside Netbeans
Steps:
• In Netbeans select:
Run\Clean and Build Main Project.
creates a .jar file in the dist
folder of your application
• Open a console window
• Navigate to the folder containing your .jar file
• java –jar NameOfApp.jar
Run a Java program outside Netbeans
A batch file can be created to run the jar file without having to
open a Console window manually
Steps:
• In Notepad:
java –jar NameOfApp.jar
pause
• Double-click the batch file
Save the file with the extension .bat
Practical
• Open a Console window and practice with DOS
commands as above
• Compile and run Lab 7 Exercise 7.3 outside
Netbeans
Download