Download Text File

Document related concepts
no text concepts found
Transcript
Streams
CSC 171 FALL 2004
LECTURE 22
Make up exam

Friday 12/3 11AM-12:10PM
READING ASSIGNMENT
Horstmann Chapter 15 – Streams
 Horstmann Chapter 14 – Exceptions


Optional
– Horstmann Chapter 16 – System Design
– Horstmann Chapter 17, 18, 19
 Prep for CSC 172
EXAM

In class 12/9
– Arrays
– Exceptions
– Streams
Streams

In Java a stream provides access to
sequences of bytes.
 Bytes can come from a variety of sources
– Console input/output
– Files stored on the computer’s disk
– Network connections
_________ access sequences of bytes.
___Streams______ access sequences of bytes.
Simplest File input

Create a FileReader
 Use its read method to read a single
character
-returns the next char as an int or the integer
-1 at end of input
 Test for -1
 If not -1, cast to char
 Close the file when done
___________ and ________________ access
sequences of characters.
_readers______ and ____writers____ access
sequences of characters.
Reading
FileReader reader = new FileReader("input.txt");
int next = reader.read() ;
char c;
if (next != -1)
c = (char)next();
...
reader.close()
Writing
FileWriter writer = new FileWriter("output.txt");
...
char c='';
...
writer.write(c);
...
write.close();
The read method returns an
_________________,
either ___________ at end of file, or another
value which needs to be cast to
___________, or ___________.
The read method returns an ___integer_____,
either ____-1_______ at end of file, or
another value which needs to be cast to
___char____, or ____byte_______.
You must _______________ files that you no
longer need.
You must ___close______ files that you no
longer need.
TEXT FORMAT

Human-readable form
 Sequence of characters
-Integer 12345 stored as characters "1" "2"
"3" "4" "5"
 Use Reader and Writer and their subclasses
Writing text files

Use a PrintWriter
-breaks up strings into individual characters
-sends them one at a time to a FileWriter
 Create a PrintWriter
FileWriter writer = new FileWriter("output.txt");
PrintWriter out = new PrintWriter(writer);

Use print and println
out.println(29.95);
out.println(new Rectangle(5,10,15,25));
out.println("Hello, World!");

Use a BufferedReader
-Reads a character at a time from a FileReader
-Assembles the characters into a line and returns it
 Use Integer.parseInt or Integer.parseDouble to
convert the strings to numbers
 Code
FileReader reader = new FileReader ("input.txt");
BufferedReader in = new BufferedReader(reader);
String inputLine = in.ReadLine();
double x = Double.parseDouble(inputLine);
Basic streams, readers, and writers can
process only _____________________.
You need to combine them with other
classes to process _______________ or
_________________.
Basic streams, readers, and writers can
process only _individual bytes or
chars______. You need to combine them
with other classes to process
___lines______ or ____objects______.
When writing text files, use
________________ class and the
_____________________ methods.
When reading text files, use
_______________ class and the
____________ method.
When writing text files, use
_____PrintWriter______ class and the
____print/println__________ methods.
When reading text files, use
_____BufferedReader________ class and
the ___readLine______ method.
File

File class describes disk files and directories
 Create a File object
File inputFile = new File("input.txt");
 Some file methods
delete
renameTo
exists

Constructing a FileReader from a File object
FileReader reader = new FileReader(inputFile) ;
A File object describes a ___________ or
__________________.
A File object describes a _____file_______ or
_______directory___________.
You can pass a File object to the constructor
of a file ____________, _________, or
stream.
You can pass a File object to the constructor
of a file ____reader_________,
___writer________, or stream.
File Chooser
File Choser

Construct a file chooser object
 Call its showOpenDialog or showSaveDialog method
 Specify null or the user interface component over which to
pop up the dialog
 If the user chooses a file, these methods return
JFileChooser.APPROVE_OPTION
 If the user cancels the selection, these methods return
