Duyệt Record với RecordEnumeration Duyệt Record với RecordEnumeration Bởi: Khoa CNTT ĐHSP KT Hưng Yên Trong các ví dụ trước để duyệt các record ta đã

Tài liệu tương tự
Microsoft Word - status_code_trong_servlet.docx

Tìm hiểu ngôn ngữ lập trình Visual Basic Tìm hiểu ngôn ngữ lập trình Visual Basic Bởi: Khuyet Danh Tìm hiểu ngôn ngữ lập trình Visual Basic Tổng quan

说明书 86x191mm

Những cơ sở của ngôn ngữ C# Những cơ sở của ngôn ngữ C# Bởi: phamvanviet truonglapvy Trong chương này sẽ trình bày về hệ thống kiểu trong C#; phân biệ

Nhúng mã-cách khai báo biến Nhúng mã-cách khai báo biến Bởi: Khoa CNTT ĐHSP KT Hưng Yên Nhúng mã javascript trong trang HTML Bạn có thể nhúng JavaScri

Microsoft Word - server_response_trong_servlet.docx

Stored Procedures Stored Procedures Bởi: Khoa CNTT ĐHSP KT Hưng Yên Trong những bài học trước đây khi dùng Query Analyzer chúng ta có thể đặt tên và s

Câu lệnh (statement) Câu lệnh (statement) Bởi: Khuyet Danh Trong C# một chỉ dẫn lập trình đầy đủ được gọi là câu lệnh. Chương trình bao gồm nhiều câu

Copyright vietjack.com Chuỗi (String) trong C# Trong C#, bạn có thể sử dụng các chuỗi (string) như là mảng các ký

Microsoft Word - cau-truc-du-lieu-hang-doi.docx

Microsoft Word - session_tracking_trong_servlet.docx

Microsoft Word - client_request_trong_servlet.docx

Kế thừa

Các biến và các kiểu dữ liệu trong JavaScript Các biến và các kiểu dữ liệu trong JavaScript Bởi: Hà Nội Aptech Các biến (Variables) Biến là một tham c

Các cấu trúc logic trong lập trình 1 Cấu trúc tuần tự (Sequence) 1.1 Những câu lệnh phải được sắp xếp theo thứ tự Một số hướng dẫn cho việc tổ chức câ

Cách tạo User và Thiết kế Database Cách tạo User và Thiết kế Database Bởi: Khoa CNTT ĐHSP KT Hưng Yên Cách tạo một User Database Chúng ta có thể tạo m

Hệ điều hành Bài tập tuần 6 1 Quản lý bộ nhớ Bài tập 1 : Xem thông tin bộ nhớ 1. Sử dụng top, ps đọc thông tin về kích thước vùng nhớ của 1 tiến trình

Array, Indexer và Collection Array, Indexer và Collection Bởi: phamvanviet truonglapvy Mảng (Array) Mảng là một tập hợp các phần tử có cùng kiểu, được

Xử lý ngoại lệ

Java cơ bản

Slide 1

Chương trình dịch

Lớp đối tượng String Lớp đối tượng String Bởi: Khuyet Danh Ngôn ngữ C# hỗ trợ khá đầy đủ các chức năng của kiểu chuỗi mà chúng ta có thể thấy được ở c

Microsoft Word - su_dung_sqlite_voi_php.docx

NGÔN NGƯ LÂ P TRIǸH Biên tập bởi: nguyenvanlinh

Microsoft Word - action_trong_jsp.docx

Microsoft Word - tao_ung_dung_hello_world_trong_android.docx

Microsoft Word - xu_ly_cookie_trong_servlet.docx

