Bài giảng lập trình hướng đối tượng OUT PUT
Trang 1HỌC VIỆN CÔNG NGHỆ BƯU CHÍNH VIỄN THÔNG
BÀI GIẢNG MÔN
LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG
Giảng viên: Nguyễn Mạnh Sơn
Bộ môn: Công nghệ phần mềm - Khoa CNTT1
Học kỳ/Năm biên soạn: I – 2009/2010
Trang 2Input và Output
Trang 36 Random Access Files
7 Kết hợp giao diện SWING và đọc ghi file
Trang 412/09/12 4
Files và Directories
File(String path)
File(String directoryPath, String filename)
File(File directory, String filename)
File Constructors
boolean canRead(); boolean canWrite()
boolean delete(); boolean equals(Object obj)
boolean exists(); boolean exists()
String getAbsolutePath();
String getCanonicalPath() throws IOException
String getName(); String getParent()
String getPath(); boolean isAbsolute()
Methods
Lớp File cho phép định nghĩa các
thông tin liên quan đến file và thư
mục
boolean isDirectory()boolean isFile()long lastModified()long length()String[] list()boolean mkdir()boolean mkdirs()boolean renameTo(File newName)
Methods
Trang 5Files and Directories
// Test Some Methods
File file = new File(args[0]);
getAbsolutePath() = 11\FileDemo.java
getCanonicalPath() = 11\FileDemo.java
D:\lecture\2004-01\teachyourself\example10-getPath() = FileDemo.javacanRead() = true
canWrite() = true
System.out.println("canRead() = " + file.canRead());
System.out.println("canWrite() = " + file.canWrite());
} catch(Exception e) { e.printStackTrace();
} }}
Trang 7Character Streams
Reader
BufferedReader InputStreamReader StringReader
CharArrayReader PipedReader
FilterReader
Trang 812/09/12 8
Character Streams
Writer
BufferedWriter OutputStreamWriter StringWriter
CharArrayWriter PipedWriter
FilterWriter PrintWriter
Trang 9abstract void close() throws IOException
abstract void flush() throws IOException
void write(int c) throws IOException
void write(char buffer[]) throws IOException
abstract void write(char buffer[], int index, int size) throws
IOException
void write(String s) throws IOException
void write(String s, int index, int size) throws IOException
Methods
OutputStreamWriter(OutputStream os)OutputStreamWriter(OutputStream os, String encoding)
FileWriter(String filepath) throws IOException
FileWriter Constructors
Trang 1012/09/12 10
Character Streams
Refer to http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.html
abstract void close() throws IOException
void mark(int numChars) throws IOException
boolean markSupported()
int read() throws IOException
int read(char buffer[]) throws IOException
int read(char buffer[], int offset, int numChars) throws
IOException
boolean ready() throws IOException
void reset() throws IOException
int skip(long numChars) throws IOException
Methods của lớp Reader
InputStreamWriter(InputStream os)InputStreamWriter(InputStream os, String encoding)
Trang 11FileWriter fw = new FileWriter(args[0]);
// Write string to the file
for (int i = 0; i < 12; i++) {
class FileReaderDemo { public static void main(String args[]) { try {
FileReader fr = new FileReader(args[0]);
int i;
while((i = fr.read()) != -1) { System.out.print((char)i);
} fr.close();
} catch(Exception e) { System.out.println("Exception: " + e);
} }}
Run :
java FileWriterDemo output.txt
java FileReaderDemo output.txt
Trang 12FileWriter fw = new FileWriter(args[0]);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < 12; i++) { bw.write("Line " + i + "\n");
} bw.close();
} catch (Exception e) { System.out.println("Exception: " + e);
} }}
Trang 13Character Stream Examples
class BufferedReaderDemo {
public static void main(String args[]) {
try {
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
class ReadConsole { public static void main(String args[]) { try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s;
while((s = br.readLine()) != null) { System.out.println(s.length());
} isr.close();
} catch (Exception e) { System.out.println("Exception: " + e);
} }}
Run :
java BufferedWriterDemo output.txt
java BufferedReaderDemo output.txt
Trang 14PrintWriter(Writer writer, boolean flushOnNewline)
PrintWriter Constructor class PrintWriterDemo { public static void main(String args[]) {
try { PrintWriter pw = new PrintWriter(System.out);
} }}
Trang 15Byte Streams (Binary Streams)
Object
InputStream
FileInputStream FilterInputStream
Trang 1612/09/12 16
Byte Streams
InputStream
AutioInputStream FileInputStream ObjectInputStream SequenceInputStream ByteArrayInputStream PipedInputStream
FilterInputStream
Trang 17Byte Streams
OutputStream
FileOutputStream ObjectOutputStream ByteArrayOutputStream PipeOutputStream
FilterOutputStream
Trang 1812/09/12 18
Byte Streams
Refer to http://java.sun.com/j2se/1.4.2/docs/api/java/io/OutputStream.html
void close() throws IOException
void flush() throws IOException
void write(int i) throws IOException
void write(byte buffer[]) throws IOException
void write(char buffer[], int index, int size) throws
IOException
Methods Defined by the OutputStream
FileOutputStreamWriter(String filepath) throws IOException
FileOutputStreamWriter(String filepath, boolean append)
throws IOException
FileOutputStreamWriter(File fileObj) throws IOException
FileOutputStream Constructor
BufferedOutputStream(OutputStream os)BufferedOutputStream(OutputStream os, int bufSize)
Trang 19Byte Streams (DataOutput Interface)
Refer tohttp://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutput.html
void write(int i) throws IOException
void write(byte buffer[]) throws IOException
void write(byte buffer[], int index, int size) throws
IOException
void writeBoolean(boolean b) throws IOException
void writeByte(int i) throws IOException
void writeByte(String s) throws IOException
void writeChar(int i) throws IOException
void writeChars(String s) throws IOException
void writeDouble(double d) throws IOException
void writeFloat(float f) throws IOException
void writeInt(int i) throws IOException
void writeLong(long l) throws IOException
void writeShort(short s) throws IOException
void writeUTF(String s) throws IOException
Methods Defined by the DataOutput
PrintStream(OutputStream outputStream)PrintStream(OutputStream outputStream, boolean flushOnNewline)
PrintStream Constructors
Trang 2012/09/12 20
Byte Streams (InputStream Interface)
Refer tohttp://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStream.html
int available() throws IOException
void close() throws IOException
void mark(int numBytes)
boolean markSupported()
int read() throws IOException
int read(byte buffer[]) throws IOException
int read(byte buffer[], int offset, int numBytes) throws
IOException
Void reset() throws IOException
int skip(long numBytes) throws IOExcepion
Methods Defined by the InputStream
BufferedInputStream Constructors
DataInputStream(InputStream is)
DataInputStream Constructor
Trang 21Byte Streams (DataInput Interface)
Refer tohttp://java.sun.com/j2se/1.5.0/docs/api/java/io/DataInput.html
boolean readBoolean() throws IOException
byte readByte() throws IOException
char readChar() throws IOException
double read Double() throws IOException
float readFloat() throws IOException
void readFully(byte buffer[]) throws IOException
void readFully(byte buffer[], int index, int size) throws
IOException
int readInt() throws IOException
String readLine() throws IOException
long readLong() throws IOException
short readShort() throws IOException
String readUTF() throws IOException
int readUnsignedByte() throws IOException
int readUnsignedShort() throws IOException
int skipBytes(int n) throws IOException
Methods Defined by DataInput class FileOutputStreamDemo {
public static void main(String args[]) { try {
FileOutputStream fos = new FileOutputStream(args[0]);
for (int i = 0; i < 12; i++) { fos.write(i);
} fos.close();
} catch (Exception e) { System.out.println("Exception: " + e);
} }}
Trang 22Run :
java FileOutputStreamDemo output.txtjava FileInputStreamDemo output.txt
Trang 23FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
int i;
while((i = bis.read()) != -1) { System.out.println(i);
} fis.close();
} catch (Exception e) { System.out.println("Exception: " + e);
} }}
Run :
java BufferedOutputStreamDemo output.txt
java BufferedInputStreamDemo output.txt
Trang 24FileInputStream fis = new FileInputStream(args[0]);
DataInputStream dis = new DataInputStream(fis);
} }}
Run :
java DataOutputStreamDemo output.txt
java DataInputStreamDemo output.txt
Trang 25Random Access Files
Refer
tohttp://java.sun.com/j2se/1.5.0/docs/api/java/io/RandomAcces
sFile.html
void close() throws IOException
long getFilePointer() throws IOException
long length() throws IOException
int read() throws IOException
int read(byte buffer[], int index, int size) throws
IOException
int read(byte buffer[]) throws IOException
void seek(long n) throws IOException
int skipBytes(int n) throws IOException
Methods Defined by the RandomAccessFile long position = raf.length(); position -= count;
if (position < 0) position = 0;
raf.seek(position);
while(true) { try {
byte b = raf.readByte();
System.out.print((char)b);
} catch (EOFException eofe) { break;
} } } catch (Exception e) { e.printStackTrace();
} }}
Trang 2612/09/12 26
Kết hợp giao diện và đọc ghi file
• Vấn đề: Kết hợp giao diện SWING để xây dựng ứng dụng
đọc và ghi file
• Viết chương trình tạo ra giao diện như dưới đây:
Trang 27Kết hợp giao diện và đọc ghi file
private boolean _clickMeMode = true;
FileIO() { //Begin Constructor
text = new JLabel("Doan van ban ghi vao file:");
button = new JButton("Ghi vao file");
button.addActionListener(this);
textField = new JTextField(30);
panel = new JPanel();
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (source == button) { String s = null;
//Write
if (_clickMeMode){
try { String text = textField.getText();
byte b[] = text.getBytes();
String outputFileName = System.getProperty("user.home", File.separatorChar + "home" +
File.separatorChar + "zelda") + File.separatorChar + "text.txt";
FileOutputStream out = new FileOutputStream(outputFileName); out.write(b);
out.close();
} catch(java.io.IOException e) { System.out.println("Khong the ghi vao file text.txt");
} //Read try { String inputFileName = System.getProperty("user.home", File.separatorChar + "home" +
File.separatorChar + "zelda") + File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileInputStream in = new FileInputStream(inputFile);
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
Trang 28
//Save text to file
text.setText("Doan van ban ghi vao file:");
textField.setText("");
button.setText("Ghi vao file");
_clickMeMode = true;
} } }
public static void main(String[] args){
FileIO frame = new FileIO();
frame.setTitle("Example");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Trang 29Xử lý ngoại lệ
Trang 31Luôn luôn thực hiện
Trang 32finally { System.out.println("Finally block");
} }}
Result : java Divider 1 0Before Division
ArithmeticExceptionFinally block
Trang 33b: finallyAfter ba: finallyAfter a
public static void b() { try {
System.out.println("Before c");
c();
System.out.println("After c");
} catch (ArrayIndexOutOfBoundsException e) { System.out.println("b: " + e);
} finally { System.out.println("b: finally");
} }
public static void c() { try {
System.out.println("Before d");
d();
System.out.println("After d");
} catch (NumberFormatException e) { System.out.println("c: " + e);
} finally { System.out.println("c: finally");
} }
public static void d() { try {
int array[] = new int[4];
array[10] = 10;
} catch (ClassCastException e) { System.out.println("d: " + e);
} finally { System.out.println("d: finally");
} }}
Trang 34Thực hiện với các Exception
throw new ExceptionType(args);
Với Exception được tạo mới
Trang 35Từ khoá Throw (tiếp)
c: java.lang.ArithmeticException: / by zeroc: finally
b: java.lang.ArithmeticException: / by zerob: finally
After ba: finallyAfter a
public static void b() { try {
System.out.println("Before c");
c();
System.out.println("After c");
} catch (ArithmeticException e) { System.out.println("b: " + e);
} finally { System.out.println("b: finally");
} }
public static void c() { try {
System.out.println("Before d");
d();
System.out.println("After d");
} catch (ArithmeticException e) { System.out.println("c: " + e);
throw e;
} finally { System.out.println("c: finally");
} }
public static void d() { try {
int i = 1;
int j = 0;
System.out.println("Before division"); System.out.println(i / j);
System.out.println("After division"); }
catch (ArithmeticException e) { System.out.println("d: " + e);
throw e;
} finally { System.out.println("d: finally");
} }}
Trang 36After amain: finally
public static void a() { try {
System.out.println("Before throw statement");
throw new ArithmeticException();
} catch (Exception e) { System.out.println("a: " + e);
} finally { System.out.println("a: finally");
} }}
Trang 37ClassCastException NegativeArraySizeException NullPointerException
NumberFromatException SecurityException
StringIndexOutOfBoundsException
Trang 38} } public static void d() { try {
int i = 1;
int j = 0;
System.out.println(i / j);
} catch (NullPointerException e) { e.printStackTrace();
} }}
Trang 39} else { throw new ExceptionB("We have a big problem");
} } }class ExceptionA extends Exception { public ExceptionA(String message) { super(message);
}}
class ExceptionB extends Exception { public ExceptionB(String message) { super(message);
}}
Trang 4012/09/12 40
Applet
Trang 41Giới thiệu APPLET
Là một chương trìnhJava mà chạy với sự hỗ trợ của trình duyệt web•
Tất cả các applets là lớp con của lớp‘Applet’•
Để tạo một applet, bạncầnimport hai gói sau:
java.applet
java.awt
Trang 4212/09/12 42
Cấu trúc applet
Định nghĩa một applet từ bốn sự kiện xảy ra trong quá trình thực thi
Mỗi sự kiện được định nghĩa bởi một phương thức tương ứng.