JFileChooser.CANCEL_OPTION
 If a file is chosen, use GetSelectedFile method to obtain a
File object describing the file
Code
JFileChooser chooser = new JFileChooser();
FileReader in = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION) {
File selectedFile= chooser.getSelectedFile();
in = new FileReader(selectedFile);
}
The ______________________________
dialog lets users select a file by navigating
directories.
The _JFileChooser__________ dialog lets
users select a file by navigating directories.
Command Line
Java MyProgram -d file.txt
class MyProgram {
public static void main(String[] args) { ...
// arg[0] == “-d”
// arg[1] == “file.txt”
}
}

When you launch a program from the
command line, you can specify arguments
after the program name. The program can
access these strings by processing the
______________ parameter of the
___________ method.

When you launch a program from the
command line, you can specify arguments
after the program name. The program can
access these strings by processing the
_____”args”___ parameter of the
___main___ method.
Binary Format

More compact and efficient
 Integer 12345 stored as 00 00 48 57
 Use InputStream and OutputStream and
their subclasses
File IO

We have seen character I/O
 Sometimes, we want to have other data
types stored in file
– It’s all just bits
Consider saving an array
a = new float[5][5];
for(int i = 0 ; i<a.length;i++)
for(int j = 0 ; j<a[i].length;j++)
a[i][j] = ((float)i+1) /
((float)j+1) ;
Open the File
private void saveArray() {
try {
JFileChooser chooser = new JFileChooser();
PrintWriter out1 = null;
if (chooser.showOpenDialog(null)==
JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
FileWriter writer = new FileWriter(selectedFile);
out1 = new PrintWriter(writer);
Write the array
for(int i = 0 ; i<a.length;i++)
for(int j = 0 ; j<a[i].length;j++){
out1.println(a[i][j] + "
");
System.out.println(" " + a[i][j]);
}
writer.close();
}
} catch (IOException e)
{System.out.println("problem");}
}
Open the file
private void restoreArray() {
try {
JFileChooser chooser = new JFileChooser();
BufferedReader in1 = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
FileReader reader = new FileReader(selectedFile);
in1 = new BufferedReader(reader);
Read the array
for(int i = 0 ; i<a.length;i++)
for(int j = 0 ; j<a[i].length;j++){
String s1 = in1.readLine();
System.out.println(s1);
a[i][j] = (float) Double.parseDouble(s1);
}
reader.close();
}
} catch (IOException e) {System.out.println("problem");}
repaint();
}
Text File
Text File
1.0
0.5
0.33333334
0.25
0.2
2.0
1.0
0.6666667
0.5
0.4
3.0
1.5
1.0
0.75
0.6
4.0
2.0
1.3333334
1.0
0.8
5.0
2.5
1.6666666
1.25
1.0
Byte by Byte Text file 303
bytes
0000000
0000020
0000040
0000060
0000100
0000120
0000140
0000160
0000200
0000220
0000240
0000260
0000300
0000320
0000340
0000360
0000400
0000420
0000440
0000457
1
.
0
\r
.
\n
\r
5
0
\n
.
1
0
.
\n
\r
.
\n
0
3
5
3
0
0
\n
.
0
6
.
\r
6
5
\r
\n
1
.
.
\n
4
.
\n
\n
\r
1
.
.
6
.
3
0
6
0
.
\n
\r
0
1
\n
5
3
3
4
\r
\n
2
7
\r
0
\n
\r
\r
\n
3
.
0
\n
0
.
7
.
\r
6
3
.
\r
3
0
\n
3
2
3
1
\n
.
1
8
\r
0
\n
1
6
0
3
5
0
4
\r
5
\n
3
2
0
\r
.
\n
6
4
\r
\n
0
\r
2
\r
\r
.
3
\n
0
\r
\n
\r
\r
3
.
.
1
6
.
\r
6
2
\n
6
5
2
6
.
6
5
6
\r
\n
6
Open the file (binary)
private void saveArray2() {
try {
JFileChooser chooser = new JFileChooser();
DataOutputStream out1 = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
FileOutputStream writer = new
FileOutputStream(selectedFile);
out1 = new DataOutputStream(writer);
Write the file
for(int i = 0 ; i<a.length;i++)
for(int j = 0 ; j<a[i].length;j++){
out1.writeFloat(a[i][j]);
System.out.println(" " + a[i][j]);
}
writer.close();
}
} catch (IOException e) {System.out.println("problem");}
}
}
Open the file
private void restoreArray2() {
try {
JFileChooser chooser = new JFileChooser();
DataInputStream in1 = null;
if (chooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
FileInputStream reader = new FileInputStream(selectedFile);
in1 = new DataInputStream(reader);
Read the file
for(int i = 0 ; i<a.length;i++)
for(int j = 0 ; j<a[i].length;j++){
a[i][j] = in1.readFloat();
}
reader.close();
}
} catch (IOException e) {System.out.println("problem");}
repaint();
}
Same data - 100 Bytes
0000000
0000020
0000040
0000060
0000100
0000120
0000140
1.0000000e+00
2.0000000e-01
5.0000000e-01
1.0000000e+00
2.0000000e+00
5.0000000e+00
1.0000000e+00
5.0000000e-01
2.0000000e+00
4.0000001e-01
7.5000000e-01
1.3333334e+00
2.5000000e+00
3.3333334e-01
1.0000000e+00
3.0000000e+00
6.0000002e-01
1.0000000e+00
1.6666666e+00
2.5000000e-01
6.6666669e-01
1.5000000e+00
4.0000000e+00
8.0000001e-01
1.2500000e+00
Data Streams
close()
readBoolean()
readByte()
readChar()
readDouble()
readFloat()
readInt()
readLong()
readShort()
readLine()
flush()
close()
writeByte(int b)
writeBoolean(boolean v)
writeBytes(String s)
writeChar(int v)
writeChars(String s)
writeDouble(Double v)
writeFloat(Float v)
writeInt(int v)
writeLong(long v)
writeShort(int v)
Example Cryptology
Ceasar Cipher
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Crypt{
public static void main(String[] args){
boolean decrypt = false;
int key = DEFAULT_KEY;
FileReader infile = null;
FileWriter outfile = null;
if (args.length < 2 || args.length > 4) usage();
try
{ for(int i = 0; i < args.length; i++)
{ if (args[i].substring(0, 1).equals("-"))
// it is a command line option
{ String option = args[i].substring(1, 2);
if (option.equals("d"))
decrypt = true;
else if (option.equals("k"))
{ key = Integer.parseInt
(args[i].substring(2));
if (key < 1 || key >= NLETTERS)
usage();
}
}
else
{ if (infile == null)
infile = new FileReader(args[i]);
else if (outfile == null)
outfile = new FileWriter(args[i]);
}
}
}
catch(IOException e){
System.out.println("Error opening file");
System.exit(0);
}
if (decrypt) key = NLETTERS - key;
try {
encryptFile(infile, outfile, key);
infile.close();
outfile.close();
}
catch(IOException e) {
System.out.println("Error processing file");
System.exit(0);
}
}
/**
Prints a message describing proper usage and exits.
*/
public static void usage() {
System.out.println
public static char encrypt(char c, int k) {
if ('a' <= c && c <= 'z')
return (char)('a' + (c - 'a' + k) % NLETTERS);
if ('A' <= c && c <= 'Z')
return (char)('A' + (c - 'A' + k) % NLETTERS);
return c;
}
public static void encryptFile(FileReader in,
FileWriter out, int k) throws
IOException {
while (true) {
int next = in.read();
if (next == -1)return; // end of file
char c = (char)next;
out.write(encrypt(c, k));
}
}
public static final int DEFAULT_KEY = 3;
public static final int NLETTERS = 'z' - 'a' + 1;
}
Serializable Objects

We can write whole objects to files
 Using object streams
 must implement “Serializable”

Use ______________________ to save
and restore all instance fields of an object
automatically.

Use ____object streams________ to save
and restore all instance fields of an object
automatically.

Objects saved to and object stream must
belong to a class that implements the
______________________ interface.

Objects saved to and object stream must
belong to a class that implements the
___Serializable_________ interface.
public AccountRecord( int acct, String first,
String last, double bal ) {
setAccount( acct );
setFirstName( first );
setLastName( last );
setBalance( bal );
}
public void setAccount( int acct ) { account = acct; }
public int getAccount() {
return account; }
public void setFirstName( String first ) { firstName = first; }
public String getFirstName() {
return firstName; }
public void setLastName( String last ) { lastName = last; }
public String getLastName() { return lastName; }
public void setBalance( double bal ) { balance = bal; }
public double getBalance() { return balance; }
public String toString(){
return "Account Record "
+ " " + account
+ " " + firstName
+ " " + lastName
+ " " + balance;
}
}
// Java core packages
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreateSequentialFile extends JFrame{
private ObjectOutputStream output;
public CreateSequentialFile(){
AccountRecord record;
openFile();
try {
// create new record
record = new AccountRecord( 1, "Ted","Pawlicki",100);
System.out.println(record.toString());
output.writeObject( record );
output.flush();
// create new record
record = new AccountRecord( 2, "Adam","Frank",2000);
System.out.println(record.toString());
output.writeObject( record );
output.flush();
// allow user to specify file name
private void openFile()
{
// display file dialog, so user can choose file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showSaveDialog(this);
// get selected file
File fileName = fileChooser.getSelectedFile();
// display error if invalid
if ( fileName == null ||
fileName.getName().equals( "" ) ){
System.err.println( "Invalid File Name");
return;
}
else {// open file
try {
output = new ObjectOutputStream(
new FileOutputStream( fileName ) );
}
// process exceptions from opening file
catch ( IOException ioException ) {
System.err.println( "Error Opening File");
return;
}
}
// close file and terminate application
private void closeFile()
{
// close file
try {
output.close();
System.exit( 0 );
}
// process exceptions from closing file
catch( IOException ioException ) {
System.err.println( "Error closing file");
System.exit( 1 );
}
}
public static void main( String args[] )
{
new CreateSequentialFile();
}
}
public ReadSequentialFile(){
AccountRecord record;
openFile();
try {
// create new record
record = (AccountRecord) input.readObject();
System.out.println(record.toString());
record = (AccountRecord) input.readObject();
System.out.println(record.toString());
record = (AccountRecord) input.readObject();
System.out.println(record.toString());
}
catch(ClassNotFoundException e) {
System.err.println(" Problem with class ");
System.exit(1);
}
catch(IOException e) {
System.err.println(" Problem with file ");
System.exit(1);
}
closeFile();
}
0000000 254 355 \0 005 s r \0 \r A c c o u n t R
0000020 e c o r d G 346 306 343 235 233 005 \r 002 \0 004
0000040 I \0 007 a c c o u n t D \0 007 b a l
0000060 a n c e L \0 \t f i r s t N a m e
0000100 t \0 022 L j a v a / l a n g / S t
0000120 r i n g ; L \0 \b l a s t N a m e
0000140 q \0 ~ \0 001 x p \0 \0 \0 001 @ Y \0 \0 \0
0000160 \0 \0 \0 t \0 003 T e d t \0 \b P a w l
0000200 i c k i s q \0 ~ \0 \0 \0 \0 \0 002 @ 237
0000220 @ \0 \0 \0 \0 \0 t \0 004 A d a m t \0 005
0000240 F r a n k s q \0 ~ \0 \0 \0 \0 \0 003 A
0000260 c 022 320 \0 \0 \0 \0 t \0 003 J o e t \0 005
0000300 S c h m o
0000305
Related documents