1. Trang chủ
  2. » Tất cả

Lab 08

17 1 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 17
Dung lượng 0,91 MB

Nội dung

Lab Guide Lab version:1.0.0 Last updated:9/17/2014 Page Overview JDK has two sets of IO packages: the Standard IO (java.io) (since JDK 1.0) and the New IO (java.nio) (introduced in JDK 1.4) In addition, JDK 1.5 introduced the formatted text-IO via new classes Scanner/Formatter and printf() Objectives Once you have completed this lab, you will understand:  Benefit of using of thread  How to write and handle a multithread program Exercises This Hands-On Lab is comprised by the following exercises:  List the Content of a directory  Copy file using buffer or non-buffer  Read and write Unicode characters  Serializable Estimated time to complete this lab: hours Page Index EXERCISE 1: LIST THE CONTENTS OF A DIRECTORY (RECURSIVELY) Task - Create ListDirectoryRecusive Task - Execute your program EXERCISE 2: COPY FILE Task - Copying a file without Buffering Task - Execute and see the result Task - Copying a file with a Programmer-Managed Buffer Task - Execute and see the result Task - Copying a file with Buffered Streams Task - Execute and see the result 10 EXERCISE 3: BEST COPIER 10 EXERCISE 4: SCANNER AND PRINTWRITER 11 Task - Create ScannerIO Class read file using Scanner class 11 Task - Create PrintwriterIO Class write file using PrintWriter class 12 EXERCISE 5: BUFFEREDREADER AND BUFFEREDWRITER 12 EXERCISE 6: PIPEDREADER AND PIPEDWRITER 12 Task - Create pReader extended Thread 12 Task - Create pWriter extended Thread 13 Task - Write test Program 13 Task - Execute and see the result 14 EXERCISE 7: BUFFEREDREADER AND BUFFEREDWRITER 14 EXERCISE 8: SERIALIZABLE - OBJECTOUTPUTSTREAM 14 Task - Create SerializedObject class 14 Page Task - Create a program to write and read Serializable object 15 Task - Execute your program 16 EXERCISE 9: COUNT THE NUMBER OF LINES 17 Page Next Step Exercise 1: List the contents of a directory (Recursively) Task - Create ListDirectoryRecusive In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up  In "Name" field, enter “ListDirectoryRecusive "  Check "public static void main(String[] args)" box  Click "Finish" Create listRecursive() Method public static void listRecursive(File dir) { if (dir.isDirectory()) { File[] items = dir.listFiles(); for (File item : items) { System.out.println(item.getAbsoluteFile()); if (item.isDirectory()) listRecursive(item); } } } Write main() method to list the contents of a directory public static void main(String[] args) { File dir = new File("C:\\Windows"); listRecursive(dir); } Page Task - Execute your program To run the program, right-click anywhere on the source file "ListDirectoryRecusive.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Exercise 2: Copy File In this exercise you will write a program to copy a file by using methods  Copying a file without Buffering  Copying a file with a Programmer-Managed Buffer  Copying a file with Buffered Streams Page Task - Copying a file without Buffering Create FileCopyNoBuffer Class Write code in FileCopyNoBuffer.java import java.io.*; public class FileCopyNoBuffer { public static void main(String[] args) { File fileIn; FileInputStream in = null; FileOutputStream out = null; long startTime, elapsedTime; // for speed benchmarking try { fileIn = new File("D:\\a.jpg"); System.out.println("File size is " + fileIn.length() + " bytes"); in = new FileInputStream(fileIn); out = new FileOutputStream("D:\\b.jpg"); startTime = System.nanoTime(); int byteRead; // Read a unsigned byte (0-255) and padded to 32-bit int while ((byteRead = in.read()) != -1) { // Write the least significant byte, drop the upper bytes out.write(byteRead); } elapsedTime = System.nanoTime() - startTime; System.out.println("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec"); } catch (IOException ex) { ex.printStackTrace(); } finally { // always close the streams try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } Page Task - Execute and see the result To run the program, right-click anywhere on the source file " FileCopyNoBuffer.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel: Open copied file in your system and compare with the original file Task - Copying a file with a Programmer-Managed Buffer Create FileCopyUserBuffer Class Write code in FileCopyUserBuffer.java import java.io.*; public class FileCopyUserBuffer { public static void main(String[] args) { File fileIn; FileInputStream in = null; FileOutputStream out = null; long startTime, elapsedTime; // for speed benchmarking try { fileIn = new File("D:\\b.jpg"); System.out.println("File size is " + fileIn.length() + " bytes"); in = new FileInputStream(fileIn); out = new FileOutputStream("D:\\c.jpg"); startTime = System.nanoTime(); byte[] byteBuf = new byte[4096]; // 4K buffer int numBytesRead; while ((numBytesRead = in.read(byteBuf)) != -1) { out.write(byteBuf, 0, numBytesRead); } elapsedTime = System.nanoTime() - startTime; Page System.out.println("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec"); } catch (IOException ex) { ex.printStackTrace(); } finally { // always close the streams try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } Task - Execute and see the result To run the program, right-click anywhere on the source file "FileCopyUserBuffer.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Open copied file in your system and compare with the original file Task - Copying a file with Buffered Streams Create FileCopyBuffered Class Write code in FileCopyBuffered.java import java.io.*; public class FileCopyBuffered { public static void main(String[] args) { File fileIn; BufferedInputStream in = null; BufferedOutputStream out = null; long startTime, elapsedTime; // for speed benchmarking try { fileIn = new File("D:\\a.jpg"); Page System.out.println("File size is " + fileIn.length() + " bytes"); in = new BufferedInputStream(new FileInputStream(fileIn)); out = new BufferedOutputStream(new FileOutputStream("D:\\e.jpg")); startTime = System.nanoTime(); int byteRead; while ((byteRead = in.read()) != -1) { out.write(byteRead); } elapsedTime = System.nanoTime() - startTime; System.out.println("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec"); } catch (IOException ex) { ex.printStackTrace(); } finally { // always close the streams try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } Task - Execute and see the result To run the program, right-click anywhere on the source file " FileCopyBuffered.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Open copied file in your system and compare with the original file Exercise 3: Best Copier Rewrite FileCopyUserBuffer.java to find the fastest method of copy by chosing different buffersize int[] bufSizeKB = {1, 2, 4, 8, 16, 32, 64, 256, 1024}; for (int run = 0; run < bufSizeKB.length; run++) { Page 10 // in KB bufSize = bufSizeKB[run] * 1024; byte[] byteBuf = new byte[bufSize]; // 4K buffer //your code } Output of your program will be: Exercise 4: Scanner and PrintWriter Task - Create ScannerIO Class read file using Scanner class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up  In "Name" field, enter “ScannerIO "  Check "public static void main(String[] args)" box  Click "Finish" Write code in ScannerIO.java public static void main(String[] args) { // // Create an instance of File for data.txt file // File file = new File("data.txt"); try { // // Create a new Scanner object which will read the data // from the file passed in To check if there are more // line to read from it we check by calling the Page 11 // scanner.hasNextLine() method We then read line one // by one till all line is read // Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } } To run the program, right-click anywhere on the source file " ScannerIO.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" Task - Create PrintwriterIO Class write file using PrintWriter class Read “data.txt” file in task and write to “datacopy.txt” using PrintWriter Example using PrintWriter class public static void main(String[] args) throws IOException { FileOutputStream fo = null; PrintWriter pw = null; try { fo = new FileOutputStream("datacopy.txt"); pw = new PrintWriter(fo); pw.println("Hello World"); } catch (Exception ex) { ex.printStackTrace(); } finally { pw.close(); fo.close(); } Exercise 5: BufferedReader and BufferedWriter Edit code in Exercise using BufferedReader and BufferedWriter Exercise 6: PipedReader and PipedWriter Task - Create pReader extended Thread import java.io.IOException; import java.io.PipedReader; public class pReader extends Thread { PipedReader reader; pReader(PipedReader reader) { this.reader = reader; Page 12 } public void run() { try { while (true) { sleep(1000); if (reader.ready()) System.out.print((char) reader.read()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } Task - Create pWriter extended Thread import java.io.IOException; import java.io.PipedWriter; import java.util.Scanner; public class pWriter extends Thread { PipedWriter writer; pWriter(PipedWriter writer) { this.writer = writer; } public void run() { String str; while (true) { Scanner in = new Scanner(System.in); str = in.nextLine(); try { writer.write(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Task - Write test Program import java.io.PipedReader; import java.io.PipedWriter; Page 13 public class test { public static void main(String args[]) throws Exception { // Create a new instance of a PipedReader object PipedReader reader = new PipedReader(); // Create a new instance of a PipedWriter object PipedWriter writer = new PipedWriter(); // Connect the PipedReader to a PipedWriter object reader.connect(writer); pReader treader = new pReader(reader); pWriter twriter = new pWriter(writer); treader.start(); twriter.start(); } } Task - Execute and see the result Exercise 7: BufferedReader and BufferedWriter Edit code in Exercise using BufferedReader and BufferedWriter Exercise 8: Serializable - ObjectOutputStream Object serialization is the process of representing a particular state of an object in a serialized bitstream, so that the bit stream can be written out to an external device (such as a disk file or network) In Java, object that requires to be serialized must implement java.io.Serializable or java.io.Externalizable interface Serializable interface is an empty interface (or tagged interface) with nothing declared Its purpose is simply to declare that particular object is serializable Task - Create SerializedObject class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up  In "Name" field, enter “SerializedObject "  In Interface field, press “Add” button, Page 14  Enter Serializable and press Add  Click "Finish" Write code in SerializedObject.java import java.io.Serializable; class SerializedObject implements Serializable { private int number; public SerializedObject(int number) { this.number = number; } public int getNumber() { return number; } } Task - Create a program to write and read Serializable object In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up  In "Name" field, enter “ObjectSerializationTest"  Check "public static void main(String[] args)" box  Click "Finish" Write code for main() method public static void main(String[] args) { ObjectInputStream in = null; ObjectOutputStream out = null; try { out = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream("C:\\object.dat"))); // Create an array of 10 SerializedObjects with ascending numbers SerializedObject[] objs = new SerializedObject[10]; for (int i = 0; i < objs.length; i++) { objs[i] = new SerializedObject(i); } // Write the 10 objects to file, one by one Page 15 for (int i = 0; i < objs.length; i++) { out.writeObject(objs[i]); } // Write the entire array in one go out.writeObject(objs); out.close(); in = new ObjectInputStream(new BufferedInputStream( new FileInputStream("C:\\object.dat"))); // Read back the objects, cast back to its original type SerializedObject objIn; for (int i = 0; i < objs.length; i++) { objIn = (SerializedObject)in.readObject(); System.out.println(objIn.getNumber()); } SerializedObject[] objArrayIn; objArrayIn = (SerializedObject[])in.readObject(); for (SerializedObject o : objArrayIn) { System.out.println(o.getNumber()); } in.close(); } catch (Exception ex) { ex.printStackTrace(); } } Task - Execute your program To run the program, right-click anywhere on the source file " ObjectSerializationTest.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Page 16 Exercise 9: Count the number of lines Write a program that will count the number of lines in each file that is specified on the command line Assume that the files are text files Note that multiple files can be specified, as in "java LineCounts file1.txt file2.txt file3.txt" Write each file name, along with the number of lines in that file, to standard output If an error occurs while trying to read from one of the files, you should print an error message for that file, but you should still process all the remaining files Summary In this lab, you have learned how to using java.io Page 17 ... Objectives Once you have completed this lab, you will understand:  Benefit of using of thread  How to write and handle a multithread program Exercises This Hands-On Lab is comprised by the following... or non-buffer  Read and write Unicode characters  Serializable Estimated time to complete this lab: hours Page Index EXERCISE 1: LIST THE CONTENTS OF A DIRECTORY (RECURSIVELY) Task - Create... error message for that file, but you should still process all the remaining files Summary In this lab, you have learned how to using java.io Page 17

Ngày đăng: 03/10/2016, 00:14

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w