Sunteți pe pagina 1din 105

Lectured by: CHEA VICHET

Tel: 077 657 007


 Java, Information store retrieve
communication system Stream
java.io package

 input stream read


information output stream store information
 Byte Stream: bytes, integers, data type

 Character Stream: text file
 I/O Stream input source output
destination

 Stream source destination


 disk file, devices, other programs, a network socket, and
memory arrays

 Stream support

 bytes, primitive data type, localized characters, and
objects

input stream read data source
(one item at a time)

output stream write data
destination (one item at a time)
 Character Stream Byte Stream
 Character vs. Byte

 Input Stream Output Stream


 Base on Source or Destination

 Node Stream Filter Stream


 data stream manipulate transform
?
 Byte Stream  Character Stream
 Binary Data  unicode

 Root class byte  Root class


stream: character stream:
InputStream Reader
OutputStream Writer
abstract abstract
class class
 Input Stream (Source  Output Stream
Stream) (Destination Stream)
 Read from stream  Write to stream
 Root class  Root class
InputStream OutputStream
Reader Writer
abstract class abstract class
 Input Stream
 source file hard drive FileInputStream
 read information method read() return byte
file
 read information method close()

 Output Stream
 object data's destination
BufferedWriter class
 method write()
data output stream's
destination
 method close()
 Filter stream

stream


Filter


1. stream data source data destination
2. filter stream
3. read write data filter (
stream )
 Exception java.io package
files stream

 FileNotFound stream file object

 EOFException: read file (end of file)


 exception subclass IOException

try {
// working with file or stream
} catch (IOException e) {
System.out.println(e.getMessage());
}
 Byte stream subclass InputStream
OutputStream Class abstract

stream object class

stream subclass
 FileInputStream FileOutputStream: Byte
stream stored in file on Disk, CD-ROM, or other storage
devices
 DataInputStream DataOutputStream: a filtered
byte stream from which data such as integer and floating
point number can be read.
 Byte Stream represents a kind of low-level I/O
that you should avoid
 If the data contains character data, the best approach
is to use character stream

 Byte Streams should only be used for most


primitive I/O

 All streams are based on byte stream


Constructor Summary
FileOutputStream(String name)
name file
FileOutputStream(String name, boolean append)
append true file

Method Summary
void write(byte[] b)
Writes b.length bytes from the specified byte array to this file output stream.

void write(byte[] b, int off, int len)


Writes len bytes from the specified byte array starting at offset off to this file
output stream.

void write(int b)
Writes the specified byte to this file output stream.
import java.io.FileOutputStream; // [ Code ]
import java.io.IOException;

public class NewFile {

public static void main(String args[]) throws IOException {

FileOutputStream fos = null;

try {
fos = new FileOutputStream("readme.txt");

// write(int c)
for (char c = 'a'; c<='z'; c++) {
fos.write(c);
}

// write(byte[] b)
byte[] b = {'H','e','l','l','o'};
fos.write(b);
// write(byte[], int offset, int length)
byte[] c = {'W','e','l','c','o','m','e'};
fos.write(c, 0, 2); //We
fos.write(c, 2, 5); //come
There is no way to
} finally {
if (fos != null) { write a new line
fos.close();
character by using
}
} FileOutputStream!

}
}
Constructor Summary

FileInputStream(String name)
name file

Method Summary
int read()
Reads a byte of data from this input stream.

int read(byte[] b)
Reads up to b.length bytes of data from this input stream into an array of bytes.

int read(byte[] b, int off, int len)


Reads up to len bytes of data from this input stream into an array of bytes.
import java.io.FileInputStream; // [ Code ]
import java.io.IOException;
import javax.swing.JOptionPane;

public class ReadTextFile {

public static void main(String[] args) throws IOException {

FileInputStream fis = null;


StringBuffer str = new StringBuffer();

try {
fis = new FileInputStream("readme.txt");

int c = fis.read(); // read once a byte

while (c != -1) {
str.append((char) c);
c = fis.read(); // read once a byte
}
} finally {
if (fis != null) {
fis.close();
}
JOptionPane.showMessageDialog(null, str);
}
}
}
int c = fis.read();

while (c != -1) { If you forget something!


. . . unfinished loop
. . .
c = fis.read();
}