Tóm tắt ngữ pháp tiếng Anh Tổng hợp và biên soạn: Thầy Tâm - Anh Văn ( TÓM TẮT NGỮ PHÁP TIẾNG ANH Mục lục Tóm tắt

Lập trình cấu trúc trong Visual Basic Lập trình cấu trúc trong Visual Basic Bởi: Nguyễn Sơn Học xong chương này, sinh viên phải nắm bắt được các vấn đ

Copyright vietjack.com Nạp chồng toán tử trong C# Operator Overloading là Nạp chồng toán tử. Bạn có thể tái định

Hàm và lớp template trong Lập trình hướng đối tượng Hàm và lớp template trong Lập trình hướng đối tượng Bởi: unknown Trong phần này, chúng ta tìm hiểu

Chương trình dịch

Microsoft Word - danh-sach-lien-ket-doi-trong-c.docx

Chương trình dịch

Bài tập chương 1 ngôn ngữ lập trình visual basic Bài tập chương 1 ngôn ngữ lập trình visual basic Bởi: Khoa CNTT ĐHSP KT Hưng Yên MỤC TIÊU: SAU KHI HO

Animation, Modules 6 - Hoạt hình, tách file

ĐỀ cương chương trình đẠi hỌc

Kiến trúc tập lệnh1

Chuỗi Chuỗi Bởi: phamvanviet truonglapvy Chuỗi (string) trong C# là một kiểu dựng sẵn như các kiểu int, long, có đầy đủ tính chất mềm dẻo, mạnh mẽ và

Các thanh công cụ Toolbar Các thanh công cụ Toolbar Bởi: Khoa CNTT ĐHSP KT Hưng Yên Origin cung cấp các nút thanh công cụ cho những lệnh menu thường x

Using a Walker - Vietnamese

Kế thừa và đa hình

Microsoft Word - co_ban_ve_jquery.docx

9-KiemThu

Chiến lược kiểm thử Chiến lược kiểm thử Bởi: Khoa CNTT ĐHSP KT Hưng Yên Các công đoạn kiểm thử Quá trình kiểm thử có thể chia làm các giai đoạn : Kiểm

Lesson 4: Over the phone (continued) Bài 4: Nói chuyện qua điện thoại (tiếp theo) Trần Hạnh và toàn Ban Tiếng Việt, Đài Úc Châu, xin thân chào quí bạn

Lập trình và ngôn ngữ lập trình

Chủ đề :

Website review luanvancaohoc.com

Làm quen với chương trình Microsoft Excel Làm quen với chương trình Microsoft Excel Bởi: unknown Làm quen với chương trình Những thao tác đầu tiên với

Chương trình dịch

Microsoft Word - jsp_syntax.docx

Lkgjlfjq?etyuiiofjkfjlsfjkslddghdgertt

Lời giới thiệu:

Exchange Server - Recipient Configuration - Create Mailbox Exchange Server - Recipient Configuration - Create Mailbox Bởi: Phạm Nguyễn Bảo Nguyên Chún

Template and Exception Template and Exception Bởi: Thanh Hiền Vũ TEMPLATE Trong phần này, chúng ta tìm hiểu về một trong các đặc tính còn lại của C++,

CÀI ĐẶ T ANDROID TRÊN NETBEAN Yêu cầ u:trong quá trình cài đặ t phả i kế t nố i mạ ng,và phiên bả n này đượ c cài trên windows. 1.Download Netbean(6.7

Slide 1

TRƯỜNG ĐẠI HỌC BÁCH KHOA HÀ NỘI VIỆN CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG TIN HỌC ĐẠI CƯƠNG Bài 5. Kiểu dữ liệu và biểu thức trong C Nội dung 1. Các ki

Kiểu dữ liệu văn bản Kiểu dữ liệu văn bản Bởi: PGS. TS. NGƯT Phạm Văn Huấn Ngoài những dữ liệu số như các số nguyên, số thực, máy tính còn có thể lưu

BƯỚC 1 CÀI LẮP SIM BƯỚC 2 APN BƯỚC 3 ĐĂNG KÝ HOÀN THÀNH Bỏ SIM vào máy di động. Cài đặt APN. Vui lòng khởi động lại thiết bị. Vui lòng mở trình duyệt

Trung Tâm Gia Sư Tài Năng Việt Đề Số 1 Câu 1: Sau khi thực hiện đoạn chương trình sau, giá trị của biến S bằng bao nhiêu: S

26 Khoa hoïc Coâng ngheä LẬP TRÌNH PHÂN TÁN DÙNG CÔNG NGHỆ MOBILE AGENT VỚI SỰ HỖ TRỢ CỦA JAVA VÀ VOYAGER Tóm tắt ThS. Nguyễn Khắc Quốc * Lập trình ph

Microsoft Word - Huong dan su dung Mailchimp.docx

Microsoft Word - custom_component_trong_android.docx

Ví dụ về duyệt đồ thị ưu tiên chiều sâu DFS và ứng dụng Đồ thị ví dụ: Nguyễn Hữu Tuân vimaru.edu.vn Hình 1: Đồ thị vô hướng có 8 đỉnh Với đồ thị trên,

Thực hành trên Rose Thực hành trên Rose Bởi: Đoàn Văn Ban Xây dựng biểu đồ thành phần + Tạo lập mới hoặc mở một biểu đồ thành phần đã được tạo lập trư

Lớp và đối tượng-các hàm và các lớp friend Lớp và đối tượng-các hàm và các lớp friend Bởi: Thanh Hiền Vũ CÁC HÀM VÀ CÁC LỚP friend Một hàm friend của

Microsoft Word - form_trong_html.docx

Trường ĐHBK Hà Nội Khoa Điện Bộ môn Điều khiển Tự động Tài liệu hướng dẫn thực hành: KĨ THUẬT LẬP TRÌNH C/C++ Bài 1: Lập trình cơ sở 1 Mục đích bài th

MD Paper-Based Test ELA Vietnamese Script for Administrating PARCC TAM

Chương trình dịch

Microsoft Word - custom_font_trong_android.docx

Microsoft Word - google_map_trong_android.docx

ỦY BAN NHÂN DÂN TỈNH TRÀ VINH TRƯỜNG ĐẠI HỌC TRÀ VINH ISO 9001:2008 NGUYỄN THÚY AN GIẢI PHÁP PHÁT TRIỂN NGUỒN NHÂN LỰC NGÀNH TÀI NGUYÊN VÀ MÔI TRƯỜNG

FAQs Những câu hỏi thường gặp 1. What is the Spend Based Rewards program for Visa Vietnam? The Spend Based Rewards program for Visa Vietnam is a servi

Backup Cloud Server

Microsoft Word - Bai 7.1.docx

Microsoft Word - kieu_du_lieu_trong_jdbc.docx

sdfsdfsdfsfsdfd

Microsoft PowerPoint - L2-Gioi_thieu_WEKA.ppt [Compatibility Mode]

Microsoft Word - xu_ly_su_kien_trong_jquery.docx

Chương 1:

Blood pool and Hemangioma - Khoang chứa máu và U máu gan Hoàng Văn Trung Normally when we look at lesions filling with contrast, the density of these

Microsoft Word - jsp_file_uploading.docx

Hướng Dẫn Sử Dụng Doanh Nghiệp với Giao AdminLTE Bao gồm: - Trỏ record - Quản trị với giao diện AdminLTE - Cấu hình trên Outlook 2013 ( PO

Microsoft Word - jsp_client_request.docx

Các Vấn Đề Cơ Sở Của Khoa Học Máy Tính Th.S GVC Tô Oai Hùng BAØI TAÄP CHÖÔNG 1 1. Viết giải thuật để mô tả thói quen mỗi buổi sáng của bạn, từ lúc ngh

NGÔN NGỮ THỐNG KÊ R

Bài 7. Con trỏ Mục tiêu: 1. Luyện tập sử dụng con trỏ và địa chỉ của các biến 2. Sử dụng con trỏ khi thao tác với mảng. Giới hạn: không dùng các thư v

Điểm ĐỀ THI HK 1 ( ) Môn: Kỹ thuật số Thời gian: 110 phút (SINH VIÊN KHÔNG ĐƯỢC SỬ DỤNG TÀI LIỆU) Chữ kí giám thị HỌ TÊN:. MSSV: NHÓM:.. SINH

Kết nối và thao tác với CSDL trong ASP Kết nối và thao tác với CSDL trong ASP Bởi: Khoa CNTT ĐHSP KT Hưng Yên Qui tắc chung - Tạo đối tượng Connection

Microsoft Word - fragment_transition_trong_android.docx

! LỊCH HỌC CỦA TRẺ 3-4 TUỔI/ DAILY SCHEDULE FOR PRESCHOOL 1 September Tuần 1 / Week 1 Bài học: Trường em Ngày: 5/9 9/9 Unit: My school Date: Sep 5-9 T

Bản ghi:

Duyệt Record với RecordEnumeration Bởi: Khoa CNTT ĐHSP KT Hưng Yên Trong các ví dụ trước để duyệt các record ta đã sử dụng vòng lặp: for (int i = 1; i <= rs.getnumrecords(); i++) rs.getrecord(i, recdata, 0); Ngoài ra còn một cách khác để duyệt RecordStore là sử dung RecordEnumeration. Lớp này cung cấp các phương thức để duyệt các record trong RecordStore một cách nhanh chóng. Dưới đây là đoạn code duyệt toàn bộ RecordStore: RecordEnumeration re = rs.enumeraterecords(null,null,false); while (re.hasnextelement()) // Get the next record into a String String str = new String(re.nextRecord());... do something... Trong đoạn code trên đã sử dụng nextrecord() để duyệt đến record sau đó, ngoài ra còn có previousrecord() giúp duyệt về record trước đó. Nếu muốn bắt đầu tại vị trí cuối cùng của recordstore ta chỉ cần gọi hàm previousrecord() ngay khi mở recordstore, nó sẽ trả về dòng cuối cùng. 1/34

RecordEnumeration có duy trì một index của các record. Khi recordstore có sự thay đổi thì RecordEnumeration có thể hoạt dộng không chính xác, do đó chúng ta cần phải gọi hàm reindex() mỗi khi recordstore có sự thay đổi. RecordEnumeration re = rs.enumeraterecords(null,comp,false); // Iterate through the sorted results while (re.hasnextelement()) String str = new String(re.nextRecord());. Enumeration sẽ sử dụng hàm compare trong class Comparator để sắp xếp các record trong RecordStore. RecordComparator Interface: javax.microedition.rms.recordcomparator M e t ho d Description int compare(byte[] rec1, byte[] rec2) So sánh để quyết định thứ tự sắp xếp Ví dụ 3: chương trình sắp xếp cơ bản /*-------------------------------------------------- * SimpleSort.java * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class SimpleSort extends MIDlet 2/34

private RecordStore rs = null; static final String REC_STORE = "db_1"; public SimpleSort() openrecstore(); // Create the record store // Write a few records writerecord("sand Wedge"); writerecord("one Wood"); writerecord("putter"); writerecord("five Iron"); // Read back with enumerator, sorting the results readrecords(); closerecstore(); // Close record store deleterecstore(); // Remove the record store public void destroyapp( boolean unconditional ) public void startapp() // There is no user interface, go ahead and shutdown destroyapp(false); notifydestroyed(); 3/34

public void pauseapp() public void openrecstore() // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); db(e.tostring()); public void closerecstore() rs.closerecordstore(); 4/34

db(e.tostring()); public void deleterecstore() if (RecordStore.listRecordStores()!= null) RecordStore.deleteRecordStore(REC_STORE); db(e.tostring()); public void writerecord(string str) byte[] rec = str.getbytes(); 5/34

rs.addrecord(rec, 0, rec.length); db(e.tostring()); public void readrecords() if (rs.getnumrecords() > 0) Comparator comp = new Comparator(); RecordEnumeration re = rs.enumeraterecords(null,comp, false); while (re.hasnextelement()) String str = new String(re.nextRecord()); System.out.println(str); System.out.println("------------------------------"); 6/34

db(e.tostring()); /*-------------------------------------------------- * Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(string str) System.err.println("Msg: " + str); /*-------------------------------------------------- Comparator.java Compares two records to determine sort order 7/34

*-------------------------------------------------*/ class Comparator implements RecordComparator public int compare(byte[] rec1, byte[] rec2) String str1 = new String(rec1), str2 = new String(rec2); int result = str1.compareto(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; Trong đoạn code trên trong hàm readrecord(), khi tạo Enumeration ta đã tham chiếu đến đối tượng comp của lớp Comparator Comparator comp = new Comparator(); RecordEnumeration re = rs.enumeraterecords(null, comp, false); while (re.hasnextelement())... 8/34

Khi enumerator tạo index cho RecordStore nó sẽ sử dụng hàm compare() ở trên để sắp xếp các record. Output của vi dụ 3: Ví dụ trên đúng trong trường hợp dữ liệu lưu vào record là dạng text, nếu quay lại ví dụ 2 ta đã ghi nhiều kiểu dữ liệu vào trong một record: // Write Java data types to stream strmdatatype.writeutf("text 1"); strmdatatype.writeboolean(true); strmdatatype.writeint(1); Các kiểu dữ liệu trên sẽ được lưu vào một stream ở dạng binary. Sau đó các stream này sẽ được chuyển thành mảng và đưa vào recordstore: // Get stream data into an array record = strmbytes.tobytearray(); // Write the array to a record rs.addrecord(record, 0, record.length); Đoạn code trong ví dụ 3 sẽ chạy sai khi áp dụng với kiểu dữ liệu binary. Để giải quyết, ta cần phải viết lại hàm compare() thự c hiện chức năng chuyển đổi chuỗi byte và sắp xếp đúng kiểu dữ liệu. Trong thực tế, chúng ta cần phải lưu nhiều trường dữ liệu trong một record như trong ví dụ 2 (lưu dữ liệu kiểu String, boolean, integer). Trong trường hợp này sẽ có nhiều lựa chọn để sắp xếp các record, và việc lựa chọn này tùy thuộc vào ứng dụng của bạn. 9/34

Trong 2 ví dụ sau đây sẽ thực thi interface RecordComparator để sắp xếp record chứa nhiều kiểu dữ liệu. Những ví dụ này sẽ sử dụng cùng dữ liệu đầu vào, tuy nhiên ví dụ 4 sẽ sắp xếp dựa vào kiểu String, trong khi ví dụ 5 sẽ sắp xếp dựa vào kiểu integer. Đây là dữ liệu sẽ lưu vào recordstore: String[] pets = "duke", "tiger", "spike", "beauregard"; boolean[] dog = true, false, true, true; int[] rank = 3, 0, 1, 2; Khi lưu vào recordstore sẽ có dạng như sau: Record #1 "duke" true 3 Record #2 "tiger" false 0 Record #3 "spike" true 1 Record #4 "beauregard" true 2 Đây là lý do ví dụ 3 không đáp ứng được yêu cầu, do dữ liệu lưu vào không còn là dạng text, và hàm String.CompareTo() trên nội dung của record không thể sắp xếp dữ liệu theo mong muốn. Do đó, bạn cần phải lấy ra từ mỗi record trường dữ liệu mà bạn muốn sắp xếp. Trong ví dụ 4 sẽ lấy kiểu String ở đầu mỗi record, ví dụ 5 sẽ lấy kiểu integer ở cuối mỗi record. Ví dụ 4: StringSort.java /*-------------------------------------------------- * StringSort.java * * Sort records that contain multiple Java * data types. Sort using String type. 10/34

* * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class StringSort extends MIDlet private RecordStore rs = null; // Record store static final String REC_STORE = "db_3"; // Name of record store public StringSort() openrecstore(); // Create the record store writetestdata(); // Write a series of records readstream(); // Read back the records closerecstore(); // Close record store deleterecstore(); // Remove the record store public void destroyapp( boolean unconditional ) public void startapp() 11/34

// There is no user interface, go ahead and shutdown destroyapp(false); notifydestroyed(); public void pauseapp() public void openrecstore() // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); db(e.tostring()); public void closerecstore() 12/34

rs.closerecordstore(); db(e.tostring()); public void deleterecstore() if (RecordStore.listRecordStores()!= null) RecordStore.deleteRecordStore(REC_STORE); db(e.tostring()); 13/34

/*-------------------------------------------------- * Create three arrays to write to record store *-------------------------------------------------*/ public void writetestdata() String[] pets = "duke", "tiger", "spike", "beauregard"; boolean[] dog = true, false, true, true; int[] rank = 3, 0, 1, 2; writestream(pets, dog, rank); /*-------------------------------------------------- * Write to record store using streams. *-------------------------------------------------*/ public void writestream(string[] sdata, boolean[] bdata,int[] idata) // Write data into an internal byte array ByteArrayOutputStream strmbytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmdatatype = 14/34

new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sdata.length; i++) // Write Java data types strmdatatype.writeutf(sdata[i]); strmdatatype.writeboolean(bdata[i]); strmdatatype.writeint(idata[i]); // Clear any buffered data strmdatatype.flush(); // Get stream data into byte array and write record record = strmbytes.tobytearray(); rs.addrecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmbytes.reset(); strmbytes.close(); strmdatatype.close(); 15/34

db(e.tostring()); /*-------------------------------------------------- * Read from the record store using streams *-------------------------------------------------*/ public void readstream() // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recdata = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmbytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmdatatype = new DataInputStream(strmBytes); if (rs.getnumrecords() > 0) ComparatorString comp = new ComparatorString(); int i = 1; 16/34

RecordEnumeration re = rs.enumeraterecords(null, comp, false); while (re.hasnextelement()) // Get data into the byte array rs.getrecord(re.nextrecordid(), recdata, 0); // Read back the data types System.out.println("Record #" + i++); System.out.println("Name: " + strmdatatype.readutf()); System.out.println("Dog: " + strmdatatype.readboolean()); System.out.println("Rank: " + strmdatatype.readint()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmbytes.reset(); comp.comparestringclose(); // Free enumerator re.destroy(); strmbytes.close(); strmdatatype.close(); 17/34

db(e.tostring()); /*-------------------------------------------------- * Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(string str) System.err.println("Msg: " + str); /*-------------------------------------------------- Compares two strings to determine sort order Each record passed in contains multiple Java data types - use only the String data for sorting *-------------------------------------------------*/ class ComparatorString implements RecordComparator 18/34

private byte[] recdata = new byte[10]; // Read from a specified byte array private ByteArrayInputStream strmbytes = null; // Read Java data types from the above byte array private DataInputStream strmdatatype = null; public void comparestringclose() if (strmbytes!= null) strmbytes.close(); if (strmdatatype!= null) strmdatatype.close(); public int compare(byte[] rec1, byte[] rec2) String str1, str2; 19/34

// If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length); if (maxsize > recdata.length) recdata = new byte[maxsize]; // Read record #1 // Only need one read because the string to // sort on is the first "field" in the record strmbytes = new ByteArrayInputStream(rec1); strmdatatype = new DataInputStream(strmBytes); str1 = strmdatatype.readutf(); // Read record #2 strmbytes = new ByteArrayInputStream(rec2); strmdatatype = new DataInputStream(strmBytes); str2 = strmdatatype.readutf(); // Compare record #1 and #2 int result = str1.compareto(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; 20/34

return RecordComparator.EQUIVALENT; Trường dữ liệu đầu tiên trong các record là kiểu string, - dùng làm tiêu chí sắp xếp. Trước hết ta lấy chuỗi cần so sánh trong dãy byte bằng hàm readutf(), rồi dùng compareto() trong class String để sắp xếp: // Read record #1 // Only need one read because the string to // sort on is the first "field" in the record... str1 = strmdatatype.readutf(); // Read record #2... str2 = strmdatatype.readutf(); // Compare record #1 and #2 int result = str1.compareto(str2);... Output của ví dụ 4: 21/34

Ví dụ 5: integer sort /*-------------------------------------------------- * IntSort.java * * Sort records that contain multiple Java * data types. Sort using integer type. * * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class IntSort extends MIDlet 22/34

private RecordStore rs = null; // Record store static final String REC_STORE = "db_4"; // Name of record store public IntSort() openrecstore(); // Create the record store writetestdata(); // Write a series of records readstream(); // Read back the records closerecstore(); // Close record store deleterecstore(); // Remove the record store public void destroyapp( boolean unconditional ) public void startapp() // There is no user interface, go ahead and shutdown destroyapp(false); notifydestroyed(); public void pauseapp() public void openrecstore() 23/34

// Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); db(e.tostring()); public void closerecstore() rs.closerecordstore(); db(e.tostring()); public void deleterecstore() 24/34

if (RecordStore.listRecordStores()!= null) RecordStore.deleteRecordStore(REC_STORE); db(e.tostring()); /*-------------------------------------------------- * Create three arrays to write to record store *-------------------------------------------------*/ public void writetestdata() String[] pets = "duke", "tiger", "spike", "beauregard"; boolean[] dog = true, false, true, true; int[] rank = 3, 0, 1, 2; writestream(pets, dog, rank); 25/34

/*-------------------------------------------------- * Write to record store using streams. *-------------------------------------------------*/ public void writestream(string[] sdata, boolean[] bdata,int[] idata) // Write data into an internal byte array ByteArrayOutputStream strmbytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmdatatype = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sdata.length; i++) // Write Java data types strmdatatype.writeutf(sdata[i]); strmdatatype.writeboolean(bdata[i]); strmdatatype.writeint(idata[i]); // Clear any buffered data 26/34

strmdatatype.flush(); // Get stream data into byte array and write record record = strmbytes.tobytearray(); rs.addrecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmbytes.reset(); strmbytes.close(); strmdatatype.close(); db(e.tostring()); /*-------------------------------------------------- * Read from the record store using streams *-------------------------------------------------*/ public void readstream() 27/34

// Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recdata = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmbytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmdatatype = new DataInputStream(strmBytes); if (rs.getnumrecords() > 0) ComparatorInt comp = new ComparatorInt(); int i = 1; RecordEnumeration re = rs.enumeraterecords(null,comp, false); while (re.hasnextelement()) // Get data into the byte array rs.getrecord(re.nextrecordid(), recdata, 0); // Read back the data types System.out.println("Record #" + i++); System.out.println("Name: " + strmdatatype.readutf()); System.out.println("Dog: " + strmdatatype.readboolean()); 28/34

System.out.println("Rank: " + strmdatatype.readint()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmbytes.reset(); comp.compareintclose(); // Free enumerator re.destroy(); strmbytes.close(); strmdatatype.close(); db(e.tostring()); /*-------------------------------------------------- * Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ 29/34

private void db(string str) System.err.println("Msg: " + str); /*-------------------------------------------------- Compares two integers to determine sort order Each record passed in contains multiple Java data types - use only the integer data for sorting *-------------------------------------------------*/ class ComparatorInt implements RecordComparator private byte[] recdata = new byte[10]; // Read from a specified byte array private ByteArrayInputStream strmbytes = null; // Read Java data types from the above byte array private DataInputStream strmdatatype = null; public void compareintclose() if (strmbytes!= null) strmbytes.close(); if (strmdatatype!= null) 30/34

strmdatatype.close(); public int compare(byte[] rec1, byte[] rec2) int x1, x2; // If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length); if (maxsize > recdata.length) recdata = new byte[maxsize]; // Read record #1 // We want the integer from the record, which is // the last "field" thus we must read the String // and boolean to get to the integer strmbytes = new ByteArrayInputStream(rec1); strmdatatype = new DataInputStream(strmBytes); strmdatatype.readutf(); strmdatatype.readboolean(); 31/34

x1 = strmdatatype.readint(); // Here's our data // Read record #2 strmbytes = new ByteArrayInputStream(rec2); strmdatatype = new DataInputStream(strmBytes); strmdatatype.readutf(); strmdatatype.readboolean(); x2 = strmdatatype.readint(); // Here's our data // Compare record #1 and #2 if (x1 == x2) return RecordComparator.EQUIVALENT; else if (x1 < x2) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; return RecordComparator.EQUIVALENT; Trong ví dụ này ta vẫn sẽ dùng dữ liệu của ví dụ 4, tiêu chí sắp xếp là theo kiểu integer, do đó trước hết ta phải lấy dữ liệu trong dãy byte. Tuy nhiên,,có một lưu ý là do dữ liệu 32/34

ta cần lấy nằm cuối cùng trong dãy byte do đó ra cần phải đọc theo thứ tự, tức là phải đọc kiểu String, boolean rồi mới đến integer: // Read record #1 // We want the integer from the record, which is // the last "field" thus we must read the String // and boolean to get to the integer... strmdatatype.readutf(); strmdatatype.readboolean(); x1 = strmdatatype.readint(); // Here's our data // Read record #2... strmdatatype.readutf(); strmdatatype.readboolean(); x2 = strmdatatype.readint(); // Here's our data // Compare record #1 and #2... Output của ví dụ 5: 33/34

34/34