int c;

while ((c = fis.read()) != -1) {


. . .
. . .
. . .
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyByte {

public static void main(String[] args) throws IOException {

FileInputStream fis = null;


FileOutputStream fos = null;

try {
// source.txt must exist
fis = new FileInputStream("source.txt");

// new or over write


fos = new FileOutputStream("destination.txt");
int c;

/*
* read() return the next byte of data,
* or -1 if the end of the stream is reached.
*/
while ((c = fis.read()) != -1){
fos.write(c);
}

} finally {
if (fis != null) {
fis.close();
} copy
if (fos != null) {
fos.close();
}
}
}
}
 public int read() throws IOException
 (byte) input stream byte int (0

.. 255) byte return -1

FileInputStream fis = null; [ Code ]


try {
fis = new FileInputStream(fileName);
int c;
H
while ((c = fis.read()) != -1) { e
System.out.println ((char) c); l
} l
} finally { o
if (fis != null) {
fis.close(); S
} t
u
}
d
e
n
t
 public int read(byte[] b) throws IOException
 bytes byte.length input stream
byte[]

FileInputStream fis = null; // [ Code ]

try {
fis = new FileInputStream("data.txt");
int size = 5; // 5 chars
byte[] bs = new byte[size]; Hello
Java
while (fis.read(bs) != -1) { Stud
for (byte b : bs) { ent
System.out.print ((char) b);
}
System.out.println ();
bs = new byte[size]; //clean array
}
} finally {
if (fis != null) {
fis.close();
}
}
. . .

public class AppendFile {

public byte[] toByteArray(String str){


byte[] bs = new byte[str.length()];
for (int i = 0; i<str.length(); i++) {
bs[i] = (byte) str.charAt(i);
}
return bs;
}

public void appendSomething() throws IOException {

FileOutputStream fos;
fso = new FileOutputStream("note.txt", true); // append
// [ Code ]
try {
String str = JOptionPane.showInputDialog("Input
some text");
byte[] bs = toByteArray(str);
fos.write(bs);
} finally {
if (fos != null) {
fos.close();
}
}
}

public static void main(String args[])


throws IOException {
AppendFile af = new AppendFile();
af.appendSomething();
}

}
1- What is the method you call at the end of I/O
operation?

2- What is wrong with the following statement?


Assume that outStream is a properly declared and
created FileOutputStream object.

byte[] byteArray = {(byte)'H', (byte)'i'};


. . .
outStream.print(byteArray);
. . .
outStream.close():
 Character Stream text
ASCII Unicode
 Plain text file: HTML document (*.HTML)
 Java source file (*.java)

 Class read write stream


subclass class Reader class Writer
 FileReader
 subclass InputStreamReader
 byte stream integer
Unicode Character
import java.io.*;

public class ReadCharacter {

public static void main(String args[]) throws IOException {


FileReader fr = new FileReader("someFile.txt");
try {
int b;
while ((b = fr.read()) != -1) {
System.out.print((char) b);
}
} finally {
if (fr != null) {
fr.close();
}
}
}
}
This is Text File.
 FileWriter
 subclass OutputStreamReader
 Unicode character byte
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacter {

public static void main(String args[]) throws IOException {

FileReader reader = null;


FileWriter writer = null;

try {
reader = new FileReader("someFile.txt");
writer = new FileWriter("character-output.txt");

int b;

while ((b = reader.read()) != -1) {


writer.write(b);
}
} finally {
if (reader != null) reader.close();
if (writer != null) writer.close();
}
}
}
 Constructor
 BufferedReader(Reader in)

 Method
 int read()
Reads a single character.
 int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.
 String readLine()
Reads a line of text.
import java.io.*; // [ Code ]
. . .
try {
FileReader file = new
FileReader("SourceReader.java");
BufferedReader buff = new BufferedReader(file);

String line;

while ((line = buff.readLine()) != null) {


System.out.println (line);
}
} catch (IOException e) {
System.out.println ("Error: "+ e.toString());
}
import java.io.*; // [ Code ]

public class SourceReader {

public static void main(String args[]) {


try {
FileReader file = new
FileReader("SourceReader.java");
BufferedReader buff = new BufferedReader(file);

String line;

while ((line = buff.readLine()) != null) {


System.out.println (line);
}
} catch (IOException e) {
System.out.println ("Error: "+ e.toString());
}
}
}
 Constructor
 BufferedWriter(Writer out)

 Method
 void newLine()
Writes a line separator.
 void write(String str)
Write a string
[ Code ]

try {
FileWriter file = new FileWriter("myNote.txt");
BufferedWriter buff = new BufferedWriter(file);

buff.write("Today I study Java.");


buff.newLine(); // break a new line
buff.write("Tomorrow I will be a programmer");
buff.flush();
buff.close();
file.close();

} catch (IOException e) {
System.out.println ("Error : "+ e.toString());
}
 Write file
 newLine():
 write(String): String file

try {
FileWriter file = new FileWriter("myNote.txt");
BufferedWriter buff = new BufferedWriter(file);

buff.write("Today I study Java.");


buff.newLine(); // break a new line
buff.write("Tomorrow I will be a programmer");
buff.flush();
buff.close(); // you must close, otherwise, it is not saved.
file.close();

} catch (IOException e) {
System.out.println ("Error : "+ e.toString());
}
Constructor
PrintWriter(Writer out)
Creates a new PrintWriter, without automatic line flushing.
PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.

Method
void println(String x)
Prints a String and then terminates the line.
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

import javax.swing.*;

public class AutoFlashPrintWriter { [ Code ]


public static void main(String args[]) throws IOException {

FileWriter fw = null;
PrintWriter pw = null;

try {
fw = new FileWriter("auto-flash-with-PrintWriter.txt");
pw = new PrintWriter(fw, true);

pw.println("This line is automatically written.");


JOptionPane.showMessageDialog(null, "Success Writing 1.");

} finally { No need pw.flash()


if (fw != null) fw.close();
if (pw != null) fw.close();
}
}
}
 Three standard streams
 System.in
 System.out
 System.err

 System.in
 System.in is an InputStream which is typically connected to
keyboard input of console programs.
 System.in is not used as often since data is commonly
passed to a command line Java application via command
line arguments, or configuration files.
 System.out
 System.out is a PrintStream.
 System.out normally outputs the data you write to it to the
console.
 Often used to print debug statements

 System.err
 System.err is a PrintStream.
 System.err works like System.out except it is normally only used
to output error texts.
 Some programs (like Eclipse) will show the output to System.err
in red text, to make it more obvious that it is error text.
FileOutputStream f = null; [ Code ]
PrintStream ps = null;

try {
f = new FileOutputStream("log.txt", true);
ps = new PrintStream(f);
System.setErr(ps);

System.out.println (10 / 0);

} catch (ArithmeticException e){


System.out.println ("Error: See in log.txt for
detail.");
System.err.println(new Date() + ": Divide by 0");

} catch (IOException e) {
System.out.println ("Error: See in log.txt for
detail.");
System.err.println(e.getMessage());
}
 Data streams support binary I/O of primitive data
type value (boolean, char, short, int,
long, float, and double) as well as String
values.

 All data streams implement either the DataInput


interface or the DataOutput interface

 DataInputStream and DataOutputStream are most


widely-used implementations of these interfaces.
 DataOutputStream can only be created as a wrapper for an existing byte
stream object

 Constructor:

public DataOutputStream(OutputStream out)

 Example:

DataOutputStream output = new DataOutputStream(


new FileOutputStream("binary.data"));

output.write(45); //byte data


output.writeInt(4545); //int data
output.writeDouble(109.123); //double data
output.writeUTF("I Love You = "); //Unicode data
output.close();
 Constructor:

public DataInputStream(InputStream out)

 Example:

FileInputStream f = new FileInputStream("binary.data");


DataInputStream input = new DataInputStream(f);

String s = "";
s += input.read() + "\n";
s += input.readInt() +"\n";
s += input.readDouble() +"\n";
s += input.readUTF();
JOptionPane.showMessageDialog(null, s );
 It is not a stream class
 It also is part of java.io package
 It represents a file or folder reference.
public File(String pathname)
 Create a new File instance by converting the given
pathname string into an abstract pathname. If the given string
is the empty string, then the result is the empty abstract
pathname.

Parameters:
pathname A pathname string
Throws:
NullPointerException If the pathname argument is null
Modifier Method and Description
and Type
boolean canExecute()
Tests whether the application can execute the file denoted by
this abstract pathname.
boolean canRead()
Tests whether the application can read the file denoted by this
abstract pathname.
boolean canWrite()
Tests whether the application can modify the file denoted by this
abstract pathname.
boolean exists()
Tests whether the file or directory denoted by this abstract
pathname exists.
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.
String getPath()
Converts this abstract pathname into a pathname string.
boolean isAbsolute()
Tests whether this abstract pathname is absolute.
boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a
directory.
boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal
file.
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.
String[] list()
Returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname.
// FileDemonstration.java
import java.io.File;
import java.util.Scanner;

public class FileDemonstration {

public static void println(String str) {


System.out.println (str);
}

public static void main(String args[]) {


Scanner input = new Scanner(System.in);
System.out.print("Input a path: ");
analyzePath(input.nextLine());
}

public static void analyzePath(String path) {

//Create File object base on user input


File name = new File(path);

if (name.exists()) {
println(name.getName() + " exists");
println(name.isDirectory() ? "is a directory" :
"is not a directory" );
println(name.isAbsolute() ? "is absolute path" :
"is not absolute path");
println("Last modified : " + name.lastModified());
println("Length : "+ name.length());
println("Absolute path : "+ name.getAbsolutePath());
println("Parent : "+ name.getParent());

if (name.isDirectory()) {
String[] directory = name.list();
println("\nDirectory contents:\n");
for (String directoryName : directory) {
println(directoryName);
} // end for
} // end if
} else {
println(path + " does not exist.");
} // end else
} // end method analyzePath
} // end class FileDemonstration
Input a path: g:\upjava
upjava exists
is a directory
is absolute path
Last modified : 1332249360206
Length : 4096
Absolute path : g:\upjava
Parent : g:\

Directory contents:

Greeting.class
Greeting.java

Input a path: g:\upjava\Greeting.java


Greeting.java exists
is not a directory
is absolute path
Last modified : 1332249360206
Length : 320
Absolute path : g:\upjava\Greeting.java
Parent : g:\upjava
 In addition to the java.io package, character-based
input and output can be performed with classes
Scanner and Formatter.

 Class Scanner is used extensively to input data from


the keyboard it can also read date from a file.

 Class Formatter enables formatted date to be
output to any text-based stream in a manner similar
to method System.out.printf.
 Now, we want to create a simple AccountRecord
sequential-access file that might
be used in an accounts receivable - account : int
- firstName : String
system to keep track of the - lastName : String
amounts owed to a company by - balance : double
its credit clients. .....

 Class AccountRecord contains


private instance variables
account, firstName,
lastName, and balance and
set and get method for
accessing these fields.
// AccountRecord.java
public class AccountRecord { AccountRecord
- account : int
private int account;
- firstName : String
private String firstName;
- lastName : String
private String lastName;
private double balance;
- balance : double
.....
public AccountRecord() {
this(0, "", "", 0.0);
}

public AccountRecord(int account, String firstName, String lastName,


double balance) {
this.account = account;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
}

// Other setXXXX and getXXXX methods...


}
 CreateTextFile declare Formatter variable output.
 A Formatter object can output to various
location, such as the screen or a file.

CreateTextFile
- output : Formatter

+ openFiel(): void
+ addRecords(): void
+ closeFile(): void
1. // CreateTextFile.java
2. import java.io.FileNotFoundException; CreateTextFile
3. import java.lang.SecurityException;
4. import java.util.Formatter;
- output : Formatter
5. import java.util.FormatterClosedException;
6. import java.util.NoSuchElementException; + openFiel(): void
7. import java.util.Scanner;
8.
+ addRecords(): void
9. public class CreateTextFile { + closeFile(): void
10.
11. private Formatter output;
12.
13. public void openFile(){
14.
15. try {
16. output = new Formatter("clients.txt");
17.
18. } catch(SecurityException e) {
19. System.err.println("You do not have write access to this file.");
20.
21. } catch(FileNotFoundException e) {
22. System.err.println("Error opening or creating file.");
23. System.exit(1); // terminate the program
24. }
25. }
26. public void addRecord() {
27.
28. AccountRecord record = new AccountRecord();
29. Scanner input = new Scanner(System.in);
30.
31. System.out.printf("%s\n%s\n%s\n%s\n\n",
32. "To terminate input, type the end-of-file indicator ",
33. "when you are prompted to enter input.",
34. "On UNIx/Linux/Max OS X type <ctrl> d then press Enter",
35. "On Windows type <ctrl> z then press Enter.");
36.
37. System.out.printf ("%s\n%s",
38. "Enter account number (> 0), first name, last name and balance.",
39. "? ");
40.
41. // loop until end-of-file indicator
42. while (input.hasNext()) {
43. try {
44. record.setAccount(input.nextInt()); // read account number
45. record.setFirstName(input.next()); // read first name
46. record.setLastName(input.next()); // read last name
47. record.setBalance(input.nextDouble()); // read balance
48.
49. if (record.getAccount() > 0) {
50. // write new record
51. output.format("%d %s %s %.2f%n",
52. record.getAccount(), record.getFirstName(),
53. record.getLastName(), record.getBalance() );
54. } else {
55. System.out.println ("Account number must be > 0");
56. }
57. } catch (FormatterClosedException e) {
58. System.out.println ("Error writing to file");
59. return;
60. } catch (NoSuchElementException e) {
61. System.err.println("Invalid input, Please try again.");
62. input.nextLine();// discard input so usr can try again
63. }
64.
65. System.out.printf ("%s\n%s", "Enter account number (> 0),
first name, last name and balance.", "? ");
66. }
67. }
68.
69. public void closeFile() {
70. if (output != null) output.close();
71. }
72. }
To terminate input, type the end-of-file indicator
when you are prompted to enter input.
On UNIx/Linux/Max OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter.

Enter account number (> 0), first name, last name and balance.
? 100 Bob Jones 24.89
Enter account number (> 0), first name, last name and balance.
? 200 Steve Doe -345.67
Enter account number (> 0), first name, last name and balance.
? 300 Pam White 0.00
Enter account number (> 0), first name, last name and balance.
? 400 Sam Stone -42.16
Enter account number (> 0), first name, last name and balance.
? 500 Sue Rich 224.62
Enter account number (> 0), first name, last name and balance.
? ^Z
 Data is stored in a file so that it may be retrieved for processing
when needed.

 This section shows how to read data sequentially from a text


file.

 We demonstrate how class Scanner can be used to input data


from a file rather than the keyboard.

File file = new File("anyFile.txt");


Scanner input = new Scanner(file);
while (input.hasNext()) {
System.out.println(input.nextLine());
}
1. import java.io.* // [ Code ]
2. import java.util.*
3.
4. public class ReadSequentialTextFile {
5.
6. private Scanner input;
7.
8. public void open() {
9. try {
10. input = new Scanner(new File("clients.txt"));
11. } catch (FileNotFoundException e) {
12. System.err.println("Error opening a file.");
13. System.exit(1);
14. }
15. }
16.
17. public void readRecords() {
18. String format = "%-10s%-12s%-12s%10s\n";
19.
20. AccountRecord record = new AccountRecord();
21. System.out.printf(format, "Account","First Name", "Last Name", "Balance");
22. try {
23. while (input.hasNext()) {
24.
25. // read from file to record object
26. record.setAccount(input.nextInt());
27. record.setFirstName(input.next());
28. record.setLastName(input.next());
29. record.setBalance(input.nextDouble());
30.
31. // display record contents
32. System.out.printf(format,
33. record.getAccount(), record.getFirstName(),
34. record.getLastName(), record.getBalance() );
35.
36. } // end while
37.
38. } catch (NoSuchElementException e){
39. System.err.println ("File improperly formed.");
40. this.closeFile();
41. System.exit(1);
42.
43. } catch (IllegalStateException e) {
44. System.err.println("Error reading from file.");
45. System.exit(1);
46. } // end try-catch
47. }
48.
49. public void closeFile() {
50. if (input != null) {
51. input.close();
52. }
53. }
54. }
public class ReadTextFileTest {

public static void main(String args[]) {


ReadSequentialTextFile application =
new ReadSequentialTextFile();
application.open();
application.readRecords();
application.closeFile();
}
}

Account First Name Last Name Balance


100 Bob Jones 24.89
200 Steve Doe -345.67
300 Pam White 0.0
400 Sam Stone -42.16
500 Sue Rich 224.62
 To receive data sequentially from a file, programs start from
the beginning of the file and read all the data consecutively
until the desired information in found. It might be necessary
to process the file sequentially several time (from the
beginning file) during the execution of the program.

 Class Scanner does not allow repositioning to the beginning


of the file. If it is necessary to read the file again, the program
must close the file and reopen it.

 Next program allows a credit manager to obtain lists of


customers with zero balances, customers with credit
balances ( ), and customers with debit balances
() . A credit balance is a negative amount, a debit
balance is a positive amount
 We begin with enum type to define the different menu options user will
have. [ Code ]
public enum MenuOption {

// declare constans of enum type


ZERO_BALANCE(1), CREDIT_BALANCE(2),
DEBIT_BALANCE(3), END(4);

private final int value; // current menu option

//constructor
MenuOption(int valueOption) {
value = valueOption;
}

public int getValue() {


return value;
}
}
 CreditInquiry contains the functionality for the
credit-inquiry program.

 CreditInquiryTest contains the main method that


executes the program. The program displays a text
menu and allows the credit manager to enter one of
the three options to obtain credit information.

 Option 1 (ZERO_BALANCE)
 Option 2 (CREDIT_BALANCE)
 Option 3 (DEBIT_BALANCE)
 Option 4 (END)
1. import java.io.*; // [ Code ]
2. import java.lang.IllegalStateException;
3. import java.util.*;
4.
5. public class CreditInquiry {
6.
7. private MenuOption accountType;
8. private Scanner input;
9. private final static MenuOption[] choice = {
10. MenuOption.ZERO_BALANCE, MenuOption.CREDIT_BALANCE,
11. MenuOption.DEBIT_BALANCE, MenuOption.END
12. };
13.
14. private void readRecords() {
15. String format = "%-10s%-12s%-12s%10s\n";
16. AccountRecord record = new AccountRecord();
17.
18. try {
19. input = new Scanner(new File("clients.txt"));
20.
21. while (input.hasNext()) {
22. record.setAccount(input.nextInt());
23. record.setFirstName(input.next());
24. record.setLastName(input.next());
25. record.setBalance(input.nextDouble());
26. if (shouldDisplay(record.getBalance())) {
27. System.out.printf (format,
28. record.getAccount(),
29. record.getFirstName(),
30. record.getLastName(),
31. record.getBalance());
32. } // end if
33. } // end while
34. } catch (NoSuchElementException e) {
35. System.err.println("File improperly formed.");
36. input.close();
37. System.exit(1);
38. } catch (IllegalStateException e) {
39. System.err.println("Error reading from file.");
40. System.exit(1);
41. } catch (FileNotFoundException e) {
42. System.err.println("File cannot be found.");
43. System.exit(1);
44. } finally {
45. if (input != null) {
46. input.close();
47. }
48. }
49. }
50. private boolean shouldDisplay(double balance){
51. if ((accountType == MenuOption.CREDIT_BALANCE) && (balance < 0)) {
52. return true;
53. } else if ((accountType == MenuOption.DEBIT_BALANCE) && (balance > 0)) {
54. return true;
55. } else if ((accountType == MenuOption.ZERO_BALANCE) && (balance == 0)) {
56. return true;
57. }
58. return false;
59. } // end method shouldDisplay
60.
61. private MenuOption getRequest() {
62. Scanner textIn = new Scanner(System.in);
63. int request = 1;
64.
65. System.out.println ("\nEnter request");
66. System.out.println ("1 - List accounts with zero balances");
67. System.out.println ("2 - List accounts with credit balances");
68. System.out.println ("3 - List accounts with debit balances");
69. System.out.println ("4 - End of run");
70.
71. try {
72. do {
73. System.out.print ("\n? ");
74. request = textIn.nextInt();
75. } while ((request < 1) || (request > 4));
76. } catch (NoSuchElementException e) {
77. System.err.println("Invalid input");
78. System.exit(1);
79. }
80. return choice[request - 1];
81. }
82.
83. public void processRequest(){
84. accountType = getRequest();
85. while (accountType != MenuOption.END) {
86. switch (accountType) {
87. case ZERO_BALANCE:
88. System.out.println ("\nAccounts with zero balances:\n");
89. break;
90. case CREDIT_BALANCE:
91. System.out.println ("\nAccounts with credit balances:\n");
92. break;
93. case DEBIT_BALANCE:
94. System.out.println ("\nAccounts with debit balances:\n");
95. break;
96. }
97. readRecords();
98. accountType = getRequest();
99. } // end while
100. } // end method proccessRequests
101. } // end class CreditInquiry
1. public class CreditInquiryTest {
2. public static void main(String args[]) {
3. CreditInquiry application = new CreditInquiry();
4. application.processRequest();
5. }
6. }

Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - End of run

? 1

Accounts with zero balances:

300 Pam White 0.0


Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - End of run

? 2

Accounts with credit balances:

200 Steve Doe -345.67


400 Sam Stone -42.16

Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - End of run

? 3
Accounts with debit balances:

100 Bob Jones 24.89


500 Sue Rich 224.62

Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - End of run

? 4

Process completed.
 The data in sequential files cannot be modified
without the risk of destroying other data in the
file.
 For example: if you want to change from
300 Pam White 0.0
to
300 Pam Worthington 0.0

 It would be copied to a new file  we need


Object Serialization
17.5, Deitel JHTP 9th Edition
 section fields AccountRecord write
text file section files AccountRecord
information record

 instance variables AccountRecord disk file



type value E.g., value "3" read
file,
int, String double !
read write object file Java
Object Serialization

 Serialized-Object Object sequence of byte


data type

 Serialized: Write to file, Deserialized: Read from file


Software Engineer Observation

The Serialization mechanism makes


exact copies of objects. This makes it a simple
way to clone objects without having to
override Object method clone.

Employee emp1 = new Employee("Sok");


Employee emp2 = emp1;
Employee emp3 = emp1.clone();
Software Engineer Observation
The Serialization mechanism makes exact copies of objects. This makes it a
simple way to clone objects without having to override Object method clone.

1. public class Employee implements Cloneable {


2.
3. private String name;
4.
5. public void setName(String name) {
6. this.name = name;
7. }
8.
9. public String getName() {
10. return name;
11. }
12.
13. public Employee clone() throws CloneNotSupportedException {
14. Employee emp = (Employee) super.clone();
15. emp.name = this.name;
16. //emp.someThing = (SomeThing) this.someThing.clone();
17. return emp;
18. }
19.
20.}
Employee emp1 = new Employee();
emp1.setName("Sok");

Employee emp2 = emp1;


System.out.println(emp1.getName()); // Sok
System.out.println(emp2.getName()); // Sok

emp2.setName("Sao");
System.out.println(emp1.getName()); // Sao
System.out.println(emp2.getName()); // Sao

try {
emp2 = emp1.clone();
emp2.setName("Bopha");
} catch (CloneNotSupportedException e) {

System.out.println(emp1.getName()); // Sao
System.out.println(emp2.getName()); // Bopha
java.io
Class ObjectInputStream
java.lang.Object
java.io.InputStream
java.io.ObjectInputStream

All Implemented Interfaces:


Closeable, DataInput, ObjectInput, ObjectStreamConstants, AutoCloseable

 read object file

Object ObjectInputStream
java.io
Class ObjectOutputStream
java.lang.Object
java.io.OutputStream
java.io.ObjectOutputStream

All Implemented Interfaces:


Closeable, DataOutput, Flushable, ObjectOutput, ObjectStreamConstants,
AutoCloseable

 write object file

Object ObjectInputStream
 Write Object to file (Serialization)

FileOutputStream outputFile = new


FileOutputStream("objectData.data");
ObjectOutputStream output = new
ObjectOutputStream(outputFile);

Employee emp = new Employee("Sok");


output.writeObject(emp);

 Read Object from file (Deserialization)

FileInputStream inputFile = new


FileInputStream("objectData.data");
ObjectInputStream input = new
ObjectInputStream(inputFile);
Employee emp = (Employee) input.readObject();
import java.io.Serializable;

public class AccountRecordSerializable implements Serializable {

private int account;


private String firstName;
private String lastName;
private double balance;

public AccountRecord() {
this(0, "", "", 0.0);
}

public AccountRecord(int account, String firstName, String lastName,


double balance) {
this.account = account;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
}

// Other setXXXX and getXXXX methods...


}
1. import java.io.FileOutputStream;
2. import java.io.IOException;
3. import java.io.ObjectOutputStream;
4. import java.util.NoSuchElementException;
5. import java.util.Scanner;
6.
7. public class CreateSequentialFileVersion2 {
8.
9. private ObjectOutputStream output;
10.
11. public void openFile(){
12. try {
13. output = new ObjectOutputStream(
14. new FileOutputStream("clients.ser"));
15.
16. } catch (IOException e) {
17. System.err.println("Error opening file.");
18. } // end catch
19. } // end openFile()
20.
21. public void addRecords(AccountRecordSerializable record) {
22. try {
23. if (record.getAccount() > 0) {
24. output.writeObject(record);
25. } else {
26. System.out.println("Account number must be greater than 0");
27. }
28. } catch (IOException e) {
29. System.err.println("Error writing to file.");
30. return ;
31. }
32. } // end method addRecords
33.
34. public void closeFile() {
35. try {
36. if (output != null) {
37. output.close();
38. }
39. } catch (IOException e) {
40. System.err.println("Error closing file.");
41. System.exit(1);
42. }
43. }
44. }
1. // UsingCreateSequentialFileVersion2.java

2. public class UsingCreateSequentialFileVersion2 {


3. public static void main(String args[]) {
4. CreateSequentialFileVersion2 app = new
CreateSequentialFileVersion2();
5. app.openFile();
6. app.addRecords(
7. new AccountRecordSerializable(100, "Bob", "Jones", 24.89));
8. app.addRecords(
9. new AccountRecordSerializable(200, "Steve", "Doe", -345.67));
10. app.closeFile();
11. }
12. }
1. import java.io.EOFException;
2. import java.io.FileInputStream;
3. import java.io.IOException;
4. import java.io.ObjectInputStream;
5.
6.
7. public class ReadSequentialFileVersion2 {
8.
9. private ObjectInputStream input;

10. public void openFile() {


11. try {
12. input = new ObjectInputStream(
new FileInputStream("clients.ser"));
13.
14. } catch (IOException e) {
15. System.err.println("Error opening file.");
16. }
17. }
18. public void readRecords() {
19. AccountRecordSerializable record;
20.
21. String format = "%-10s%-12s%-12s%10s\n";
22. System.out.printf(format, "Account","First Name",
"Last Name", "Balance");
18. try {
19. while (true) {
20. record =
(AccountRecordSerializable) input.readObject();
21. System.out.printf(format,
22. record.getAccount(), record.getFirstName(),
23. record.getLastName(),record.getBalance());
24. }
25. } catch (EOFException e) {
26. return; // end of file was reached
27. } catch (ClassNotFoundException e) {
28. System.err.println("Unable to create object.");
29. } catch (IOException e) {
30. System.err.println("Error during read from file.");
31. }
32. }
33.
34. public void closeFile() {
35. try {
36. if (input != null) {
37. input.close();
38. }
39. } catch(IOException e) {
40. System.err.println("Error closing file.");
41. System.exit(1);
42. }
43. }
44. }
1. // UsingReadSequentialFileVersion2.java
2.
3. public class UsingReadSequentialFileVersion2 {
4. public static void main(String[] args) {
5. ReadSequentialFileVersion2 app =
6. new ReadSequentialFileVersion2();
7. app.openFile();
8. app.readRecords();
9. app.closeFile();
10. }
11. }

Account First Name Last Name Balance


100 Bob Jones 24.89
200 Steve Doe -345.67
 Java SCJP, Page 514
int result = jFileChooser1.showOpenDialog(this);
if (result == jFileChooser1.CANCEL_OPTION) {
System.exit(1);
}

File fileName = jFileChooser1.getSelectedFile();


try {
Scanner input = new Scanner(fileName);
jTextArea1.setText("");
while(input.hasNext()) {
jTextArea1.append(input.nextLine() + "\n");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}

S-ar putea să vă placă și