You are on page 1of 431

Hướng dẫn sử dụng biểu thức chính quy trong Java

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

1- ​Regular expression

​ uy tắc viết biểu thức chính quy


2- Q

​ ác ký tự đặc biệt trong Java Regex (Special characters)


3- C

​ ử dụng String.matches(String)
4- S

​ ử dụng Pattern và Matcher


5- S

6- ​Nhóm (Group)

​ ử dụng Pattern, Matcher, Group và *?


7- S

1- Regular expression
Một biểu thức chính quy (Regular expressions) định nghĩa một khuôn mẫu (pattern) tìm kiếm chuỗi.
Nó có thể được sử dụng tìm kiếm, sửa đổi, và thao tác trên văn bản. Khuôn mẫu được định nghĩa bởi
biểu thức chính quy có thể khớp một hoặc một vài lần, hoặc không khớp với một văn bản cho trước.

Viết tắt của biểu thức chính quy là regex

Biểu thức chính quy (Regular expression) được hỗ trợ bởi hầu hết các ngôn ngữ lập trình, ví dụ,
Java, C#, C/C++​, v..v Thật không may mỗi ngôn ngữ hỗ trợ biểu thức thông thường hơi khác nhau.

Có thể bạn quan tâm:

● Hướng dẫn sử dụng biểu thức chính quy trong C#


● Hướng dẫn sử dụng biểu thức chính quy trong ECMAScript

2- Quy tắc viết biểu thức chính quy


TT Biểu thức Mô tả
chính quy

1 . Khớp (match) với bất kỳ ký tự nào

2 ^regex Biểu thức chính quy phải khớp tại điểm bắt đầu

3 regex$ Biểu thức chính quy phải khớp ở cuối dòng.

4 [abc] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c.

5 [abc][vz] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c theo sau là v hay z.

6 [^abc] Khi dấu ^ xuất hiện như là nhân vật đầu tiên trong dấu ngoặc vuông, nó phủ nhận
mô hình. Điều này có thể khớp với bất kỳ ký tự nào ngoại trừ a hoặc b hoặc c.

7 [a-d1-7] Phạm vi: phù hợp với một chuỗi giữa a và điểm d và con số từ 1 đến 7.

8 X|Z Tìm X hoặc Z.

9 XZ Tìm X và theo sau là Z.

10 $ Kiểm tra kết thúc dòng.

11 \d Số bất kỳ, viết ngắn gọn cho [0-9]

12 \D Ký tự không phải là số, viết ngắn gon cho [^0-9]

13 \s Ký tự khoảng trắng, viết ngắn gọn cho [ \t\n\x0b\r\f]

14 \S Ký tự không phải khoản trắng, viết ngắn gọn cho [^\s]

15 \w Ký tự chữ, viết ngắn gọn cho [a-zA-Z_0-9]

16 \W Ký tự không phải chữ, viết ngắn gọn cho [^\w]

17 \S+ Một số ký tự không phải khoảng trắng (Một hoặc nhiều)

18 \b Ký tự thuộc a-z hoặc A-Z hoặc 0-9 hoặc _, viết ngắn gọn cho [a-zA-Z0-9_].
19 * Xuất hiện 0 hoặc nhiều lần, viết ngắn gọn cho {0,}

20 + Xuất hiện 1 hoặc nhiều lần, viết ngắn gọn cho {1,}

21 ? Xuất hiện 0 hoặc 1 lần, ? viết ngắn gọn cho {0,1}.

22 {X} Xuất hiện X lần, {}

23 {X,Y} Xuất hiện trong khoảng X tới Y lần.

24 *? * có nghĩa là xuất hiện 0 hoặc nhiều lần, thêm ? phía sau nghĩa là tìm kiếm khớp
nhỏ nhất.

3- Các ký tự đặc biệt trong Java Regex (Special characters)


Một số ký tự đặc biệt trong Java Regex​:

1
2 \.[{(*+?^$|

Những ký tự liệt kê ở trên là các ký tự đặc biệt. Trong ​Java Regex bạn muốn nó hiểu các ký tự đó
theo cách thông thường bạn cần thêm dấu \ ở phía trước.

Chẳng hạn ký tự chấm . ​java regex đang hiểu là một ký tự bất kỳ, nếu bạn muốn nó hiểu là một ký tự
chấm thông thường, cần phải có dấu \ phía trước.

1
2 // Mẫu regex mô tả một ký tự bất kỳ.
3
4 String regex = ".";
5

// Mẫu regex mô tả ký tự dấu chấm.

String regex = "\\.";


4- Sử dụng String.matches(String)

● Class String

1
2 ...
3
4
5

// Kiểm tra đối tượng toàn bộ String có khớp với regex hay không.

public boolean matches(String regex)

..

Sử dụng method ​String.matches(String regex) cho phép bạn kiểm tra toàn bộ ​String có khớp với
một regex​ hay không. Đây là một cách thông dụng nhất. Hãy xem các ví dụ:

StringMatches.java

?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class StringMatches {
7
8
9
10
11 public static void main(String[] args) {
12
13
14
15
16 String s1 = "a";
17
18 System.out.println("s1=" + s1);
19
20
// Kiểm tra toàn bộ s1
21
22
23 // Khớp với bất kỳ ký tự nào
24
25 // Quy tắc: .
26
27
// ==> true
28
29
30 boolean match = s1.matches(".");
31
32 System.out.println("-Match . " + match);
33
34
35
36
37 s1 = "abc";
38
39 System.out.println("s1=" + s1);
40
41
42
43 // Kiểm tra toàn bộ s1
44
45 // Khớp với bất kỳ ký tự nào.
46
47
// ==> false (Rõ ràng, chuỗi 3 ký tự sao khớp với 1 ký tự bất kỳ?)
48
49
50 match = s1.matches(".");
51
52 System.out.println("-Match . " + match);
53
54
55
56
57 // Kiểm tra toàn bộ s1
58
59 // Khớp với bất kỳ ký tự nào 0 hoặc nhiều lần
60
61
// Kết hợp các quy tắc: . và *
62
63
64 // ==> true
65
66 match = s1.matches(".*");
67
68
System.out.println("-Match .* " + match);
69
70
71
72
73 String s2 = "m";
74
75
System.out.println("s2=" + s2);
76
77
78 // Kiểm tra toàn bộ s2
79
80 // Bắt đầu bởi m
81
82
83
84 // Quy tắc ^
85
86 // true
87
88
match = s2.matches("^m");
89
90
91 System.out.println("-Match ^m " + match);
92
93
94
95
s2 = "mnp";
96
97
98 System.out.println("s2=" + s2);
99
10 // Kiểm tra toàn bộ s2
0
10
// Bắt đầu bởi m
1
10
2 // Quy tắc ^
10
3 // ==> false (Rõ ràng, chuỗi 3 ký tự sao khớp với 1 ký tự bất kỳ bắt đầu bởi m)

match = s2.matches("^m");

System.out.println("-Match ^m " + match);

// Bắt đầu bởi m

// Sau đó là ký tự bất kỳ, xuất hiện 1 hoặc nhiều lần.

// Quy tắc ^ và . và +
// true

match = s2.matches("^m.+");

System.out.println("-Match ^m.+ " + match);

String s3 = "p";

System.out.println("s3=" + s3);

// Kiểm tra s3 kết thúc bằng p

// Quy tắc $

// true

match = s3.matches("p$");

System.out.println("-Match p$ " + match);

s3 = "2nnp";

System.out.println("s3=" + s3);

// Kiểm tra toàn bộ s3

// Kết thúc bằng p

// ==> false (Rõ ràng, chuỗi 4 ký tự sao khớp với 1 ký tự p cuối cùng)
match = s3.matches("p$");

System.out.println("-Match p$ " + match);

// Kiểm tra toàn bộ s3

// Ký tự bất kỳ xuất hiện 1 lần: .

// tiếp theo là n, xuất hiện 1 hoặc tối đa 3 lần.

// Kết thúc bởi p: p$

// Kết hợp các quy tắc: . , {X,Y}, $

// true

match = s3.matches(".n{1,3}p$");

System.out.println("-Match .n{1,3}p$ " + match);

String s4 = "2ybcd";

System.out.println("s4=" + s4);

// Bắt đầu là 2

// Tiếp theo x hoặc y hoặc z

// Tiếp theo bất kỳ 1 hoặc nhiểu lần.


// Kết hợp các quy tắc: [abc] , . , +

// true

match = s4.matches("2[xyz].+");

System.out.println("-Match 2[xyz].+ " + match);

String s5 = "2bkbv";

// Bắt đầu là bất kỳ, 1 hoặc nhiểu lần

// Tiếp theo a hoặc b, hoặc c: [abc]

// Tiếp theo z hoặc v: [zv]

// Tiếp theo bất kỳ

// true

match = s5.matches(".+[abc][zv].*");

System.out.println("-Match .+[abc][zv].* " + match);

}
}

Kết quả chạy ví dụ:

SplitWithRegex.java

?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class SplitWithRegex {
7
8
9
10
11 public static final String TEXT = "This is my text";
12
13
14
15
16 public static void main(String[] args) {
17
18 System.out.println("TEXT=" + TEXT);
19
20
// Khoảng trắng xuất hiện 1 hoặc nhiều lần.
21
22
23 // Các ký tự khoảng trắng: \t\n\x0b\r\f
24
25 // Kết hợp quy tắc: \s và +

String regex = "\\s+";

String[] splitString = TEXT.split(regex);

// 4

System.out.println(splitString.length);

for (String string : splitString) {


System.out.println(string);

// Thay thế tất cả các khoảng trắng với ký tự tab.

String newText = TEXT.replaceAll("\\s+", "\t");

System.out.println("New text=" + newText);

Kết quả chạy ví dụ:

EitherOrCheck.java

?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class EitherOrCheck {
7
8
9
10
11 public static void main(String[] args) {
12
13
14
15
16 String s = "The film Tom and Jerry!";
17
18 // Kiểm tra toàn bộ s
19
20
// Bắt đầu bởi ký tự bất kỳ xuất hiện 0 hoặc nhiều lần
21
22
23 // Tiếp theo là từ Tom hoặc Jerry
24
25 // Kết thúc bởi ký tự bất kỳ xuất hiện 0 hoặc nhiều lần
26
27
// Kết hợp các quy tắc: ., *, X|Z
28
29
30 // true
31
boolean match = s.matches(".*(Tom|Jerry).*");

System.out.println("s=" + s);

System.out.println("-Match .*(Tom|Jerry).* " + match);


s = "The cat";

// false

match = s.matches(".*(Tom|Jerry).*");

System.out.println("s=" + s);

System.out.println("-Match .*(Tom|Jerry).* " + match);

s = "The Tom cat";

// true

match = s.matches(".*(Tom|Jerry).*");

System.out.println("s=" + s);

System.out.println("-Match .*(Tom|Jerry).* " + match);

Kết quả chạy ví dụ:


5- Sử dụng Pattern và Matcher
1. ​Pattern ​là một đối tượng mẫu, một phiên bản đã được biên dịch của một biểu thức chính quy. Nó
không có cấu tử (constructor) public, và chúng ta sẽ sử dụng method tĩnh ​compile(String) để tạo đối
tượng, với tham số là biểu thức chính quy.

2. ​Matcher ​là một phương tiện để so khớp chuỗi dữ liệu đầu vào với đối tượng ​Pattern ​đã được tạo
ra ở trên. Class này không có cấu tử public, và chúng ta lấy đối tượng này thông qua method
matcher(String)​ của đối tượng Pattern​. Với tham số đầu vào String​ là văn bản cần kiểm tra.

3. ​PatternSyntaxException ​sẽ bị ném ra nếu biểu thức chính quy có ngữ pháp không chính xác.

1
2 String regex= ".xx.";
3
4 // Tạo đối tượng Pattern thông qua method tĩnh.
5
6
Pattern pattern = Pattern.compile(regex);
7
8
9 // Lấy ra đối tượng Matcher

Matcher matcher = pattern.matcher("MxxY");

boolean match = matcher.matches();


System.out.println("Match "+ match);
● Class Pattern:

1
2 public static Pattern compile(String regex, int flags) ;
3
4
5
6
public static Pattern compile(String regex);
7

public Matcher matcher(CharSequence input);

public static boolean matches(String regex, CharSequence input);


● Class Matcher:

?
1
2 public int start()
3
4
5
6
public int start(int group)
7
8
9
10
11 public int end()
12
13
14
15
16 public int end(int group)
17
18
19
20
public String group()
21

public String group(int group)

public String group(String name)

public int groupCount()

public boolean matches()


public boolean lookingAt()

public boolean find()

Đây là một ví dụ sử dụng ​Matcher và method ​find() để tìm kiếm các chuỗi con khớp với một biểu
thức chính quy.

MatcherFind.java

?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class MatcherFind {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 final String TEXT = "This \t is a \t\t\t String";
24
25
26
27
// Khoảng trắng xuất hiện 1 hoặc nhiều lần.
28

String regex = "\\s+";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(TEXT);


int i = 0;

while (matcher.find()) {

System.out.print("start" + i + " = " + matcher.start());

System.out.print(" end" + i + " = " + matcher.end());

System.out.println(" group" + i + " = " + matcher.group());

i++;

Kết quả chạy ví dụ:

Method ​Matcher.lookingAt()

MatcherLookingAt.java

?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class MatcherLookingAt {
14
15
16
17
18 public static void main(String[] args) {
19
20
String country1 = "iran";
21
22
23 String country2 = "Iraq";
24
25
26
27
// Bắt đầu bởi I tiếp theo là ký tự bất kỳ.
28
29
30 // Tiếp theo là ký tự a hoặc e.
31
String regex = "^I.[ae]";

Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);


Matcher matcher = pattern.matcher(country1);

// lookingAt() tìm kiếm khớp phần đầu.

System.out.println("lookingAt = " + matcher.lookingAt());

// Trong khi matches() phải khớp toàn bộ

System.out.println("matches = " + matcher.matches());

// Reset matcher với text mới, country2

matcher.reset(country2);

System.out.println("lookingAt = " + matcher.lookingAt());

System.out.println("matches = " + matcher.matches());

6- Nhóm (Group)
Một biểu thức chính quy bạn có thể tách ra thành các nhóm (group):

?
1
2 // Một biểu thức chính quy
3
4 String regex = "\\s+=\\d+";
5
6
7
8
// Viết dưới dạng group, bởi dấu ()

String regex2 = "(\\s+)(=)(\\d+)";

// Một cách khác.

String regex3 = "(\\s+)(=\\d+)";

Các group có thể lồng nhau, và như vậy cần một quy tắc đánh chỉ số các group. Toàn bộ pattern
được định nghĩa là group số 0. Còn lại được mô tả giống hình minh họa dưới đây:

Chú ý: Sử dụng (?:pattern) để thông báo với Java không xem đây là một group (None-capturing
group)

Từ Java 7, bạn có thể xác định một group có tên ​(?<name>pattern)​, Và bạn có thể truy cập các nội
dung khớp với ​Matcher.group(String name)​. Điều này làm Regex dài hơn, nhưng mã này là có ý
nghĩa hơn, dễ hơn.

Nhóm bắt theo tên cũng có thể được truy cập thông qua ​Matcher.group(int group) với cách đánh chỉ
số tương tự.
Nội bộ, Java chỉ lập bản đồ (ánh xạ) từ tên đến chỉ số nhóm. Do đó, bạn không thể sử dụng cùng tên
để bắt 2 nhóm khác nhau.

Hãy xem một ví dụ sử dụng đánh tên cho nhóm (group) ( Java >=7​)

NamedGroup.java

1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class NamedGroup {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23
24
25 final String TEXT = " int a = 100;float b= 130;float c= 110 ; ";
26
27
28
29
30 // Sử dụng (?<groupName>pattern) để định nghĩa một Group có tên: groupName
// Định nghĩa group có tên declare: sử dụng (?<declare> ...)

// Và một group có tên value: sử dụng: (?<value> ..)

String regex = "(?<declare>\\s*(int|float)\\s+[a-z]\\s*)=(?<value>\\s*\\d+\\s*);";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(TEXT);

while (matcher.find()) {

String group = matcher.group();

System.out.println(group);

System.out.println("declare: " + matcher.group("declare"));

System.out.println("value: " + matcher.group("value"));

System.out.println("------------------------------");

Kết quả chạy ví dụ:


Để dễ hiểu bạn có thể xem hình minh họa dưới đây:

7- Sử dụng Pattern, Matcher, Group và *?


Trong một số tình huống *? rất quan trọng, hãy xem một ví dụ sau:

?
1
2 // Đây là một regex
3
4 // Bắt gặp ký tự bất kỳ 0 hoặc nhiều lần,
5
6
// sau đó tới ký tự ' và tiếp theo là >
7
8
9 String regex = ".*'>";
10

// Đoạn TEXT1 sau đây có vẻ hợp với regex nói trên.

String TEXT1 = "FILE1'>";

// Đoạn TEXT2 sau cũng hợp với regex nói trên.

String TEXT2 = "FILE1'> <a href='​http://HOST/file/FILE2​'>";

*?​ sẽ tìm ra một phù hợp nhỏ nhất. Chúng ta xem ví dụ sau:

NamedGroup2.java

?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class NamedGroup2 {
14
15
16
17
18 public static void main(String[] args) {
19
20
String TEXT = "<a href='​http://HOST/file/FILE1​'>File 1</a>"
21
22
23 + "<a href='​http://HOST/file/FILE2​'>File 2</a>";
24
25

// Java >= 7.

// Định nghĩa một group có tên fileName

// *? ==> Nó sẽ tìm một phù hợp nhỏ nhất.

String regex = "/file/(?<fileName>.*?)'>";

Pattern pattern = Pattern.compile(regex);


Matcher matcher = pattern.matcher(TEXT);

while (matcher.find()) {

System.out.println("File Name = " + matcher.group("fileName"));

Kết quả chạy ví dụ:

Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Nguyên tắc hoạt động của Thread

2- ​Ví dụ bắt đầu với Thread

3- ​Runnable Interface

4- ​Luồng Deamon (Deamon Thread)

5- ​Sử dụng join() & join(long)

6- ​Xử lý ngoại lệ cho Thread

7- ​Sử dụng yield()

8- ​So sánh sleep() và wait()

Java cơ bản

Hướng dẫn lập trình đa luồng trong Java - Java Multithreading

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ guyên tắc hoạt động của Thread


1- N

​ í dụ bắt đầu với Thread


2- V

3- ​Runnable Interface

​ uồng Deamon (Deamon Thread)


4- L

​ ử dụng join() & join(long)


5- S
​ ử lý ngoại lệ cho Thread
6- X

​ ử dụng yield()
7- S

8- ​So sánh sleep() và wait()

1- Nguyên tắc hoạt động của Thread

2- Ví dụ bắt đầu với Thread


Chúng ta cần 2 class tham gia vào ví dụ này.

● HelloMain ​là một class thông thường có hàm main, nó là một luồng chính (main thread).
● HelloThread ​là một class mở rộng từ class Thread​. Nó được tạo và chạy kích hoạt chạy bên
trong luồng chính và sẽ chạy song song với luồng chính.

?
1
2 package org.o7planning.tutorial.thread.hellothread;
3
4
5
6 public class HelloMain {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
int idx = 1;
15
16
17
18
19 for (int i = 0; i < 2; i++) {
20
21
22
23 System.out.println("Main thread running " + idx++);
24
25 // Ngủ 2101 milli giây.
26
27 Thread.sleep(2101);
28
29 }

HelloThread helloThread = new HelloThread();

// Chạy thread

helloThread.start();
for (int i = 0; i < 3; i++) {

System.out.println("Main thread running " + idx++);

// Ngủ 2101 milli giây.

Thread.sleep(2101);

System.out.println("==> Main thread stopped");

}
HelloThread.java

?
1
2 package org.o7planning.tutorial.thread.hellothread;
3
4
5
6 public class HelloThread extends Thread {
7
8
9
10 // Code trong hàm run() sẽ được thực thi khi
11
12 // thread được chạy (start)
13
14
@Override
15
16
public void run() {
17
18
19 int index = 1;
20
21
22
23 for (int i = 0; i < 10; i++) {

System.out.println(" - HelloThread running " + index++);

try {

// Ngủ 1030 milli giây.

Thread.sleep(1030);

} catch (InterruptedException e) {

}
}

System.out.println(" - ==> HelloThread stopped");

}
Kết quả chạy class HelloMain​:

3- Runnable Interface
Bạn cũng có thể tạo một thread t​ ừ một class thi hành interface Runnable​. Xem ví dụ minh họa:

RunnableDemo.java

?
1
2 package org.o7planning.tutorial.thread.runnable;
3
4
5
6 public class RunnableDemo implements Runnable {
7
8
9
10 @Override
11
12 public void run() {
13
14
int idx = 1;
15
16
for (int i = 0; i < 5; i++) {
17
18
System.out.println("Hello from RunnableDemo " + idx++);

// Ngủ 2 giây.

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

}
RunnableTest.java

?
1
2 package org.o7planning.tutorial.thread.runnable;
3
4
5
6 public class RunnableTest {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("Main thread running..");
15
16
17
18
// Tạo một thread từ Runnable.

Thread thread = new Thread(new RunnableDemo());

thread.start();

// Ngủ 5 giây.

Thread.sleep(5000);

System.out.println("Main thread stopped");

}
Chạy class RunnableTest​:
4- Luồng Deamon (Deamon Thread)
Java ​chia thread làm 2 loại một loại thông thường và ​Deamon Thread​. Chúng chỉ khác nhau ở cách
thức ngừng hoạt động. Trong một chương trình các luồng thông thường và luồng ​Deamon chạy song
song với nhau. Khi tất cả các luồng thông thường kết thúc, mọi luồng ​Deamon cũng sẽ bị kết thúc
theo bất kể nó đang làm việc gì.

Chú ý:

Sử dụng s​ etDeamon(boolean) để sét đặt một luồng là Deamon hoặc không. Chú ý, bạn chỉ có thể
​ etDeamon(boolean) khi thread chưa được chạy. Điều đó có nghĩa là khi thread đã chạy
gọi hàm s
bạn không thể chuyển luồng từ non-deamon​ sang d
​ eamon​ và ngược lại.

Khi một luồng mới được tạo ra, nó được thừa hưởng đặc tính ​deamon từ luồng cha. Như vậy khi
​ ain của 1 class nó vốn là luồng n
bạn tạo một luồng trong hàm m ​ on-deamon,​ vì vậy thread tạo ra
mặc định cũng là ​none-deamon​. Như vậy nếu bạn tạo một luồng mới trong một luồng ​Deamon​,
mặc định nó cũng sẽ là Deamon.​

1
2 Thread thread = new MyThread();
3
4
5
6 // sét luồng này là deamon.
7
8 // Chỉ gọi được method này khi thread chưa start.
9
10
11
// Trong trường hợp start rồi sẽ bị một ngoại lệ.

thread.setDeamon(true);

// Sét luồng này là non-deamon.

// Chỉ gọi được method này khi thread chưa start.

// Trong trường hợp start rồi sẽ bị một ngoại lệ.

thread.setDeamon(false);
Để dễ hiểu chúng ta xem ví dụ sau, chúng ta cần 3 class tham gia vào minh họa:

NoneDeamonThread.java

?
1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 public class NoneDeamonThread extends Thread {
7
8
9
10 @Override
11
12 public void run() {
13
14
int i = 0;
15
16
17
18
19 // Vòng lặp 10 lần. Luồng này sẽ kết thúc.
20
21 while (i < 10) {
22
System.out.println(" - Hello from None Deamon Thread " + i++);

try {

// Ngủ 1 giây.

Thread.sleep(1000);

} catch (InterruptedException e) {

// Ghi ra thông báo luồng này kết thúc.


System.out.println("\n==> None Deamon Thread ending\n");

}
DeamonThread.java

1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 class DeamonThread extends Thread {
7
8
9
10 @Override
11
12 public void run() {
13
14
int count = 0;
15
16
17
18
19 // Vòng lặp vô tận.

while (true) {

System.out.println("+ Hello from Deamon Thread " + count++);

try {

// Ngủ 2 giây.

sleep(2000);

} catch (InterruptedException e) {
}

}
DaemonTest.java

1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 public class DaemonTest {
7
8
9
10 public static void main(String[] args) {
11
12 System.out.println("==> Main Thread running..\n");
13
14
// Tạo một Thread
15
16
Thread deamonThread = new DeamonThread();
17
18
19 // Sét nó là Deamon Thread.
20
21 deamonThread.setDaemon(true);
22
23 deamonThread.start();
24
25
26
// Tạo một Thread khác

new NoneDeamonThread().start();
try {

// Ngủ 5 giây.

Thread.sleep(5000);

} catch (InterruptedException e) {

// Ghi ra thông báo luồng main này kết thúc.

System.out.println("\n==> Main Thread ending\n");

}
Kết quả chạy class DeamonTest​:
Hình minh họa trên cho thấy rằng luồng ​Deamon đã bị dừng lại khi tất cả các luồng thông thường đã
dừng. Mặc dù code của nó là chạy vô tận.

Luồng deamon thường dùng làm gì?


Một trong các luồng ​Deamon quan trọng của Java đó là luồng gom rác ( ​Garbage Collection
Thread), nghĩa là gom các tài nguyên không còn sử dụng để giải phóng bộ nhớ. Khi tất cả các luồng
người dùng không còn hoạt động nữa luồng gom rác cũng bị dừng theo.

5- Sử dụng join() & join(long)


Thread.join() là một method thông báo rằng hãy chờ thread này hoàn thành rồi thread cha mới được
tiếp tục chạy.

1
2 // Thread cha cần phải đợi cho tới khi luồng này kết thúc
3
4 // mới được chạy tiếp.
5
6 // (Nó tương đương với gọi join(0) )
7
8 public final void join() throws InterruptedException;
9
10
11
12 // Thread cha cần phải đợi 'millis' milli giây mới được tiếp tục chạy.
13
14
15 // kể từ lúc gọi join(long).
16
// Nếu tham số millis = 0 nghĩa là đợi cho tới khi luồng này kết thúc.

public final synchronized void join(long millis) throws InterruptedException;

// Thread cha cần phải đợi 'millis' milli giây và 'nanos' nano giây mới được tiếp tục
chạy.

// kể từ lúc gọi join(long,int).

// Nếu tham số millis = 0 & nanos = 0 nghĩa là đợi cho tới khi luồng này kết thúc.

// 1 giây = 1000000 nano giây.

public final synchronized void join(long millis, int nanos) throws InterruptedException;
Hãy xem một ví dụ minh họa:

JoinThread.java

?
1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinThread extends Thread {
7
8 private String threadName;
9
10 private int count;
11
12
13
14
public JoinThread(String threadName, int count) {
15
16
this.threadName = threadName;
17
18
19 this.count = count;
20
21 }
22
23
24
@Override

public void run() {

for (int i = 1; i < count + 1; i++) {

System.out.println("Hello from " + this.threadName + " " + i);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {
}

System.out.println("\n==> Thread " + threadName + " end!\n");

}
JoinTest.java

1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinTest {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("\n==> Main thread starting..\n");
15
16
17
18
19 Thread joinThreadA = new JoinThread("A*", 2);
20
21 Thread joinThreadB = new JoinThread("B*", 3);
22
23
24
25 // Thread thông thường, sẽ không sử dụng join().
26
27 Thread noJoinThreadC = new JoinThread("C", 5);
28
29
30
31
32 joinThreadA.start();

joinThreadB.start();

noJoinThreadC.start();

// Sử dụng join()

joinThreadA.join();

joinThreadB.join();

// Đoạn code dưới đây sẽ phải chờ cho tới khi 2

// joinThread A,B hoàn thành, mới được chạy tiếp.

System.out.println("Hello from main thread...");

System.out.println("Thread A isLive? " + joinThreadA.isAlive());

System.out.println("Thread B isLive? " + joinThreadB.isAlive());

System.out.println("Thread C isLive? " + noJoinThreadC.isAlive());

System.out.println("\n==> Main Thread end!\n");

}
Kết quả chạy class JoinTest​:
Ví dụ sử dụng join(long millis)​:

JoinTest2.java

?
1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinTest2 {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("\n==> Main thread starting..\n");
15
16
17
18
19 Thread joinThreadA = new JoinThread("A*", 5);
20
21
22
23 joinThreadA.start();
24
// Luồng cha (main) phải chờ 5000 milli giây

// mới được tiếp tục chạy. (Không nhất thiết phải A kết thúc)

joinThreadA.join(5000);

System.out.println("Main thread after 5000 milli second");

System.out.println("Hello from main thread...");

System.out.println("Thread A isLive? " + joinThreadA.isAlive());


System.out.println("\n==> Main Thread end!\n");

}
Kết quả chạy ví dụ:

6- Xử lý ngoại lệ cho Thread


Phương thức ​Thread.setDefaultUncaughtExceptionHandler() thiết lập mặc định xử lý khi luồng đột
ngột chấm dứt do một ngoại lệ còn tự do, mà không có xử lý khác đã được xác định cho luồng đó.

ThreadExceptionDemo.java

?
1
2 package org.o7planning.tutorial.thread.exception;
3
4
5
6 import java.util.Random;
7
8
9
10 public class ThreadExceptionDemo {
11
12
13
14
public static class RunnableTest implements Runnable {
15
16
17
18
19 @Override
20
21 public void run() {
22
23 System.out.println("Thread running ..");
24
25
26
27 while (true) {
28
29 Random r = new Random();
30
31
// Một số ngẫu nhiên từ 0 - 99
32
33
int i = r.nextInt(100);
34
35
36 System.out.println("Next value " + i);
37
38
39
40 try {
41
42
43 Thread.sleep(2000);
44
45 } catch (InterruptedException e) {
46
47 }
48
49
50
if (i > 70) {

// Mô phỏng một ngoại lệ đã không được sử lý trong luồng.

throw new RuntimeException("Have a problem...");

public static void main(String[] args) {

System.out.println("==> Main thread running...");

Thread thread = new Thread(new RunnableTest());

Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
@Override

public void uncaughtException(Thread t, Throwable e) {

System.out.println("#Thread: " + t);

System.out.println("#Thread exception message: " + e.getMessage());

});

thread.start();

System.out.println("==> Main thread end...");

}
Kết quả chạy ví dụ:
7- Sử dụng yield()

Về mặt lý thuyết, ​"yield" có nghĩa là để cho đi, từ bỏ, đầu hàng. Một luồng ​yield nói với máy ảo là nó
sẵn sàng để cho các thread khác được sắp xếp ở vị trí của nó. Điều này cho thấy rằng nó không phải
làm một cái gì đó quá quan trọng. Lưu ý rằng nó chỉ là một gợi ý, mặc dù, và không đảm bảo có hiệu
lực ở tất cả.

yield()​ được định nghĩa như sau trong Thread.java

1
public static native void yield();
Như vậy phương thức ​yield() được sử dụng khi bạn bạn thấy rằng thread đó đang rảnh rỗi, nó không
phải làm việc gì quan trọng, nên nó gợi ý hệ điều hành tạm thời nhường quyền ưu tiên cho các luồng
khác.
Ví dụ dưới đây, có 2 luồng, mỗi luồng in ra một dòng văn bản 100K lần (con số đủ lớn để thấy sự
khác biệt). Một luồng được sét độ ưu tiên cao nhất và một luồng được sét độ ưu tiên ít nhất. Đo
khoảng thời gian kết thúc của 2 luồng.

YieldThreadExample.java

?
1
2 package org.o7planning.tutorial.thread.yield;
3
4
5
6 import java.util.Date;
7
8
9
10 public class YieldThreadExample {
11
12
13
14
private static Date importantEndTime;
15
16
private static Date unImportantEndTime;
17
18
19
20
21 public static void main(String[] args) {
22
23 importantEndTime = new Date();
24
25 unImportantEndTime = new Date();
26
27
28
29 System.out.println("Create thread 1");
30
31
32
33
Thread importantThread = new ImportantThread();
34
35
36
37
38 // Sét đặt độ ưu tiên cao nhất cho thread này.
39
40 importantThread.setPriority(Thread.MAX_PRIORITY);
41
42
43
44
45 System.out.println("Create thread 2");
46
47
48
49 Thread unImportantThread = new UnImportantThread();
50
51
52
53 // Sét đặt độ ưu tiên thấp nhất cho thread này.
54
55
unImportantThread.setPriority(Thread.MIN_PRIORITY);
56
57
58
59
60 // Start threads.
61
62 unImportantThread.start();
63
64 importantThread.start();
65
66
67
68 }
69
70
71
72
// Một nhiệm vụ quan trọng, yêu cầu độ ưu tiên cao.
73
74
static class ImportantThread extends Thread {

@Override

public void run() {


for (int i = 0; i < 100000; i++) {

System.out.println("\n Important work " + i);

// Thông báo với hệ điều hành,

// thread này nhường quyền ưu tiên cho các luồng khác.

Thread.yield();

// Thời điểm kết thúc của thread này.

importantEndTime = new Date();

printTime();

static class UnImportantThread extends Thread {

@Override

public void run() {

for (int i = 0; i < 100000; i++) {


System.out.println("\n -- UnImportant work " + i);

// Thời điểm kết thúc của thread này.

unImportantEndTime = new Date();

printTime();

private static void printTime() {

// Khoảng thời gian (Mili giây).

long interval = unImportantEndTime.getTime() - importantEndTime.getTime();

System.out.println("UnImportant Thread - Important Thread = " //

+ interval + " milliseconds");

}
Kết quả: thread có ưu tiên thấp hơn đã hoàn thành công việc trước 51 mili giây so với thread có ưu
tiên cao hơn.
8- So sánh sleep() và wait()
TODO.

Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Giới thiệu

2- ​Thư viện điều khiển Database Oracle

2.1- ​Maven cho Oracle JDBC Driver

​ ách sử dụng (ojdbc)


2.2- C

3- ​Thư viện điều khiển Database MySQL

​ ách sử dụng
3.1- C

​ ột số rắc rối và cách khắc phục


3.2- M

4- ​Thư viện điều khiển Database SQL Server (JTDS)

​ ách sử dụng (jtds)


4.1- C

​ ột số rắc rối và cách khắc phục


4.2- M

5- ​Thư viện điều khiển Database SQL Server (SQLJDBC)

​ ách sử dụng (sqljdbc)


5.1- C

​ ột số rắc rối và cách khắc phục


5.2- M

6- ​Thư viện điều khiển Database MongoDB

Java cơ bản

Thư viện điều khiển các loại cơ sở dữ liệu khác nhau trong Java

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net

​ iới thiệu
1- G

​ hư viện điều khiển Database Oracle


2- T

2.1- ​Maven cho Oracle JDBC Driver

2.2- ​Cách sử dụng (ojdbc)

​ hư viện điều khiển Database MySQL


3- T

3.1- ​Cách sử dụng

3.2- ​Một số rắc rối và cách khắc phục

​ hư viện điều khiển Database SQL Server (JTDS)


4- T

4.1- ​Cách sử dụng (jtds)

4.2- ​Một số rắc rối và cách khắc phục

​ hư viện điều khiển Database SQL Server (SQLJDBC)


5- T

5.1- ​Cách sử dụng (sqljdbc)

5.2- ​Một số rắc rối và cách khắc phục

​ hư viện điều khiển Database MongoDB


6- T

1- Giới thiệu
Tài liệu này hướng dẫn các bạn download thư viện điều khiển một loại cơ sở dữ liệu nào đó, hiện tại
tôi hướng dẫn trên các loại database:

1. Oracle
2. MySQL
3. SQL Server​.

2- Thư viện điều khiển Database Oracle


Thư viện điều khiển cơ sở dữ liệu ​Oracle t​ hường có tên ​ojdbc14.jar​, ​ojdbc6.jar​, ... sự khác biệt chỉ
là nó được biên dịch bởi java ​phiên bản nào. Chẳng hạn:

● ojdbc14.jar​: được biên dịch và đóng gói bởi Java phiên bản 1.4
● ojdbc6.jar​: được biên dịch và đóng gói bởi Java phiên bản 6.

Chi tiết hơn bạn có thể xem và download tại website của Oracle​:

● http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html

Bạn có thể download file ​ojdbc6.jar​, nó có thể điều khiển cho database ​Oracle ​các phiên bản khác
nhau (XE, 10g, 11g, 12). Mà hầu hết các ứng dụng Java thời điểm này đều sử dụng Java phiên bản 6
hoặc mới hơn.
​ òi hỏi bạn phải có tài khoản Oracle ​(Đăng ký miễn phí).
Việc download tại website của Oracle đ

Trong trường hợp muốn nhanh chóng bạn có thể download theo đường link dưới đây:

● https://code.google.com/p/afirs/downloads/detail?name=ojdbc6.jar

Kết quả download được:

2.1- Maven cho Oracle JDBC Driver

1
2 <repositories>
3
4
<!-- Repository for ORACLE ojdbc6. -->
5
6
7 <repository>
8
9
<id>codelds</id>
10
11
12 <url>​https://code.lds.org/nexus/content/groups/main-repo​</url>
13
14
</repository>
15
16
17 </repositories>
18
19
20
21
22 .......
23
24

<dependencies>

......

<!-- Oracle database driver -->

<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc6</artifactId>

<version>11.2.0.3</version>

</dependency>

.......

</dependencies>

2.2- Cách sử dụng (ojdbc)


?

1
2 // Driver class:
3
4
oracle.jdbc.driver.OracleDriver
5
6
7
8
9
// URL Connection String: (SID)
10
11
12 String urlString ="jdbc:oracle:thin:@myhost:1521:mysid"

// URL Connection String: (Service Name)

String urlString ="jdbc:oracle:thin:username/pass@//myhost:1521/myservicename"

// Or:

String urlString ="jdbc:oracle:thin:@myhost:1521/myservicename";

Ví dụ kết nối JDBC v​ ào cơ sở dữ liệu Oracle​.

OracleConnUtils.java

?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class OracleConnUtils {
13
14
15
16
17 public static Connection getOracleConnection()
18
19
20 throws ClassNotFoundException, SQLException {
21
22 String hostName = "localhost";
23
24
25 String sid = "db11g";
26
27 String userName = "learningsql";
28
29
30 String password = "1234";
31
32
33
34
35 return getOracleConnection(hostName, sid, userName, password);

}
public static Connection getOracleConnection(String hostName, String sid,

String userName, String password) throws ClassNotFoundException,

SQLException {

// Khai báo class Driver cho DB Oracle

// Việc này cần thiết với Java 5

// Java6 trở lên tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java > 6, thì ko cần dòng này cũng được.

Class.forName("oracle.jdbc.driver.OracleDriver");

// Cấu trúc URL Connection dành cho Oracle

// Ví dụ: jdbc:oracle:thin:@localhost:1521:db11g

String connectionURL = "jdbc:oracle:thin:@" + hostName + ":1521:" + sid;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);
return conn;

3- Thư viện điều khiển Database MySQL


Bạn có thể download các thư viện điều khiển cơ sở dữ liệu MySQL t​ ại:

● http://mvnrepository.com/artifact/mysql/mysql-connector-java
Kết quả download được:

3.1- Cách sử dụng

Cách sử dụng: ( MySQL​)


?

1
2 // Driver class:
3
4
com.mysql.jdbc.Driver
5
6
7
8
9
// URL Connection String:

String url = "jdbc:mysql://hostname:3306/dbname";

// Ví dụ:

String url = "jdbc:mysql://localhost:3306/simplehr";

Ví dụ sử dụng JDBC ​kết nối vào Database MySQL

MySQLConnUtils.java
?

1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class MySQLConnUtils {
13
14
15
16
17 public static Connection getMySQLConnection()
18
19
20 throws ClassNotFoundException, SQLException {
21
22 String hostName = "localhost";
23
24
25 String dbName = "learningsql";
26
27 String userName = "root";
28
29
30 String password = "12345";
31
32
return getMySQLConnection(hostName, dbName, userName, password);
33

}
public static Connection getMySQLConnection(String hostName, String dbName,

String userName, String password) throws SQLException,

ClassNotFoundException {

// Khai báo class Driver cho DB MySQL

// Việc này cần thiết với Java 5

// Java6 trở lên tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.

Class.forName("com.mysql.jdbc.Driver");

// Cấu trúc URL Connection dành cho MySQL

// Ví dụ: jdbc:mysql://localhost:3306/simplehr

String connectionURL = "jdbc:mysql://" + hostName + ":3306/" + dbName;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;
}

3.2- Một số rắc rối và cách khắc phục

Trong một số trường hợp kết nối vào ​MySQL ​từ ​Java hoặc đơn giản là từ máy khác bị lỗi, nguyên
nhân có thể bạn chưa cấu hình MySQL server​ cho phép kết nối từ máy khác.

Bạn có thể xem lại mục cấu hình trong tài liệu "​ Hướng dẫn cài đặt và cấu hình MySQL
Community":​

● Hướng dẫn cài đặt và cấu hình MySQL Community

4- Thư viện điều khiển Database SQL Server (JTDS)


JTDS​ là một thư viện khác điều khiển database SQLServer​, nó là một thư viện mã nguồn mở.

jTDS​: là một mã nguồn mở thuần ​Java ​100% (type 4) ​JDBC 3.0 điều khiển cho ​Microsoft SQL
Server (6,5, 7, 2000, 2005, 2008, 2012) và ​Sybase ASE (10, 11, 12, 15). ​jTDS ​dựa trên ​FreeTDS ​và
hiện là trình điều khiển JDBC nhanh nhất cho ​SQL Server và ​Sybase​. ​jTDS ​là 100% tương thích với
JDBC 3.0​, hỗ trợ forward-only và scrollable/updateable ​ResultSet v​ à thực hiện tất cả các phương
thức của DatabaseMetaData v​ à ​ResultSetMetaData​.

Bạn có thể download các phiên bản tại:

● http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds
Kết quả download được:
4.1- Cách sử dụng (jtds)

Cách sử dụng: (SQL Server)

1
2 // Driver Class
3
4
net.sourceforge.jtds.jdbc.Driver
5
6
7
8
9
// Connection URL String:
10
11
12 jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
13
14
15
// Example 1:

String url =
"jdbc:jtds:sqlserver://MYPC:1433/simplehr;instance=SQLEXPRESS;user=sa;passwor
d=s3cr3t";

getConnection(url);

// Example 2:

String url = "jdbc:jtds:sqlserver://MYPC:1433/simplehr;instance=SQLEXPRESS";

getConnection(url, "sa", "s3cr3t"):

Ví dụ sử dụng JDBC ​kết nối vào Database SQLServer​ sử dụng thư viện JTDS​.

SQLServerConnUtils_JTDS.java

?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class SQLServerConnUtils_JTDS {
13
14
15
16
17 // Kết nối vào SQLServer.
18
19
20 // (Sử dụng thư viện điều khiển JTDS)
21
22 public static Connection getSQLServerConnection_JTDS() throws SQLException,
23
24
25 ClassNotFoundException {
26
27 String hostName = "localhost";
28
29
30 String sqlInstanceName = "SQLEXPRESS";
31
32
String database = "simplehr";
33
34
35 String userName = "sa";
36
37
String password = "12345";
38
39
40
41
42
43 return getSQLServerConnection_JTDS(hostName, sqlInstanceName, database,
44
userName, password);

// Trường hợp sử dụng SQLServer.

// Và thư viện JTDS.

private static Connection getSQLServerConnection_JTDS(String hostName,

String sqlInstanceName, String database, String userName,

String password) throws ClassNotFoundException, SQLException {

// Khai báo class Driver cho DB SQLServer

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.

Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Cấu trúc URL Connection dành cho SQLServer

// Ví dụ:

// jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS

String connectionURL = "jdbc:jtds:sqlserver://" + hostName + ":1433/"

+ database + ";instance=" + sqlInstanceName;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;

4.2- Một số rắc rối và cách khắc phục

Trong một số tình huống kết nối vào SQLServer ​và bị lỗi:

?
1
2 Exception in thread "main" java.sql.SQLException: Server tran-vmware has no
3 instance named SQLEXPRESS.
4
5
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:301)
6
7
8 at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
9

at java.sql.DriverManager.getConnection(DriverManager.java:571)

at java.sql.DriverManager.getConnection(DriverManager.java:215)

at
org.o7planning.tutorial.jdbc.ConnectionUtils.getSQLServerConnection_JTDS(Connecti
onUtils.java:189)

at
org.o7planning.tutorial.jdbc.ConnectionUtils.getSQLServerConnection_JTDS(Connecti
onUtils.java:72)

at
org.o7planning.tutorial.jdbc.ConnectionUtils.getMyConnection(ConnectionUtils.java:31)

at org.o7planning.tutorial.jdbc.TestConnection.main(TestConnection.java:20)

Lỗi trên có thể do bạn chưa bật dịch vụ ​TCP/IP của ​SQLServer​. Bạn có thể tham khảo thêm mục cấu
hình trong tài liệu: "Hướng dẫn cài đặt và cấu hình SQLServer Express ..." tại:

● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014

5- Thư viện điều khiển Database SQL Server (SQLJDBC)


SQLJDBC l​ à thư viện được cung cấp bởi Microsoft​.

Download:
● http://www.microsoft.com/en-us/download/details.aspx?id=11774
Giải nén file vừa download được.
Kết quả có được thư viện:

5.1- Cách sử dụng (sqljdbc)

?
1
2 // Driver Class:
3
4
com.microsoft.sqlserver.jdbc.SQLServerDriver
5
6
7
8
9
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
10
11
12
13
14
// Url String:
15

String url =
"jdbc:sqlserver://ServerIp;Instance=SQLEXPRESS;databaseName=simplehr";

// Hoặc

String url =
"jdbc:sqlserver://ServerIp:1433;Instance=SQLEXPRESS;databaseName=simplehr";

String user = "dbUserID";

String pass = "dbUserPassword";

Connection connection = DriverManager.getConnection(url, user, pass);


Ví dụ sử dụng JDBC ​kết nối vào Database SQLServer​ sử dụng thư viện SQLJDBC​.

SQLServerConnUtils_SQLJDBC.java

?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class SQLServerConnUtils_SQLJDBC {
13
14
15
16
17 // Kết nối vào SQLServer.
18
19
20 // (Sử dụng thư viện điều khiển SQLJDBC)
21
22 public static Connection getSQLServerConnection_SQLJDBC()
23
24
25 throws ClassNotFoundException, SQLException {
26
27 String hostName = "localhost";
28
29
30 String sqlInstanceName = "SQLEXPRESS";
31
32
String database = "learningsql";
33
34
35 String userName = "sa";
36
37
String password = "12345";
38
39
40
41
42
43 return getSQLServerConnection_SQLJDBC(hostName, sqlInstanceName,
44
45
database, userName, password);

// Trường hợp sử dụng SQLServer.

// Và thư viện SQLJDBC.

private static Connection getSQLServerConnection_SQLJDBC(String hostName,

String sqlInstanceName, String database, String userName,

String password) throws ClassNotFoundException, SQLException {

// Khai báo class Driver cho DB SQLServer

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Cấu trúc URL Connection dành cho SQLServer

// Ví dụ:

// jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr

String connectionURL = "jdbc:sqlserver://" + hostName + ":1433"

+ ";instance=" + sqlInstanceName + ";databaseName=" + database;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;

5.2- Một số rắc rối và cách khắc phục

Trong một số tình huống kết nối vào SQLServer ​và bị lỗi:

?
1
2 com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host
3 localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the
4 connection properties. Make sure that an instance of SQL Server is running on the host
5 and accepting TCP/IP connections at the port. Make sure that TCP connections to the
6 port are not blocked by a firewall.".
7
8
at
9
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerExc
1
eption.java:190)
0
1
1 at
1 com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServ
2 erException(SQLServerException.java:241)

at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)

at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)

at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnectio
n.java:1309)

at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:99
1)

at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:
827)

at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)

at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)

...

Lỗi trên có thể do bạn chưa ​Enable dịch vụ ​TCP/IP của ​SQLServer​. Bạn có thể tham khảo thêm mục
cấu hình SQLServer​ trong tài liệu "Hướng dẫn cài đặt và cấu hình SQLServer Express ..." tại:

● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014

Trường hợp tiếp tục bị lỗi:

1
2 Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The
3 TCP/IP connection to the host tran-vmware, port 1433 has failed. Error: "Connection
4 refused: connect. Verify the connection properties. Make sure that an instance of SQL
5 Server is running on the host and accepting TCP/IP connections at the port. Make sure
6 that TCP connections to the port are not blocked by a firewall.".
7
8
at
9
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerExc
1
eption.java:190)
0
1
1 at
1 com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServ
2 erException(SQLServerException.java:241)

at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)

at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)

at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnectio
n.java:1309)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:99
1)

at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:
827)

at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)

at java.sql.DriverManager.getConnection(DriverManager.java:571)

at java.sql.DriverManager.getConnection(DriverManager.java:215)

...

Đây là một lỗi khó chịu, vì khi chuyển sang sử dụng thư viện JTDS ​không bị lỗi này.

● TODO
● You should use JTDS

6- Thư viện điều khiển Database MongoDB


Thư viện điều khiển cơ sở dữ liệu MongoDB​ bạn có thể download tại:

● https://github.com/mongodb/mongo-java-driver/downloads
Bạn cũng có thể download tại Maven Repository​:

● http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Database sử dụng trong tài liệu này

2- ​JDBC là gì?

3- ​Java kết nối với database dựa trên nguyên tắc nào?

4- ​Download một số các driver quan trọng

5- ​Tạo project để bắt đầu ví dụ với JDBC

6- ​Connection

7- ​Sử dụng JDBC API truy vấn dữ liệu

8- ​Các kiểu ResultSet

9- ​Ví dụ Insert dữ liệu

10- ​PreparedStatement

11- ​CallableStatement

​ iều khiển giao dịch (Transaction)


12- Đ

​ hực thi một lô lệnh (Batch)


13- T

Java cơ bản

Hướng dẫn sử dụng Java JDBC kết nối cơ sở dữ liệu

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net
​ atabase sử dụng trong tài liệu này
1- D

2- ​JDBC là gì?

3- J​ ava kết nối với database dựa trên nguyên tắc nào?

​ ownload một số các driver quan trọng


4- D

​ ạo project để bắt đầu ví dụ với JDBC


5- T

6- ​Connection

​ ử dụng JDBC API truy vấn dữ liệu


7- S

​ ác kiểu ResultSet
8- C

​ í dụ Insert dữ liệu
9- V

10- ​PreparedStatement

11- ​CallableStatement

​ iều khiển giao dịch (Transaction)


12- Đ

​ hực thi một lô lệnh (Batch)


13- T

1- Database sử dụng trong tài liệu này


Tài liệu hướng dẫn này sẽ hướng dẫn các sử dụng Java kết nối vào database. Database được sử
dụng làm mẫu trong tài liệu này là "simplehr"​. Bạn có thể xem các script tạo database tại:

● Cơ sở dữ liệu mẫu

2- JDBC là gì?
JDBC (Java Database Connectivity) là một API tiêu chuẩn dùng để tương tác với các loại cơ sở dữ
liệu quan hệ. ​JDBC có một tập hợp các class và các Interface dùng cho ứng dụng ​Java có thể nói
chuyện với các cơ sở dữ liệu.

Các thành phần của JDBC Api về cơ bản bao gồm:

1. DriverManager​:
○ Là một class, nó dùng để quản lý danh sách các Driver ​(database drivers).
2. Driver​:
○ Là một Interface, nó dùng để liên kết các liên lạc với cơ sở dữ liệu, điều khiển các liên
lạc với database. Một khi Driver được tải lên, lập trình viên không cần phải gọi nó một
cách cụ thể.
3. Connection :​
○ Là một Interface với tất cả các method cho việc liên lạc với database. Nó mô tả nội dung
liên lạc. tất cả các thông tin liên lạc với cơ sở dữ liệu là thông qua chỉ có đối tượng
Connection​.
4. Statement :​
○ Là một Interface, gói gọn một câu lệnh SQL gửi tới cơ sở dữ liệu được phân tích, tổng
hợp, lập kế hoạch và thực hiện.
5. ResultSet:​
○ ResultSet​ đại diện cho tập hợp các bản ghi lấy do thực hiện truy vấn.

3- Java kết nối với database dựa trên nguyên tắc nào?
Java​ sử dụng JDBC​ để làm việc với các cơ sở dữ liệu.
Ví dụ bạn làm việc với cơ sở dữ liệu Oracle từ Java bạn cần phải có Driver (Đó là class điều khiển
việc kết nối với loại cơ sở dữ liệu bạn muốn). Trong ​JDBC API chúng ta có ​java.sql.Driver,​ nó chỉ là
một interface, và nó có sẵn trong ​JDK​. Như vậy bạn phải download thư viện ​Driver ứ ​ ng với loại
Database mà bạn mong muốn.

● Chẳng hạn với Oracle ​thì class thi hành Interface ​java.sql.Driver​ đó là:
oracle.jdbc.driver.OracleDriver

java.sql.DriverManager​ là một class trong JDBC API​. Nó làm nhiệm vụ quản lý các Driver.

Bạn hãy xem hình minh họa dưới đây:


Chúng ta có 2 cách để làm việc với một loại cơ sở dữ liệu cụ thể nào đó.

● Cách 1: Bạn hãy cung cấp thư viện Driver điều khiển loại cơ sở dữ liệu đó, đây là cách trực
tiếp. Nếu bạn dùng DB oracle (hoặc DB khác) bạn phải download thư viện dành cho loại DB
này.
● Cách 2: Khai báo một "ODBC DataSource",​ và sử dụng cầu nối JDBC-ODBC​ để kết nối với
"ODBC DataSource"​ kia. Cầu nối JDBC-ODBC​ là thứ có sẵn trong JDBC API​.

Câu hỏi của chúng ta là "ODBC DataSource"​ là cái gì?


ODBC - Open Database Connectivity​: Nó chính là một bộ thư viện mở, có khả năng kết nối với hầu
hết các loại cơ sở dữ liệu khác nhau, và nó miễn phí. Được cung cấp bởi Microsoft​.

ODBC DataSource​: Trên hệ điều hành Window bạn có thể khai báo một kết nối ODBC tới một loại
DB nào đó. Và như vậy chúng ta có một nguồn dữ liệu (Data Source).

Trong ​JDBC API​, đã xây dựng sẵn một cầu nối ​JDBC-ODBC để ​JDBC có thể nói chuyện được với
ODBC Data Source​.

Về tốc độ, cách 1 sẽ nhanh hơn cách 2, vì cách 2 phải sử dụng tới cầu nối.

4- Download một số các driver quan trọng


Trong trường hợp nếu bạn không muốn sử dụng ​JDBC-ODBC​, bạn có thể sử dụng cách trực tiếp kết
nối vào Database, trong trường hợp đó cần phải download Driver ứng với mỗi loại DB này. Tại đây tôi
hướng dẫn download một loại Driver cho các Database thông dụng:

● Oracle
● MySQL
● SQLServer
● ....

Bạn có thể xem hướng dẫn tại:

● Thư viện điều khiển các loại cơ sở dữ liệu khác nhau trong Java

Kết quả chúng ta có một vài file:


5- Tạo project để bắt đầu ví dụ với JDBC
Tạo mới project JavaJdbcTutorial​:

Tạo thư mục ​libs trên project và copy các thư viện kết nối trực tiếp các loại database ​Oracle, MySQL,
SQLServer mà bạn vừa download được ở trên vào. Bạn có thể copy hết hoặc một trong các thư viện
đó, theo loại DB mà bạn sử dụng.

Chú ý: Bạn chỉ cần download một Driver ứng với loại Database mà bạn quen thuộc. Cơ sở dữ liệu
dùng làm ví dụ trong tài liệu này bạn có thể lấy tại:

● Cơ sở dữ liệu mẫu
Nhấn phải vào Project chọn Properties:
Giờ thì bạn có thể sẵn sàng làm việc với một trong các Database ( Oracle​, ​MySQL​, ​SQL Server​)

6- Connection
Trong tài liệu hướng dẫn này tôi sẽ hướng dẫn các kết nối vào cả 3 loại database:

● MySQL
● SQLServer
● Oracle

​ ào mà bạn quen thuộc.


Trong khi thực hành, bạn chỉ cần làm việc với một loại DB n
​ ể lấy ra đối tượng Connection k​ ết nối với Database.
Chúng ta tạo class ConnectionUtils đ

ConnectionUtils.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11
12
13
public class ConnectionUtils {
14
15
16
17
18 public static Connection getMyConnection() throws SQLException,
19
20
ClassNotFoundException {
21
22
23 // Sử dụng Oracle.
24
25 // Bạn có thể thay thế bởi Database nào đó.
26
27
return OracleConnUtils.getOracleConnection();
28
29
30 }
31

//

// Test Connection ...

//
public static void main(String[] args) throws SQLException,

ClassNotFoundException {

System.out.println("Get connection ... ");

// Lấy ra đối tượng Connection kết nối vào database.

Connection conn = ConnectionUtils.getMyConnection();

System.out.println("Get connection " + conn);

System.out.println("Done!");

OracleConnUtils.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class OracleConnUtils {
17
18
19
20
// Kết nối vào ORACLE.
21
22
23 public static Connection getOracleConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String hostName = "localhost";
28
29
30 String sid = "db11g";
31
32 String userName = "simplehr";
33
34
String password = "simplehr";
35
36
37
38
return getOracleConnection(hostName, sid, userName, password);
}

public static Connection getOracleConnection(String hostName, String sid,

String userName, String password) throws ClassNotFoundException,

SQLException {

// Khai báo class Driver cho DB Oracle

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.

Class.forName("oracle.jdbc.driver.OracleDriver");

// Cấu trúc URL Connection dành cho Oracle

// Ví dụ: jdbc:oracle:thin:@localhost:1521:db11g

String connectionURL = "jdbc:oracle:thin:@" + hostName + ":1521:" + sid;

Connection conn = DriverManager.getConnection(connectionURL, userName,


password);

return conn;

MySQLConnUtils.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class MySQLConnUtils {
17
18
19
20
// Kết nối vào MySQL.
21
22
23 public static Connection getMySQLConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String hostName = "localhost";
28
29
30
31
32 String dbName = "simplehr";
33
34
String userName = "root";
35
36
37 String password = "1234";
38
return getMySQLConnection(hostName, dbName, userName, password);

public static Connection getMySQLConnection(String hostName, String dbName,

String userName, String password) throws SQLException,

ClassNotFoundException {

// Khai báo class Driver cho DB MySQL

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.

Class.forName("com.mysql.jdbc.Driver");

// Cấu trúc URL Connection dành cho Oracle

// Ví dụ: jdbc:mysql://localhost:3306/simplehr

String connectionURL = "jdbc:mysql://" + hostName + ":3306/" + dbName;

Connection conn = DriverManager.getConnection(connectionURL, userName,


password);

return conn;

SQLServerConnUtils_JTDS.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class SQLServerConnUtils_JTDS {
17
18
19
20
21
22
23 // Kết nối vào SQLServer.
24
25 // (Sử dụng thư viện điều khiển JTDS)
26
27
public static Connection getSQLServerConnection()
28
29
30 throws SQLException, ClassNotFoundException {
31
32 String hostName = "localhost";
33
34
String sqlInstanceName = "SQLEXPRESS";
35
36
37 String database = "simplehr";
38
39 String userName = "sa";
40
41
42
43 String password = "1234";
44
45
46
47
return getSQLServerConnection(hostName, sqlInstanceName, database,

userName, password);

// Trường hợp sử dụng SQLServer.

// Và thư viện JTDS.

public static Connection getSQLServerConnection(String hostName,

String sqlInstanceName, String database, String userName,

String password) throws ClassNotFoundException, SQLException {

// Khai báo class Driver cho DB SQLServer

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.

Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Cấu trúc URL Connection dành cho SQLServer

// Ví dụ:

// jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS

String connectionURL = "jdbc:jtds:sqlserver://" + hostName + ":1433/"

+ database + ";instance=" + sqlInstanceName;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;

SQLServerConnUtils_SQLJDBC.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class SQLServerConnUtils_SQLJDBC {
17
18
19
20
// Kết nối vào SQLServer.
21
22
23 // (Sử dụng thư viện điều khiển SQLJDBC)
24
25 public static Connection getSQLServerConnection()
26
27
throws SQLException, ClassNotFoundException {
28
29
30 String hostName = "localhost";
31
32 String sqlInstanceName = "SQLEXPRESS";
33
34
String database = "simplehr";
35
36
37 String userName = "sa";
38
39 String password = "1234";
40
41
42
43
44
45 return getSQLServerConnection(hostName, sqlInstanceName,

database, userName, password);

// Trường hợp sử dụng SQLServer.

// Và thư viện SQLJDBC.

public static Connection getSQLServerConnection(String hostName,

String sqlInstanceName, String database, String userName,

String password) throws ClassNotFoundException, SQLException {

// Khai báo class Driver cho DB SQLServer

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Cấu trúc URL Connection dành cho SQLServer


// Ví dụ:

// jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr

String connectionURL = "jdbc:sqlserver://" + hostName + ":1433"

+ ";instance=" + sqlInstanceName + ";databaseName=" + database;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;

ODBCConnUtils.java

?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class ODBCConnUtils {
17
18
19
20
// Lấy ra kết nối vào ODBC Data Source có tên "simplehr-ds".
21
22
23 public static Connection getJdbcOdbcConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String odbcDataSourceName = "simplehr-ds";
28
29
30 String userName = "simplehr";
31
32 String password = "simplehr";
33
34
return getJdbcOdbcConnection(odbcDataSourceName, userName, password);
35

}
public static Connection getJdbcOdbcConnection(String odbcDataSourceName,

String userName, String password) throws SQLException,

ClassNotFoundException {

// Khai báo class Driver (Cầu nối Jdbc-Odbc)

// Việc này cần thiết với Java 5

// Java6 tự động tìm kiếm Driver thích hợp.

// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Cấu trúc URL Connection dành cho JDBC-ODBC

String connectionURL = "jdbc:odbc:" + odbcDataSourceName;

Connection conn = DriverManager.getConnection(connectionURL, userName,

password);

return conn;

}
}

Bạn có thể thay đổi Class ​ConnectionUtils ​để sử dụng kết nối tới một Database nào đó quen thuộc.
Và chạy class này để test kết nối.

Chú ý: Nếu bạn sử dụng ​MySQL h ​ oặc S


​ QL Server mặc định 2 Database này chặn không cho phép
kết nối vào nó từ một IP khác. Bạn cần cấu hình để cho phép điều này. Bạn có thể xem hướng dẫn
trong tài liệu cài đặt và cấu hình MySQL​, ​SQL Server t​ rên ​o7planning​.

Cài đặt và cấu hình MySQL Community​:

● Hướng dẫn cài đặt và cấu hình MySQL Community

Cài đặt và cấu hình SQL Server:

● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014

7- Sử dụng JDBC API truy vấn dữ liệu


Đây là hình ảnh dữ liệu trong bảng ​Employee​. Chúng ta sẽ xem cách ​Java l​ ấy ra dữ liệu thế nào
thông qua một ví dụ:
ResultSet ​là một đối tượng Java, nó được trả về khi bạn truy vấn (query) dữ liệu. Sử dụng
ResultSet.next() để di chuyển con trỏ tới các bản ghi tiếp theo (Di chuyển dòng). Tại một bản ghi nào
đó bạn sử dụng các method ​ResultSet.getXxx() để lấy ra các giá trị tại các cột. Các cột được đánh
với thứ tự 1,2,3,...

** ResultSet **

1
2 public String getString(int columnIndex) throws SQLException;
3
4 public boolean getBoolean(int columnIndex) throws SQLException;
5
6
public int getInt(int columnIndex) throws SQLException;
7
8
9 public double getDouble(int columnIndex) throws SQLException;
10
11
12
13
...

public String getString(String columnLabel) throws SQLException;


public boolean getBoolean(String columnLabel) throws SQLException;

public int getInt(String columnLabel) throws SQLException;

public double getDouble(String columnLabel) throws SQLException;

....

Ví dụ minh họa:

QueryDataExample.java

?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.ResultSet;
10
11 import java.sql.SQLException;
12
13
import java.sql.Statement;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class QueryDataExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32
33
34
// Lấy ra đối tượng Connection kết nối vào DB.
35
36
37 Connection connection = ConnectionUtils.getMyConnection();
38
39
40
// Tạo đối tượng Statement.

Statement statement = connection.createStatement();

String sql = "Select Emp_Id, Emp_No, Emp_Name from Employee";

// Thực thi câu lệnh SQL trả về đối tượng ResultSet.

ResultSet rs = statement.executeQuery(sql);

// Duyệt trên kết quả trả về.

while (rs.next()) {// Di chuyển con trỏ xuống bản ghi kế tiếp.

int empId = rs.getInt(1);

String empNo = rs.getString(2);

String empName = rs.getString("Emp_Name");

System.out.println("--------------------");

System.out.println("EmpId:" + empId);

System.out.println("EmpNo:" + empNo);

System.out.println("EmpName:" + empName);
}

// Đóng kết nối

connection.close();

Kết quả chạy ví dụ:

8- Các kiểu ResultSet


Bạn đã làm quen với ​ResultSet ​với các ví dụ phía trên. Mặc định các ​ResultSet ​khi duyệt dữ liệu chỉ
có thể chạy từ trên xuống dưới, từ trái sang phải. Điều đó có nghĩa là với các ​ResultSet ​mặc định bạn
không thể gọi:

● ResultSet.previous()​ : Lùi lại một bản ghi.


● Trên cùng một bản ghi không thể gọi ResultSet.getXxx(4)​ rồi mới gọi ResultSet.getXxx(2)​.

Việc cố tình gọi sẽ bị một Exception​.

?
1
2 public Statement createStatement(int resultSetType, int resultSetConcurrency)
3
4 throws SQLException;
5
6
7
8
9 // Ví dụ:

Statement statement = connection.createStatement(

ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

// ResultSet có thể cuộn (tiến lùi, sang trái sang phải).

ResultSet rs = statement.executeQuery(sql);

resultSetType Ý nghĩa

TYPE_FORWARD_ON - ​ResultSet c​ hỉ cho phép duyệt từ trên xuống dưới, từ trái sang phải. Đây
LY là kiểu mặc định của các ResultSet​.

TYPE_SCROLL_INSE - ​ResultSet c​ ho phép cuộn tiến lùi, sang trái, sang phải, nhưng không
NSITIVE nhạy với các sự thay đổi dữ liệu dưới DB. Nghĩa là trong quá trình duyệt
qua một bản ghi và lúc nào đó duyệt lại bản ghi đó, nó không lấy các dữ
liệu mới nhất của bản ghi mà có thể bị ai đó thay đổi.

TYPE_SCROLL_SENS - ​ResultSet c​ ho phép cuộn tiến lùi, sang trái, sang phải, và nhạy cảm với
ITIVE sự thay đổi dữ liệu.

resultSetConcurr Ý nghĩa
ency

CONCUR_READ_ - Khi duyệt dữ liệu với các ResultSet ​kiểu này bạn chỉ có thể đọc dữ liệu.
ONLY
CONCUR_UPDAT - Khi duyệt dữ liệu với các ResultSet ​kiểu này bạn chỉ có thể thay đổi dữ liệu
ABLE tại nơi con trỏ đứng, ví dụ update giá trị cột nào đó.

ScrollableResultSetExample.java

?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.ResultSet;
10
11 import java.sql.SQLException;
12
13
import java.sql.Statement;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class ScrollableResultSetExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32
33
34
// Lấy ra đối tượng Connection kết nối tới DB.
35
36
37 Connection connection = ConnectionUtils.getMyConnection();
38
39
40
41
42
43 // Tạo một đối tượng Statement
44
45 // Có thể cuộn dữ liệu, nhưng không nhậy với các thay đổi dưới DB.
46
47
// Con trỏ chỉ có khả năng đọc, không có khả năng update dữ liệu trong quá trình
48
duyệt.
49
50
51 Statement statement = connection.createStatement(
52
53 ResultSet.TYPE_SCROLL_INSENSITIVE,
54 ResultSet.CONCUR_READ_ONLY);
55
56
57
58
59 String sql = "Select Emp_Id, Emp_No, Emp_Name from Employee";
60
61
62
63
// Thực thi câu lệnh SQL trả về đối tượng ResultSet.
64
65
66 ResultSet rs = statement.executeQuery(sql);
67
68
69
70
71
72
73 // Nhẩy con trỏ tới cuối

boolean last = rs.last();

System.out.println("last : "+ last);


if(last) {

// Ghi ra thông tin bản ghi cuối.

System.out.println("EmpId:" + rs.getInt(1));

System.out.println("EmpNo:" + rs.getString(2));

System.out.println("EmpName:" + rs.getString(3));

System.out.println("--------------------");

// Nhẩy con trỏ lùi lại lần 1

boolean previous =rs.previous();

System.out.println("Previous 1: "+ previous);

// Nhẩy lùi con trỏ lần 2

previous =rs.previous();
System.out.println("Previous 2: "+ previous);

// Duyệt trên kết quả trả về.

while (rs.next()) {

// Lấy dữ liệu cột 2

String empNo = rs.getString(2);

// Rồi mới lấy dữ liệu cột 1.

int empId = rs.getInt(1);

String empName = rs.getString("Emp_Name");

System.out.println("--------------------");

System.out.println("EmpId:" + empId);

System.out.println("EmpNo:" + empNo);

System.out.println("EmpName:" + empName);

}
// Đóng kết nối

connection.close();

Kết quả chạy ví dụ:

9- Ví dụ Insert dữ liệu

InsertDataExample.java

?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11 import java.sql.Statement;
12
13
14
15
16 import org.o7planning.tutorial.jdbc.ConnectionUtils;
17
18
19
20
public class InsertDataExample {
21
22
23
24
25 public static void main(String[] args) throws ClassNotFoundException,
26
27
SQLException {
28
29
30

// Lấy ra kết nối tới cơ sở dữ liệu.

Connection connection = ConnectionUtils.getMyConnection();

Statement statement = connection.createStatement();


String sql = "Insert into Salary_Grade (Grade, High_Salary, Low_Salary) "

+ " values (2, 20000, 10000) ";

// Thực thi câu lệnh.

// executeUpdate(String) sử dụng cho các loại lệnh Insert,Update,Delete.

int rowCount = statement.executeUpdate(sql);

// In ra số dòng được trèn vào bởi câu lệnh trên.

System.out.println("Row Count affected = " + rowCount);

Kết quả chạy ví dụ:


10- PreparedStatement
PreparedStatement​ là một Interface con của Statement.​

PreparedStatement ​sử dụng để chuẩn bị trước các câu lệnh ​SQL​, và tái sử dụng nhiều lần, giúp cho
chương trình thực hiện nhanh hơn.

PrepareStatementExample.java

?
1
2 package org.o7planning.tutorial.jdbc.pareparedstatement;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class PrepareStatementExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32 // Lấy ra kết nối tới cơ sở dữ liệu.
33
34
Connection connection = ConnectionUtils.getMyConnection();
35
36
37
38
39 // Tạo một câu SQL có 2 tham số (?)
40
41
42
43 String sql = "Select emp.Emp_Id, emp.Emp_No, emp.Emp_Name, emp.Dept_Id
44 from Employee emp "
45
46 + " where emp.Emp_Name like ? and emp.Dept_Id = ? ";
47
48
49
50
51 // Tạo một đối tượng PreparedStatement.
52
53 PreparedStatement pstm = connection.prepareStatement(sql);
54
55
56

// Sét đặt giá trị tham số thứ nhất (Dấu ? thứ nhất)

pstm.setString(1, "%S");

// Sét đặt giá trị tham số thứ hai (Dấu ? thứ hai)

pstm.setInt(2, 20);

ResultSet rs = pstm.executeQuery();

while (rs.next()) {

System.out.println(" ---- ");

System.out.println("EmpId : " + rs.getInt("Emp_Id"));

System.out.println("EmpNo : " + rs.getString(2));


System.out.println("EmpName : " + rs.getString("Emp_Name"));

System.out.println();

System.out.println("Set other parameters ..");

// Tái sử dụng PreparedStatement.

// Sét đặt các tham số khác.

pstm.setString(1, "KI%");

pstm.setInt(2,10);

// Thực thi câu lệnh truy vấn.

rs = pstm.executeQuery();

while (rs.next()) {

System.out.println(" ---- ");

System.out.println("EmpId : " + rs.getInt("Emp_Id"));


System.out.println("EmpNo : " + rs.getString(2));

System.out.println("EmpName : " + rs.getString("Emp_Name"));

Kết quả chạy ví dụ:

11- CallableStatement
CallableStatement​ được xây dựng để gọi một thủ tục (procedure) hoặc hàm (function) của SQL​.

1
2 // Câu lệnh gọi thủ tục SQL trên Java
3
4 String sql = "{call procedure_name(?,?,?)}";
5
// Câu lệnh gọi một hàm SQL trên Java

String sql ="{? = call function_name(?,?,?)}";

Để làm ví dụ với ​CallableStatement chúng ta cần một hàm hoặc một thủ tục trong DB. Với ​Oracle​,
MySQL​ hoặc SQLServer b ​ ạn có thể tạo nhanh một thủ tục như dưới đây:

● ORACLE

Get_Employee_Info

1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 Create Or Replace Procedure Get_Employee_Info(p_Emp_Id Integer
12
13
,v_Emp_No Out Varchar2
14
15
16 ,v_First_Name Out Varchar2

,v_Last_Name Out Varchar2

,v_Hire_Date Out Date) Is

Begin

v_Emp_No := 'E' || p_Emp_Id;

--
v_First_Name := 'Michael';

v_Last_Name := 'Smith';

v_Hire_Date := Sysdate;

End Get_Employee_Info;
● MySQL

Get_Employee_Info

1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 CREATE PROCEDURE get_Employee_Info(p_Emp_ID Integer,
12
13
out v_Emp_No Varchar(50) ,
14
15
16 out v_First_Name Varchar(50) ,

Out v_Last_name Varchar(50) ,

Out v_Hire_date Date)

BEGIN

set v_Emp_No = concat( 'E' , Cast(p_Emp_Id as char(15)) );


--

set v_First_Name = 'Michael';

set v_Last_Name = 'Smith';

set v_Hire_date = curdate();

END
● SQL Server

Get_Employee_Info

1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 CREATE PROCEDURE Get_Employee_Info
12
13
@p_Emp_Id Integer ,
14
15
16 @v_Emp_No Varchar(50) OUTPUT,
17
18 @v_First_Name Varchar(50) OUTPUT,

@v_Last_Name Varchar(50) OUTPUT,

@v_Hire_DateDate OUTPUT
AS

BEGIN

set @v_Emp_No = 'E' + CAST( @p_Emp_Id as varchar) ;

--

set @v_First_Name = 'Michael';

set @v_Last_Name = 'Smith';

set @v_Hire_date = getdate();

END

CallableStatementExample.java

?
1
2 package org.o7planning.tutorial.jdbc.callablestatement;
3
4
5
6
import java.sql.CallableStatement;
7
8
9 import java.sql.Connection;
10
11 import java.sql.Date;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class CallableStatementExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32 // Lấy ra kết nối tới cơ sở dữ liệu.
33
34
Connection connection = ConnectionUtils.getMyConnection();
35
36
37
38
39 // Câu lệnh gọi thủ tục (***)
40
41
42
43 String sql = "{call get_Employee_Info(?,?,?,?,?)}";
44
45
46
47
// Tạo một đối tượng CallableStatement.
48
49
50 CallableStatement cstm = connection.prepareCall(sql);
51
52
53
54
// Truyền tham số vào hàm (p_Emp_ID)
55
56
57 // (Là dấu chấm hỏi thứ 1 trên câu lệnh sql ***)

cstm.setInt(1, 10);

// Đăng ký nhận giá trị trả về tại dấu hỏi thứ 2

// (v_Emp_No)

cstm.registerOutParameter(2, java.sql.Types.VARCHAR);

// Đăng ký nhận giá trị trả về tại dấu hỏi thứ 3

// (v_First_Name)

cstm.registerOutParameter(3, java.sql.Types.VARCHAR);
// Đăng ký nhận giá trị trả về tại dấu hỏi thứ 4

// (v_Last_Name)

cstm.registerOutParameter(4, java.sql.Types.VARCHAR);

// Đăng ký nhận giá trị trả về tại dấu hỏi thứ 5

// (v_Hire_Date)

cstm.registerOutParameter(5, java.sql.Types.DATE);

// Thực thi câu lệnh

cstm.executeUpdate();

String empNo = cstm.getString(2);

String firstName = cstm.getString(3);

String lastName = cstm.getString(4);

Date hireDate = cstm.getDate(5);

System.out.println("Emp No: " + empNo);


System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Hire Date: " + hireDate);

Kết quả chạy ví dụ:

12- Điều khiển giao dịch (Transaction)


Giao dịch (Transaction) là một khái niệm quan trọng trong SQL​.

Ví dụ người A chuyển một khoản tiền 1000$ vào tài khoản người B như vậy trong Database diễn ra 2
quá trình:

● Trừ số dư tài khoản của người A đi 1000$


● Thêm vào số dư tài khoản của người B 1000$.

Và giao dịch được gọi là thành công nếu cả 2 bước kia thành công. Ngược lại chỉ cần 1 trong hai
bước hỏng là coi như giao dịch không thành công, phải rollback lại trạng thái ban đầu.

TransactionExample.java

?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11
12
13
import org.o7planning.tutorial.jdbc.ConnectionUtils;
14
15
16
17
18 public class TransactionExample {
19
20
21
22
23 private static void doJob1(Connection conn) {
24
25 // Làm gì đó tại đây.
26
27
// Insert update dữ liêu.
28
29
30 }
31
32
33
34
private static void doJob2(Connection conn) {
35
36
37 // Làm gì đó tại đây.
38
39 // Insert update dữ liêu.
40
41
42
43 }
44
45
46
47
public static void main(String[] args) throws ClassNotFoundException,
48
49
50 SQLException {

// Lấy ra kết nối tới cơ sở dữ liệu.

Connection connection = ConnectionUtils.getMyConnection();

// Sét đặt chế độ tự động Commit thành false

// Để tự quản lý việc commit trên chương trình.

connection.setAutoCommit(false);

try {

// Làm một việc gì đó liên quan tới DB.

doJob1(connection);

// Lamf nhiệm vụ thứ 2

doJob2(connection);
// Gọi method commit dữ liệu xuống DB.

connection.commit();

// Có vấn đề gì đó lỗi xẩy ra.

catch (Exception e) {

e.printStackTrace();

// Rollback dữ liệu

connection.rollback();

// Đóng Connection.

connection.close();

13- Thực thi một lô lệnh (Batch)

BatchExample.java
?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11 import java.sql.Statement;
12
13
14
15
16 import org.o7planning.tutorial.jdbc.ConnectionUtils;
17
18
19
20
public class BatchExample {
21
22
23
24
25 public static void main(String[] args) throws SQLException,
26
27
ClassNotFoundException {
28
29
30
31
32 Connection conn = ConnectionUtils.getMyConnection();
33
34
35
36
37 try {
38
39 // Create statement object
40
41
42
43 Statement stmt = conn.createStatement();
44
45
46
47
// Set auto-commit to false
48
49
50 conn.setAutoCommit(false);
51
52
53
54
// Create SQL statement
55
56
57 // Tạo câu lệnh Insert dữ liệu vào bảng Employee
58
59 String sql1 = "Update Employee emp set emp.Salary = emp.Salary + 100 "
60

+ " where emp.Dept_Id = 10 ";

// Add above SQL statement in the batch.

// Thêm câu lệnh SQL trên vào lô

stmt.addBatch(sql1);

// Create one more SQL statement

String sql2 = "Update Employee emp set emp.Salary = emp.Salary + 20 "

+ " where emp.Dept_Id = 20 ";

// Add above SQL statement in the batch.


// Thêm vào lô

stmt.addBatch(sql2);

// Create one more SQL statement

String sql3 = "Update Employee emp set emp.Salary = emp.Salary + 30 "

+ " where emp.Dept_Id = 30 ";

// Add above SQL statement in the batch.

// Thêm vào lô

stmt.addBatch(sql3);

// Create an int[] to hold returned values

int[] counts = stmt.executeBatch();

System.out.println("Sql1 count = " + counts[0]);

System.out.println("Sql2 count = " + counts[1]);

System.out.println("Sql3 count = " + counts[2]);


// Explicitly commit statements to apply changes

conn.commit();

} catch (Exception e) {

e.printStackTrace();

conn.rollback();

Kết quả chạy ví dụ:

BatchExample2.java

?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.Date;
10
11 import java.sql.PreparedStatement;
12
13
import java.sql.SQLException;
14
15
16 import java.util.UUID;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class BatchExample2 {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31
32 SQLException {
33
34
35
36
37 Connection conn = ConnectionUtils.getMyConnection();
38
39
40
41
42
43 try {
44
45 String sql = "Insert into Timekeeper(Timekeeper_Id, Date_Time, In_Out,
46 Emp_Id) "
47
48
+ " values (?,?,?,?) ";
49
50
51 // Create statement object
52
53 PreparedStatement stmt = conn.prepareStatement(sql);
54
55
56
57
58 // Set auto-commit to false

conn.setAutoCommit(false);

// Sét đặt các tham số.

stmt.setString(1, UUID.randomUUID().toString());

stmt.setDate(2, new Date(System.currentTimeMillis()));

stmt.setString(3, "I");

stmt.setInt(4, 7839);

// Thêm vào lô.

stmt.addBatch();
// Sét đặt các giá trị tham số khác

stmt.setString(1, UUID.randomUUID().toString());

stmt.setDate(2, new Date(System.currentTimeMillis()));

stmt.setString(3, "I");

stmt.setInt(4, 7566);

// Thêm vào lô.

stmt.addBatch();

// Create an int[] to hold returned values

int[] counts = stmt.executeBatch();

System.out.println("counts[0] = " + counts[0]);

System.out.println("counts[1] = " + counts[1]);

// Explicitly commit statements to apply changes

conn.commit();
} catch (Exception e) {

e.printStackTrace();

conn.rollback();

Kết quả chạy ví dụ:

Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Vấn đề

2- ​Lấy giá trị cột ID của bản ghi vừa được trèn

3- ​Lấy giá trị nhiều cột vừa được trèn

Java cơ bản

Lấy các giá trị của các cột tự động tăng khi Insert một bản ghi sử dụng
JDBC

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ ấn đề
1- V

​ ấy giá trị cột ID của bản ghi vừa được trèn


2- L

​ ấy giá trị nhiều cột vừa được trèn


3- L

1- Vấn đề
Trong một số cơ sở dữ liệu, Cột ​ID c​ ủa một bảng có thể là kiểu mà giá trị tự động tăng. Mỗi khi trèn
một bản ghi (record) vào bảng, giá trị của cột này sẽ được gán bởi database, bạn không thể chủ động
chỉ định một giá trị cho nó. Câu hỏi của bạn là trong trường hợp này làm thế nào để lấy được ​ID c​ ủa
bản ghi vừa được trèn vào.

Ngoài ra một số cột có thể không tham gia trong câu lệnh ​Insert ​của bạn, trong trường hợp đó giá trị
của nó được gán mặc định bởi database, bạn muốn lấy ra các giá trị này mà không cần thiết phải tạo
thêm một lệnh truy vấn.

PostGres
Trong ​PostGres​, cột có kiểu Serial s​ ẽ có giá trị tự động tăng bởi database.

** Employees (PostGres) **

1
2 CREATE TABLE Employees
3
4 (
5
6
ID serial NOT NULL,
7
8
9 Full_Name character varying(50) NOT NULL,

Gender character varying(1) default 'M' NOT NULL,

Hire_Date date NOT NULL,

PRIMARY KEY (ID)

);

MySQL

Trong ​MySQL​, để một cột có giá trị tự động tăng nó phải được gán thuộc tính (attribute)
"Auto_Increase"​.

** Employees (MySQL) **
?

1
2 CREATE TABLE Employees
3
4 (
5
6
ID Int Auto_Increase NOT NULL,
7
8
Full_Name Varchar(50) NOT NULL,

Gender Varchar(1) default 'M' NOT NULL,

Hire_Date date NOT NULL,

PRIMARY KEY (ID)

);

2- Lấy giá trị cột ID của bản ghi vừa được trèn
Khi bạn sử dụng ​JDBC đ ​ ể ​Insert m​ ột bản ghi vào database. Cột ​ID ​có thể không tham gia vào trong
câu lệnh ​Insert​. Vị trí của cột ​ID đ​ ược xác định bởi thiết kế của bảng đó. Cột đầu tiên có chỉ số 1, cột
thứ 2 có chỉ số 2,...
GeneratedIDValueExample.java

?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16 import java.sql.Statement;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class GeneratedIDValueExample {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31 SQLException {
32
33 // Lấy ra kết nối tới cơ sở dữ liệu.
34
35
Connection conn = ConnectionUtils.getMyConnection();
36
37
38
39
40 // Employees (id, full_name, gender, hire_date)
41
42
43 // ID: Auto Increase
44
45 String sql = "Insert into Employees " //

+ " (full_name, gender, hire_date) " //

+ " values " //

+ " (?, ?, ?)";

// Tạo một đối tượng PreparedStatement.

PreparedStatement pstm = conn.prepareStatement(sql,


Statement.RETURN_GENERATED_KEYS);

pstm.setString(1, "Tran");

pstm.setString(2, "M");

pstm.setDate(3, new java.sql.Date(System.currentTimeMillis()));

// Execute!

pstm.execute();

ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;

if (rs.next()) {

// Giá trị của ID (Vị trí 1 theo thiết kế của bảng)

idValue = rs.getInt(1);

System.out.println("ID value: " + idValue);

Chỉ số của cột ID của bảng có thể không phải là 1 (Tùy thuộc vào thiết kế của bảng). Trong trường
hợp này tốt nhất bạn truy cập giá trị của nó theo tên.

GeneratedIDValueExample2.java

?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16 import java.sql.Statement;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class GeneratedIDValueExample2 {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31 SQLException {
32
33
34
35
Connection conn = ConnectionUtils.getMyConnection();
36
37
38
39
40 // Employees (id, full_name, gender, hire_date)
41
42
43 // ID: Auto Increase
44
45 String sql = "Insert into Employees " //
46
47
+ " (full_name, gender, hire_date) " //

+ " values " //

+ " (?, ?, ?)";

// Tạo một đối tượng PreparedStatement.

PreparedStatement pstm = conn.prepareStatement(sql,


Statement.RETURN_GENERATED_KEYS);

pstm.setString(1, "Tran");

pstm.setString(2, "M");

pstm.setDate(3, new java.sql.Date(System.currentTimeMillis()));

// Execute!

pstm.execute();

ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;

if (rs.next()) {

// Giá trị của ID.

// Chú ý với một số DB, tên cột phân biệt chữ hoa chữ thường.

// (Ví dụ Postgres, tên cột luôn luôn là chữ thường).

idValue = rs.getInt("id");

System.out.println("ID value: " + idValue);

3- Lấy giá trị nhiều cột vừa được trèn


Một số cột có thể không tham gia vào câu lệnh ​Insert c​ ủa bạn. Giá trị của chúng được gán bởi
database, bạn có thể lấy ra giá trị của chúng mà không cần tạo thêm một câu lệnh truy vấn.
GetGeneratedValueExample2.java

?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class GetGeneratedValueExample2 {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
SQLException {
29
30
31
32
33 Connection conn = ConnectionUtils.getMyConnection();
34
35
36
37
38 // Employees (id, full_name, gender, hire_date)
39
40 // ID: Auto Increase
41
42
43 // gender: Default
44
45 String sql = "Insert into Employees " //
46
47
+ " (Full_Name, Hire_Date) " //
48

+ " values " //

+ " (?, ?)";

// Tạo một đối tượng PreparedStatement.

// Và đăng ký các tham số đầu ra theo tên ("id", "gender", "hire_date")

PreparedStatement pstm = conn.prepareStatement(sql, new String[] { "id",


"gender", "hire_date" });

pstm.setString(1, "Tran");

pstm.setDate(2, new java.sql.Date(System.currentTimeMillis()));

// Execute!

pstm.execute();

ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;

String gender = null;

java.sql.Date hireDate = null;

if (rs.next()) {

idValue = rs.getInt("ID");

gender = rs.getString("Gender");

hireDate = rs.getDate("Hire_Date");

System.out.println("ID value: " + idValue + " Gender: " + gender + ", Hidedate: " +
hireDate);

Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Đọc ghi file zip sử dụng java.util.zip

2- ​Đọc ghi file jar sử dụng java.util.jar

3- ​Xử lý file RAR

Java cơ bản

Hướng dẫn nén và giải nén trong Java

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ ọc ghi file zip sử dụng java.util.zip


1- Đ

​ ọc ghi file jar sử dụng java.util.jar


2- Đ

​ ử lý file RAR
3- X

1- Đọc ghi file zip sử dụng java.util.zip


Để xử lý các công việc liên quan tới nén và giải nén, ​JDK ​cung cấp cho bạn package ​java.util.zip với
một số class để làm việc này.

Đáng tiếc là thư viện này không thể đọc và giải nén các định dạng phổ biến khác như ​rar​, hoặc ​7zip​.
Để giải sử lý các định dạng ​rar, 7zip, .. bạn cần có một thư viện khác. Trong tài liệu này tôi có để cập
tới các thư viện để làm việc này.
Đây là hình ảnh một file zip​ được mở bằng công cụ Winrar​.

java.util.zip​ coi các file trong file zip là các ​ZipEntry​.


ListZipEntriesDemo.java

?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.FileInputStream;
7
8
9 import java.util.zip.ZipEntry;
10
11 import java.util.zip.ZipInputStream;
12
13
14
15
16 public class ListZipEntriesDemo {
17
18
19
20
public static void main(String[] args) {
21
22
23 String FILE_PATH = "C:/test/datas.zip";
24
25
26
27
ZipInputStream zipIs = null;
28
29
30 try {
31
32 // Tạo đối tượng ZipInputStream để đọc file zip.
33
34
zipIs = new ZipInputStream(new FileInputStream(FILE_PATH));
35
36
37
38
ZipEntry entry = null;
// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)

while ((entry = zipIs.getNextEntry()) != null) {

if (entry.isDirectory()) {

System.out.print("Directory: ");

} else {

System.out.print("File: ");

System.out.println(entry.getName());

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

zipIs.close();

} catch (Exception e) {

}
}

Kết quả chạy ví dụ:

Ví dụ giải nén file zip vào một thư mục nào đó:

UnZipDemo.java

?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileInputStream;
10
11 import java.io.FileOutputStream;
12
13
import java.util.zip.ZipEntry;
14
15
16 import java.util.zip.ZipInputStream;
17
18
19
20
public class UnZipDemo {
21
22
23
24
25 public static void main(String[] args) {
26
27
final String OUTPUT_FOLDER = "C:/output";
28
29
30 String FILE_PATH = "C:/test/datas.zip";
31
32
33
34
// Tạo thư mục Output nếu nó không tồn tại.
35
36
37 File folder = new File(OUTPUT_FOLDER);
38
39 if (!folder.exists()) {
40
41
42
43 folder.mkdirs();
44
45 }
46
47
// Tạo một buffer (Bộ đệm).
48
49
50 byte[] buffer = new byte[1024];
51
52
53
54
ZipInputStream zipIs = null;
55
56
57 try {
58
59 // Tạo đối tượng ZipInputStream để đọc file từ 1 đường dẫn (path).
60
61
zipIs = new ZipInputStream(new FileInputStream(FILE_PATH));
62

ZipEntry entry = null;

// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)

while ((entry = zipIs.getNextEntry()) != null) {

String entryName = entry.getName();

String outFileName = OUTPUT_FOLDER + File.separator + entryName;

System.out.println("Unzip: " + outFileName);


if (entry.isDirectory()) {

// Tạo các thư mục.

new File(outFileName).mkdirs();

} else {

// Tạo một Stream để ghi dữ liệu vào file.

FileOutputStream fos = new FileOutputStream(outFileName);

int len;

// Đọc dữ liệu trên Entry hiện tại.

while ((len = zipIs.read(buffer)) > 0) {

fos.write(buffer, 0, len);

fos.close();

}
} catch (Exception e) {

e.printStackTrace();

} finally {

try {

zipIs.close();

} catch (Exception e) {

Kết quả chạy ví dụ:

Nén thư mục


ZipDirectory.java

?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileInputStream;
10
11 import java.io.FileOutputStream;
12
13
import java.io.IOException;
14
15
16 import java.io.OutputStream;
17
18 import java.util.ArrayList;
19
20
import java.util.List;
21
22
23 import java.util.zip.ZipEntry;
24
25 import java.util.zip.ZipOutputStream;
26
27
28
29
30 public class ZipDirectory {
31
32
33
34
public ZipDirectory() {
35
36
37
38
39 }
40
41
42
43
44
45 // Phương thức dùng để nén một thư mục.
46
47
public void zipDirectory(File inputDir, File outputZipFile) {
48
49
50 // Tạo thư mục cha cho file đầu ra (output file).
51
52 outputZipFile.getParentFile().mkdirs();
53
54
55
56
57 String inputDirPath = inputDir.getAbsolutePath();
58
59 byte[] buffer = new byte[1024];
60
61
62
63
64 FileOutputStream fileOs = null;
65
66 ZipOutputStream zipOs = null;
67
68
try {
69
70
71
72
73 List<File> allFiles = this.listChildFiles(inputDir);
74
75
76
77
78 // Tạo đối tượng ZipOutputStream để ghi file zip.
79
80 fileOs = new FileOutputStream(outputZipFile);
81
82
83
84 //
85
86 zipOs = new ZipOutputStream(fileOs);
87
88
for (File file : allFiles) {
89
90
91 String filePath = file.getAbsolutePath();
92
93
94
95
System.out.println("Zipping " + filePath);
96
97
98 // entryName: is a relative path.

String entryName = filePath.substring(inputDirPath.length() + 1);

ZipEntry ze = new ZipEntry(entryName);

// Thêm entry vào file zip.

zipOs.putNextEntry(ze);

// Đọc dữ liệu của file và ghi vào ZipOutputStream.

FileInputStream fileIs = new FileInputStream(filePath);

int len;

while ((len = fileIs.read(buffer)) > 0) {


zipOs.write(buffer, 0, len);

fileIs.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

closeQuite(zipOs);

closeQuite(fileOs);

private void closeQuite(OutputStream out) {

try {

out.close();

} catch (Exception e) {
}

// Phương thức này trả về danh sách các file,

// bao gồm tất cả các file con, cháu,.. của thư mục đầu vào.

private List<File> listChildFiles(File dir) throws IOException {

List<File> allFiles = new ArrayList<File>();

File[] childFiles = dir.listFiles();

for (File file : childFiles) {

if (file.isFile()) {

allFiles.add(file);

} else {

List<File> files = this.listChildFiles(file);

allFiles.addAll(files);

}
return allFiles;

public static void main(String[] args) {

ZipDirectory zipDir = new ZipDirectory();

File inputDir = new File("C:/datas");

File outputZipFile = new File("C:/output/datas.zip");

zipDir.zipDirectory(inputDir, outputZipFile);

Kết quả chạy ví dụ:


2- Đọc ghi file jar sử dụng java.util.jar

Về cơ bản việc đọc ghi file jar k​ hông có gì khác biệt so với file Zip​.

​ ở rộng từ ZipInputStream ​hỗ trợ thêm tính năng đọc các thông tin
● JarInputStream m
MANIFEST​.
● JarOutputStream m​ ở rộng từ ZipOutputStream h ​ ỗ trợ thêm tính năng ghi thông tin
MANIFEST​.

Các file thư viện jar thông thường của java thường có thông tin MANIFEST ​rất đơn giản.

Ví dụ đây là một file ​MANIFEST.MF đóng gói trong file jar của 1 ứng dụng ​RAP ​có nhiều thông tin
hơn:

META-INF/MANIFEST.MF

?
1
2 Manifest-Version: 1.0
3
4 Bundle-ManifestVersion: 2
5
6
Bundle-Name: RAPWorkbenchTutorial
7
8
9 Bundle-SymbolicName: RAPWorkbenchTutorial;singleton:=true
10
11 Bundle-Version: 1.0.0.qualifier
12
13
Bundle-Activator: rapworkbenchtutorial.Activator
14
15
16 Require-Bundle: org.eclipse.rap.ui;bundle-version="2.3.0",
17
org.apache.felix.gogo.command;bundle-version="0.10.0",

org.apache.felix.gogo.runtime;bundle-version="0.10.0",

org.apache.felix.gogo.shell;bundle-version="0.10.0",

org.eclipse.equinox.console;bundle-version="1.1.0",

org.eclipse.equinox.http.jetty;bundle-version="3.0.200",

org.eclipse.equinox.ds;bundle-version="1.4.200",

org.eclipse.rap.rwt.osgi;bundle-version="2.3.0",

org.eclipse.rap.design.example;bundle-version="2.3.0"

Bundle-RequiredExecutionEnvironment: JavaSE-1.7

Bundle-ActivationPolicy: lazy

Ví dụ một file jar mở với Winrar​:


Các thực thể trong file jar được coi là các JarEntry​.

Một ví dụ đơn giản đọc thông tin ​MANIFEST ​của file jar. Dưới đây là hình ảnh nội dung của một file
Manifest ​đơn giản.
ReadJarFileDemo.java

?
1
2 package org.o7planning.tutorial.jar;
3
4
5
6
import java.io.FileInputStream;
7
8
9 import java.util.jar.Attributes;
10
11 import java.util.jar.JarEntry;
12
13
import java.util.jar.JarInputStream;
14
15
16 import java.util.jar.Manifest;
17
18
19
20
public class ReadJarFileDemo {
21
22
23
24
25 public static void main(String[] args) {
26
27
String FILE_PATH = "C:/DevPrograms/Java/jdk1.7.0_45/lib/dt.jar";
28
29
30
31
32 JarInputStream zipIs = null;
33
34
try {
35
36
37 // Tạo đối tượng JarInputStream để đọc file jar.
38
39 zipIs = new JarInputStream(new FileInputStream(FILE_PATH));
40
41
42
43
44
45 // Đọc thông tin Manifest:
46
47
Manifest manifest = zipIs.getManifest();
48
49
Attributes atts = manifest.getMainAttributes();

String version = atts.getValue("Manifest-Version");

String createdBy = atts.getValue("Created-By");

System.out.println("Manifest-Version:" + version);

System.out.println("Created-By:" + createdBy);

System.out.println("========================");

JarEntry entry = null;

// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)

while ((entry = zipIs.getNextJarEntry()) != null) {

if (entry.isDirectory()) {

System.out.print("Folder: ");

} else {

System.out.print("File: ");
}

System.out.println(entry.getName());

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

zipIs.close();

} catch (Exception e) {

Kết quả chạy ví dụ:


3- Xử lý file RAR
Để xử lý file ​RAR b
​ ạn cần một thư viện mã nguồn mở. Bạn có thể sử dụng một trong các thư viện
sau, được đánh giá tốt theo thứ tự giảm dần.

1. JUnRar​:
2. java-unrar

Trong tài liệu này tôi sẽ hướng dẫn bạn sử dụng ​JUnRar (Phiên bản tại thời điểm 9-2014 đang là
0.7)

● http://github.com/edmund-wagner/junrar
Download junrar:

● http://mvnrepository.com/artifact/com.github.junrar/junrar
Xem thêm các chuyên mục:

Java cơ bản
Mục lục

1- ​Java Reflection là gì ?

2- ​Một số class tham gia trong các ví dụ

3- ​Bắt đầu với một ví dụ đơn giản

4- ​Class

5- ​Cấu tử (Constructor)

6- ​Trường (Field)

7- ​Phương thức (method)

8- ​Các phương thức getter và setter

9- ​Truy cập vào các private method, field

10- ​Annotation

Java cơ bản

Hướng dẫn sử dụng Java Reflection

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

1- ​Java Reflection là gì ?

​ ột số class tham gia trong các ví dụ


2- M

​ ắt đầu với một ví dụ đơn giản


3- B
4- ​Class

​ ấu tử (Constructor)
5- C

​ rường (Field)
6- T

​ hương thức (method)


7- P

​ ác phương thức getter và setter


8- C

​ ruy cập vào các private method, field


9- T

10- ​Annotation

1- Java Reflection là gì ?
Java ​sử dụng từ ​"Java Reflection" để đặt tên cho một ​API quan trọng trong thư viện chuẩn của
Java​. Tại sao API ​này lại được đặt tên như vậy? Chúng hãy cùng phân tích ý nghĩa của việc này.

Reflection ​chính là một hình ảnh phản chiếu của một vật thể. Chẳng hạn hình ảnh của bạn trong một
tấm gương, hoặc ảnh phản xạ của một cái cây trên mặt hồ. Từ ​"Java Reflection" đơn giản là đang
ám chỉ một hình ảnh khác, một cách tiếp cận khác của Java​.

Java ​là một ngôn ngữ hướng đối tượng (Object-oriented), thông thường bạn cần tạo ra một đối tượng
và bạn có thể truy cập vào các trường (field), hoặc gọi phương thức (method) của đối tượng này
thông qua toán tử dấu chấm ( . )

Java Reflection giới thiệu một cách tiếp cận khác, bạn có thể truy cập vào một trường của một đối
tượng nếu bạn biết tên của trường đó. Hoặc bạn có thể gọi một phương thức của đối tượng nếu bạn
biết tên phương thức, các kiểu tham số của phương thức, và các giá trị tham số để truyền vào ...
Java Reflecion cho phép bạn đánh giá, sửa đổi cấu trúc và hành vi của một đối tượng tại thời gian
chạy (runtime) của chương trình. Đồng thời nó cho phép bạn truy cập vào các thành viên ​private
(private member) tại mọi nơi trong ứng dụng, điều này không được phép với cách tiếp cận truyền
thống.

1. Java t​ hông thường có thể được gọi là Java Introspection ​(Nội quan), chương trình có khả
năng đánh giá cấu trúc của một đối tượng tại thời gian chạy (Runtime).
2. Với Java Reflection​, chương trình có khả năng đánh giá cấu trúc của một đối tượng tại thời
gian chạy, sửa đổi cấu trúc và hành vi của đối tượng.

2- Một số class tham gia trong các ví dụ


Đây là một số class tham gia vào các ví dụ trong tài liệu này.

Animal.java
?

1
2 package org.o7planning.tutorial.beans;
3
4
5
6
public abstract class Animal {
7
8
9
10
11
12

public String getLocation() {

return "Earth";

public abstract int getNumberOfLegs() ;

Say.java

1
2 package org.o7planning.tutorial.beans;
3
4
5
6
public interface Say {
public String say();

Cat.java

?
1
2 package org.o7planning.tutorial.beans;
3
4
5
6
7
8
9 public class Cat extends Animal implements Say {
10
11
12
13
public static final String SAY = "Meo meo";
14
15
16 public static final int NUMBER_OF_LEGS = 4;
17
18
19
20
// Private field.
21
22
23 private String name;
24
25
26
27
// Private field
28
29
30 public int age;
31
32
33
34
public Cat() {
35
36
37
38
39 }
40
41
42
43
44
45 public Cat(String name) {
46
47
this.name = name;
48
49
50 this.age = 1;
51
52 }
53
54
55
56
57 public Cat(String name, int age) {
58
59 this.name = name;
60
61
this.age = age;
62

public String getName() {

return this.name;

// Private Method.

private void setName(String name) {


this.name = name;

public int getAge() {

return this.age;

public void setAge(int age) {

this.age = age;

/**

* Implements from interface Say.

*/

@Override

public String say() {

return SAY;
}

/**

* Implements from Animal.

*/

@Override

public int getNumberOfLegs() {

return NUMBER_OF_LEGS;

3- Bắt đầu với một ví dụ đơn giản


Đây là một ví dụ đơn giản lấy ra danh sách các method public của một class, bao gồm cả các method
thừa kế từ các class cha, và các interface.

ListMethod.java

?
1
2 package org.o7planning.tutorial.reflect.helloreflect;
3
4
5
6
import java.lang.reflect.Method;
7
8
9
10
11 public class ListMethod {
12
13
14
15
16 // Protected method
17
18 protected void info() {
19
20
21
22
23 }
24
25
26
27
public static void testMethod1() {
28
29
30
31
}

public void testMethod2() {


}

public static void main(String[] args) {

// Lấy ra danh sách các method public của class này

// Bao gồm các các method thừa kế từ class cha, hoặc các interface.

Method[] methods = ListMethod.class.getMethods();

for (Method method : methods) {

System.out.println("Method " + method.getName());

Kết quả chạy class:


4- Class
Một số method quan trọng trong Reflection ​liên quan tới Class​.

Ví dụ ghi ra các thông tin cơ bản của class như tên class, package, modifier, ..

ShowClassInfo.java

?
1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import java.lang.reflect.Modifier;
7
8
9
10
11 public final class ShowClassInfo {
12
13
14
15
16 public static void main(String[] args) {
17
18
19
20
// Lấy ra đối tượng 'Class' mô tả class ShowClassInfo
21
22
23 Class<ShowClassInfo> aClass = ShowClassInfo.class;
24
25
26
27
// Ghi ra tên class, bao gồm cả tên package.
28
29
30 System.out.println("Class Name= " + aClass.getName());
31
32
33
34
// Ghi ra tên đơn giản của Class
35
36
37 System.out.println("Simple Class Name= " + aClass.getSimpleName());
38
39
40
// Thông tin Package.

Package pkg = aClass.getPackage();

System.out.println("Package Name = " + pkg.getName());

// Modifier

int modifiers = aClass.getModifiers();

boolean isPublic = Modifier.isPublic(modifiers);

boolean isInterface = Modifier.isInterface(modifiers);

boolean isAbstract = Modifier.isAbstract(modifiers);

boolean isFinal = Modifier.isFinal(modifiers);

// true

System.out.println("Is Public? " + isPublic);

// true

System.out.println("Is Final? " + isFinal);

// false
System.out.println("Is Interface? " + isInterface);

// false

System.out.println("Is Abstract? " + isAbstract);

Kết quả chạy class

Ví dụ ghi ra thông tin của class Cat​, như tên class, và các Interface mà class này thi hành.

ShowClassCatInfo.java

?
1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import org.o7planning.tutorial.beans.Cat;
7
8
9
10
11 public class ShowClassCatInfo {
12
13
14
15
16 public static void main(String[] args) {
17
18
19
20
// Đối tượng Class mô tả class Cat.
21
22
23 Class<Cat> aClass = Cat.class;
24
25
26
27
// Tên class
28
29
System.out.println("Simple Class Name = " + aClass.getSimpleName());

// Lấy ra đối tượng class mô tả class cha của class Cat.

Class<?> aSuperClass = aClass.getSuperclass();


System.out.println("Simple Class Name of Super class = "

+ aSuperClass.getSimpleName());

// Lấy ra mảng các Class mô tả các Interface mà Cat thi hành.

Class<?>[] itfClasses = aClass.getInterfaces();

for (Class<?> itfClass : itfClasses) {

System.out.println("Interface: " + itfClass.getSimpleName());

Kết quả chạy class:

Ví dụ lấy ra thông tin các constructor, method, field của class (Chỉ public), bao gồm cả các public
method, public field, thừa kế từ các class cha, và các interace.
ShowMemberInfo.java

1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import java.lang.reflect.Constructor;
7
8
9 import java.lang.reflect.Field;
10
11 import java.lang.reflect.Method;
12
13
14
15
16 import org.o7planning.tutorial.beans.Cat;
17
18
19
20
public class ShowMemberInfo {
21
22
23
24
25 public static void main(String[] args) {
26
27
28
29
30 // Lấy ra đối tượng Class mô tả class Cat
31
32 Class<Cat> aClass = Cat.class;
33
34
35
36
37 // Lấy ra danh sách các cấu tử của Cat.
38
39
40 Constructor<?>[] constructors = aClass.getConstructors();
41
42
43
44
System.out.println(" ==== CONSTRUCTORs: ===== ");

for (Constructor<?> constructor : constructors) {

System.out.println("Constructor: " + constructor.getName());

// Lấy ra danh sách các method public của Cat

// Bao gồm cả các method thừa kế từ class cha và các interface

Method[] methods = aClass.getMethods();

System.out.println(" ==== METHODs: ====== ");

for (Method method : methods) {

System.out.println("Method: " + method.getName());

}
// Lấy ra danh sách các field public

// Kể các các public field thừa kế từ các class cha, và các interface

Field[] fields = aClass.getFields();

System.out.println(" ==== FIELDs: ====== ");

for (Field field : fields) {

System.out.println("Field: " + field.getName());

Kết quả
5- Cấu tử (Constructor)
Ví dụ lấy ra một cấu tử với (constructor) các tham số chỉ định trước. Và ghi ra thông tin về cấu tử
(constructor) này.

ConstructorExample.java

?
1
2 package org.o7planning.tutorial.reflect.constructor;
3
4
5
6
import java.lang.reflect.Constructor;
7
8
9 import java.lang.reflect.InvocationTargetException;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class ConstructorExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, InstantiationException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Lấy ra đối tượng Class mô tả class Cat
33
34
Class<Cat> aClass = Cat.class;
35
36
37
38
39 // Lấy ra cấu tử có tham số (String,int) của class Cat
Constructor<?> constructor = aClass.getConstructor(String.class,

int.class);

// Lấy ra thông tin kiểu tham số của cấu tử.

Class<?>[] paramClasses = constructor.getParameterTypes();

for (Class<?> paramClass : paramClasses) {

System.out.println("Param: " + paramClass.getSimpleName());

// Khởi tạo đối tượng Cat theo cách thông thường.

Cat tom = new Cat("Tom", 3);

System.out

.println("Cat 1: " + tom.getName() + ", age =" + tom.getAge());

// Khởi tạo đối tượng Cat theo cách của reflect.


Cat tom2 = (Cat) constructor.newInstance("Tom", 2);

System.out.println("Cat 2: " + tom.getName() + ", age ="

+ tom2.getAge());

Kết quả chạy class:

6- Trường (Field)
Ví dụ dưới đây lấy ra field​ với tên chỉ định sẵn.

FieldExample.java

?
1
2 package org.o7planning.tutorial.reflect.field;
3
4
5
6
import java.lang.reflect.Field;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class FieldExample {
17
18
19
20
public static void main(String[] args) throws NoSuchFieldException,
21
22
23 SecurityException, IllegalArgumentException, IllegalAccessException {
24
25
26
27
// Lấy ra đối tượng Class mô tả class Cat
28
29
30 Class<Cat> aClass = Cat.class;
31
32
33
34
// Lấy ra field có tên 'NUMBER_OF_LEGS':
35
36
37 Field field = aClass.getField("NUMBER_OF_LEGS");
38
39
// Ghi ra kiểu của Field

Class<?> fieldType = field.getType();

System.out.println("Field type: " + fieldType.getSimpleName());

Field ageField = aClass.getField("age");

Cat tom = new Cat("Tom", 5);

// Lấy ra giá trị của trường "age" theo cách của Reflect.

Integer age = (Integer) ageField.get(tom);

System.out.println("Age = " + age);

// Sét đặt giá trị mới cho trường "age".

ageField.set(tom, 7);

System.out.println("New Age = "+ tom.getAge());


}

Kết quả chạy class:

7- Phương thức (method)


Ví dụ lấy ra một method cho bởi tên, và các tham số chỉ định trước. Ghi ra thông tin về method này,
như kiểu trả về, danh sách các tham số,...

MethodExample.java

?
1
2 package org.o7planning.tutorial.reflect.method;
3
4
5
6
import java.lang.reflect.InvocationTargetException;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class MethodExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Lấy ra đối tượng Class mô tả class Cat
33
34
Class<Cat> aClass = Cat.class;
35
36
37
38
39 // Lấy ra đối tượng 'Method' mô tả method getAge()
40
41
42
Method getAgeMethod = aClass.getMethod("getAge");

// Kiểu trả về của method getAge

Class<?> returnType= getAgeMethod.getReturnType();

System.out.println("Return type of getAge: "+ returnType.getSimpleName());

Cat tom = new Cat("Tom", 7);

// Gọi method 'getAge' theo cách của Reflect

// Nó tương đương với gọi: tom.getAge()

int age = (int) getAgeMethod.invoke(tom);

System.out.println("Age = " + age);

// Lấy ra đối tượng 'Method' mô tả method setAge(int) của class Cat.

Method setAgeMethod = aClass.getMethod("setAge", int.class);


// Gọi method setAge(int) theo cách của Reflect.

// Nó tương đương với gọi: tom.setAge(5);

setAgeMethod.invoke(tom, 5);

System.out.println("New Age = " + tom.getAge());

Kết quả chạy class

8- Các phương thức getter và setter


Ví dụ dưới đây, liệt kê ra các phương thức public setter​, và các ​public getter c​ ủa class.

GetSetExample.java

?
1
2 package org.o7planning.tutorial.reflect.getset;
3
4
5
6
import java.lang.reflect.Method;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class GetSetExample {
17
18
19
20
// Method là getter nếu có tên bắt đầu bằng get, và không có tham số.
21
22
23 public static boolean isGetter(Method method) {
24
25 if (!method.getName().startsWith("get")) {
26
27
return false;
28
29
30 }
31
32 if (method.getParameterTypes().length != 0) {
33
34
return false;
35
36
37 }
38
39 if (void.class.equals(method.getReturnType())) {
40
41
42
43 return false;
44
45 }
46
47
return true;
48
49
50 }
51
52
53

// Method là setter nếu có tên bắt đầu bằng set, và chỉ có 1 tham số.

public static boolean isSetter(Method method) {

if (!method.getName().startsWith("set")) {

return false;

if (method.getParameterTypes().length != 1) {

return false;

return true;

}
public static void main(String[] args) {

// Lấy ra đối tượng Class mô tả class Cat

Class<Cat> aClass = Cat.class;

// Lấy ra danh sách các public method.

Method[] methods = aClass.getMethods();

for (Method method : methods) {

boolean isSetter = isSetter(method);

boolean isGetter = isGetter(method);

System.out.println("Method: " + method.getName());

System.out.println(" - Is Setter? " + isSetter);

System.out.println(" - Is Getter? " + isGetter);

}
}

Kết quả chạy chương trình:

?
1
2 Method: getName
3
4 - Is Setter? false
5
6
- Is Getter? true
7
8
9 Method: getNumberOfLegs
10
11 - Is Setter? false
12
13
- Is Getter? true
14
15
16 Method: getAge
17
18 - Is Setter? false
19
20
- Is Getter? true
21
22
23 Method: setAge
24
25 - Is Setter? true
26
27
- Is Getter? false
28
29
30 Method: say
31
32 - Is Setter? false
33
34
- Is Getter? false
35
36
37 Method: getLocation
38
39 - Is Setter? false
40
41
42
43 - Is Getter? true
44
45 Method: wait
46
47
- Is Setter? false

- Is Getter? false

Method: wait

- Is Setter? false

- Is Getter? false

Method: wait

- Is Setter? false

- Is Getter? false

Method: equals

- Is Setter? false

- Is Getter? false

Method: toString

- Is Setter? false

- Is Getter? false

Method: hashCode
- Is Setter? false

- Is Getter? false

Method: getClass

- Is Setter? false

- Is Getter? true

Method: notify

- Is Setter? false

- Is Getter? false

Method: notifyAll

- Is Setter? false

- Is Getter? false

9- Truy cập vào các private method, field

Bạn không thể truy cập vào các method hay field mà nó là ​private theo cách thông thường, quá trình
biên dịch java cũng không cho phép điều đó. Nhưng với Java Reflection​ điều đó hoàn toàn có thể.

AccessPrivateFieldExample.java

?
1
2 package org.o7planning.tutorial.reflect.privateaccess;
3
4
5
6
import java.lang.reflect.Field;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class AccessPrivateFieldExample {
17
18
19
20
public static void main(String[] args) throws IllegalArgumentException,
21
22
23 IllegalAccessException, NoSuchFieldException, SecurityException {
24
25
26
27
// Tạo một đối tượng Class mô tả class Cat.
28
29
30 Class<Cat> aClass = Cat.class;
31
32
33
34
// Class.getField(String) chỉ lấy được các trường public.
35
36
// Sử dụng Class.getDeclaredField(String):

// Lấy ra đối tượng Field mô tả trường name của class Cat.


// (Trường khi báo trong class này).

Field private_nameField = aClass.getDeclaredField("name");

// Cho phép để truy cập vào các trường private.

// Nếu không sẽ bị ngoại lệ IllegalAccessException

private_nameField.setAccessible(true);

Cat tom = new Cat("Tom");

String fieldValue = (String) private_nameField.get(tom);

System.out.println("Value field name = " + fieldValue);

// Sét đặt trường name giá trị mới.

private_nameField.set(tom, "Tom Cat");

System.out.println("New name = " + tom.getName());

}
}

Kết quả chạy class:

Tiếp theo ví dụ truy cập vào một private method.

AccessPrivateMethodExample.java

?
1
2 package org.o7planning.tutorial.reflect.privateaccess;
3
4
5
6
import java.lang.reflect.InvocationTargetException;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class AccessPrivateMethodExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Tạo một đối tượng Class mô tả class Cat.
33
34
Class<Cat> aClass = Cat.class;
35
36
37

// Class.getMethod(String) chỉ lấy được các method public.


// Sử dụng Class.getDeclaredMethod(String):

// Lấy ra đối tượng Method mô tả method setName(String) của class Cat.

// (Phương thức khai báo trong class).

Method private_setNameMethod = aClass.getDeclaredMethod("setName",

String.class);

// Cho phép để truy cập vào các method private.

// Nếu không sẽ bị ngoại lệ IllegalAccessException

private_setNameMethod.setAccessible(true);

Cat tom = new Cat("Tom");

// Gọi private method.

private_setNameMethod.invoke(tom, "Tom Cat");

System.out.println("New name = " + tom.getName());

}
}

Kết quả

10- Annotation

MyAnnotation.java

?
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.ElementType;
7
8
9 import java.lang.annotation.Retention;
10
11 import java.lang.annotation.RetentionPolicy;
12
13
import java.lang.annotation.Target;
14
15
16
17
18 // Annotation này có thể sử dụng tại thời điểm chạy (Runtime) của chương trình.

@Retention(RetentionPolicy.RUNTIME)

// Có thể dùng cho class,interface, method, field, parameter.

@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD,

ElementType.PARAMETER })

public @interface MyAnnotation {

String name();

String value() default "";


}

Một ví dụ Annotation với class:

ClassAnnotationExample.java

1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9
10
11 @MyAnnotation(name = "Table", value = "Employee")
12
13
public class ClassAnnotationExample {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 Class<?> aClass = ClassAnnotationExample.class;
24
25

// Lấy ra danh sách các Annotation của class.

Annotation[] annotations = aClass.getAnnotations();


for (Annotation ann : annotations) {

System.out.println("Annotation: " + ann.annotationType().getSimpleName());

// Hoặc lấy cụ thể.

Annotation ann = aClass.getAnnotation(MyAnnotation.class);

MyAnnotation myAnn = (MyAnnotation) ann;

System.out.println("Name = " + myAnn.name());

System.out.println("Value = " + myAnn.value());

Kết quả:

Một ví dụ Annotation với Field & Method:

FieldMethodAnnotationExample.java

?
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9 import java.lang.reflect.Field;
10
11 import java.lang.reflect.Method;
12
13
14
15
16 public class FieldMethodAnnotationExample {
17
18
19
20
@MyAnnotation(name = "My Field")
21
22
23 private int myField;
24
25
26
27
@MyAnnotation(name = "My Method", value = "My Method Value")
28
29
30 protected void myMethod(String str) {
31
32
33
34
}
35
36
37
38
39 public static void main(String[] args) throws NoSuchFieldException,
40
41
42
43 SecurityException, NoSuchMethodException {
44
45
46
47
Class<?> aClass = FieldMethodAnnotationExample.class;
48
49
50
51
52 //
53
54
System.out.println(" == FIELD == ");
55
56
57 Field field = aClass.getDeclaredField("myField");
58
59
60
61
// Lấy ra danh sách các Annotation của field.
62

Annotation[] fieldAnns = field.getAnnotations();

for (Annotation methodAnn : fieldAnns) {

System.out.println("Annotation: "

+ methodAnn.annotationType().getSimpleName());

// Lấy cụ thể.

Annotation fieldAnn = field.getAnnotation(MyAnnotation.class);


MyAnnotation myAnn1 = (MyAnnotation) fieldAnn;

System.out.println("Name = " + myAnn1.name());

System.out.println("Value = " + myAnn1.value());

// Tương tự với method ...

System.out.println(" == METHOD == ");

Method method = aClass.getDeclaredMethod("myMethod", String.class);

// Lấy ra danh sách các Annotation của method.

Annotation[] methodAnns = method.getAnnotations();

for (Annotation methodAnn : methodAnns) {

System.out.println("Annotation: "

+ methodAnn.annotationType().getSimpleName());
}

// Lấy cụ thể.

Annotation methodAnn = method.getAnnotation(MyAnnotation.class);

MyAnnotation myAnn2 = (MyAnnotation) methodAnn;

System.out.println("Name = " + myAnn2.name());

System.out.println("Value = " + myAnn2.value());

Kết quả chạy:

Ví dụ Annotation v​ ới tham số của method:

ParameterAnnotationExample.java
?

1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
public class ParameterAnnotationExample {
14
15
16
17
18 // Ví dụ một method có Annotation ở tham số.
19
20
protected void doSomething(int jobType,
21
22
23 @MyAnnotation(name = "Table", value = "Employee") String info) {
24
25
26
27
}
28
29
30
31
32 public static void main(String[] args) throws NoSuchMethodException,
33
34
SecurityException {
35
36
37
38
39 Class<?> aClass = ParameterAnnotationExample.class;
40
41
42
43
// Lấy ra đối tượng Method của method doSomething(int,String)

Method method = aClass.getDeclaredMethod("doSomething", int.class,

String.class);

// Lấy ra danh sách các Parameter của method.

Class<?>[] parameterTypes = method.getParameterTypes();

for (Class<?> parameterType : parameterTypes) {

System.out.println("Parametete Type: "

+ parameterType.getSimpleName());

System.out.println(" ---- ");

// Lấy ra mảng 2 chiều các Annotation trong các Parameter.

Annotation[][] annotationss = method.getParameterAnnotations();


// Lấy ra danh sách các Annotation của Parameter tại vị trí Index =1.

Annotation[] annotations = annotationss[1];

for (Annotation ann : annotations) {

System.out.println("Annotation: "

+ ann.annotationType().getSimpleName());

Xem thêm các chuyên mục:

Java cơ bản
Hướng dẫn gọi phương thức từ xa với Java RMI

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ iới thiệu
1- G

​ ạo project
2- T

​ hạy ứng dụng


3- C

1- Giới thiệu
RMI là một cách để bạn có thể gọi phương thức (method) từ xa, chẳng hạn gọi method đang chạy
trên một máy tính B. Và nhận kết quả trả về. Như vậy máy B giống như một máy chủ cung cấp dịch
vụ.

2- Tạo project
Tạo mới một project có tên RMITutorial
Đây là mô hình các class được đóng gói dành cho Client​ và ​Server

Đây là mô hình làm việc của RMI. Server sẽ đăng ký đối tượng lên trên bộ đăng ký (Registry). Client
sẽ tìm kiếm bộ đăng ký theo địa chỉ IP và cổng (Host + Port) để có thể gọi các các phương thức
(method) từ các đối tượng tại Server.
Constants.java

1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
public class Constants {
7
8
9
10
11 // Địa điểm Hà Nội
12
13
public static final String LOCATION_HANOI = "HaNoi";
14
15
16 public static final String LOCATION_TOKYO = "Tokyo";
17
public static final String LOCATION_CHICAGO = "Chicago";

// Thời tiết mưa

public static final String WEATHER_RAIN ="rain";

// Thời tiết nắng.

public static final String WEATHER_SUNNY ="sunny";


}

WeatherData.java

?
1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
import java.io.Serializable;
7
8
9 import java.util.Date;
10
11
12
13
public class WeatherData implements Serializable {
14
15
16
17
18 private static final long serialVersionUID = 1L;
19
20
21
22
23 private Date date;
24
25 private String location;
26
27
private String weather;
28
29
30
31
32 public WeatherData(Date date, String location, String weather) {
33
34
this.date = date;
35
36
37 this.location = location;
38
39 this.weather = weather;
40
41
42
43 }
44

public Date getDate() {

return date;

public void setDate(Date date) {

this.date = date;

public String getLocation() {

return location;

public void setLocation(String location) {

this.location = location;

}
public String getWeather() {

return weather;

public void setWeather(String weather) {

this.weather = weather;

WeatherService.java

1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
import java.rmi.Remote;
7
8
9 import java.rmi.RemoteException;
10
11 import java.util.Date;
12
13
14
15

public interface WeatherService extends Remote {

// Method lấy về đối tượng thông tin thời tiết.

// Tham số truyền vào ngày & địa điểm.

public WeatherData getWeather(Date date, String location)

throws RemoteException;

WeatherServiceImpl.java

?
1
2 package org.o7planning.tutorial.rmi.server;
3
4
5
6
import java.rmi.RemoteException;
7
8
9 import java.rmi.server.UnicastRemoteObject;
10
11 import java.util.Calendar;
12
13
import java.util.Date;
14
15
16
17
18 import org.o7planning.tutorial.rmi.Constants;
19
20
import org.o7planning.tutorial.rmi.WeatherData;
21
22
23 import org.o7planning.tutorial.rmi.WeatherService;
24
25
26
27
public class WeatherServiceImpl extends UnicastRemoteObject implements
28
29
30 WeatherService {
31
32 private static final long serialVersionUID = 1L;
33
34
35
36
37 public WeatherServiceImpl() throws RemoteException {
38
39 super();
40
41
42
43 }
44
45
46

@Override

public synchronized WeatherData getWeather(Date date, String location)

throws RemoteException {

Calendar c = Calendar.getInstance();

c.setTime(date);

int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

// Sunday, Monday

if (dayOfWeek == 1 || dayOfWeek == 2) {

if (location.equals(Constants.LOCATION_CHICAGO)) {

// Rain

return new WeatherData(date, location, Constants.WEATHER_RAIN);

} else if (location.equals(Constants.LOCATION_HANOI)) {

// Sunny
return new WeatherData(date, location, Constants.WEATHER_SUNNY);

} else if (location.equals(Constants.LOCATION_TOKYO)) {

// Sunny

return new WeatherData(date, location, Constants.WEATHER_SUNNY);

return new WeatherData(date, location, Constants.WEATHER_SUNNY);

} else {

return new WeatherData(date, location, Constants.WEATHER_SUNNY);

Client.java

?
1
2 package org.o7planning.tutorial.rmi.client;
3
4
5
6
import java.rmi.registry.LocateRegistry;
7
8
9 import java.rmi.registry.Registry;
10
11 import java.util.Date;
12
13
14
15
16 import org.o7planning.tutorial.rmi.Constants;
17
18 import org.o7planning.tutorial.rmi.WeatherData;
19
20
import org.o7planning.tutorial.rmi.WeatherService;
21
22
23
24
25 public class Client {
26
27
28
29
30 // Host or IP of Server
31
32 private static final String HOST = "localhost";
33
34
private static final int PORT = 1099;
35
36
37 private static Registry registry;
38
39
40
41
42
43 public static void main(String[] args) throws Exception {

// Search the registry in the specific Host, Port.

registry = LocateRegistry.getRegistry(HOST, PORT);

// Lookup WeatherService in the Registry.

WeatherService service = (WeatherService) registry

.lookup(WeatherService.class.getSimpleName());

Date today = new Date();

// Get Chicago weather info:

WeatherData chicagoWeather = service.getWeather(today,

Constants.LOCATION_CHICAGO);

System.out.println("Chicago weather today: "

+ chicagoWeather.getWeather());
// Get Hanoi weather info:

WeatherData hanoiWeather = service.getWeather(today,

Constants.LOCATION_HANOI);

System.out.println("Hanoi weather today: " + hanoiWeather.getWeather());

Server.java

?
1
2 package org.o7planning.tutorial.rmi.server;
3
4
5
6
import java.rmi.AlreadyBoundException;
7
8
9 import java.rmi.Remote;
10
11 import java.rmi.RemoteException;
12
13
import java.rmi.registry.LocateRegistry;
14
15
16 import java.rmi.registry.Registry;
17
18
19
20
import org.o7planning.tutorial.rmi.WeatherService;
21
22
23
24
25 public class Server {
26
27
private static final int PORT = 1099;
28
29
30 private static Registry registry;
31
32
33
34
public static void startRegistry() throws RemoteException {
35
36
37
38
39 // Tạo một bộ đăng ký (Registry) tại Server.
40
41
registry = LocateRegistry.createRegistry(PORT);

public static void registerObject(String name, Remote remoteObj)

throws RemoteException, AlreadyBoundException {

// Đăng ký đối tượng vào bộ đăng ký.

// Nó được gắn với cái tên nào đó.

// Client sẽ tìm trên bộ đăng ký với tên này để có thể gọi đối tượng.

registry.bind(name, remoteObj);

System.out.println("Registered: " + name + " -> "

+ remoteObj.getClass().getName() + "[" + remoteObj + "]");

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

System.out.println("Server starting...");
startRegistry();

registerObject(WeatherService.class.getSimpleName(), new
WeatherServiceImpl());

// Server đã được start, và đang lắng nghe các request từ Client.

System.out.println("Server started!");

3- Chạy ứng dụng


Để chạy được ứng dụng trên bạn cần đóng gói project thành 2 file ​jar​. File jar 1 gồm các class dùng
để chạy ứng dụng tại client. Và file jar 2 bao gồm các class để chạy ứng dụng tại server.

Đây là hình minh họa:

Tuy nhiên bạn có thể chạy thử (demo) trên Eclipse​:

Trước hết chạy class Server:


Server đang được chạy, nó đã đăng ký các ​Remote Object lên bộ đăng ký (Registry). Bước tiếp theo
chạy class tại Client. Chạy class Client:

Xem thêm các chuyên mục:

Java cơ bản
Hướng dẫn lập trình Java Socket

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

1- ​Socket là gì?

​ í dụ đơn giản với Socket


2- V

​ í dụ Socket + Thread
3- V

4- ​Java Socket API

4.1- ​ServerSocket class

4.2- ​Socket class

4.3- ​InetAddress

1- Socket là gì?
Tại phía server (server-side):

● Thông thường, một chương trình server chạy trên một máy tính cụ thể, chương trình này có
một ổ cắm (Server Socket), ổ cắm được ràng buộc bởi cổng (Port number) cụ thể. Các chương
trình phục vụ (Server program) chỉ chờ đợi, lắng nghe tại ổ cắm (Server Socket) các Client để
thực hiện một yêu cầu kết nối.

Tại phía client (client-side):

● Các Client biết tên máy của máy tính mà trên đó chương trình chủ (server) đang chạy và số
cổng mà chương trình chủ lắng nghe. Để thực hiện một yêu cầu kết nối, Client cố gắng tạo ra
cuộc gặp với máy chủ trên máy tính của chương trình chủ và cổng. Các Client cũng cần phải
tự định danh chính nó với server để gắn với một cổng địa phương cái sẽ được sử dụng trong
suốt quá trình kết nối này, thông thường nó được gán bởi hệ điều hành.

Hình minh họa tổng quát:

Nếu mọi việc suôn sẻ, chương trình chủ (server program) chấp nhận kết nối của ​client​. Khi chấp
nhận, máy chủ có được một ​socket mới bị ràng buộc vào cùng "cổng địa phương" và thông tin đầu
cuối (remote endpoint) của nó chính là địa chỉ và cổng của ​client​. Nó đã tạo ra một ​socket mới để
chăm sóc ​Client vừa được chấp nhận kết nối, và tiếp tục lắng nghe tại ổ cắm gốc ban đầu
(ServerSocket) cho các yêu cầu kết nối khác.
Về phía ​Client​, nếu kết nối được chấp nhận, một ổ cắm được tạo thành công và Client có thể sử
dụng ổ cắm để giao tiếp với chương trình chủ.

Các Client và Server có thể giao tiếp bằng cách ghi hay đọc từ ổ cắm (Socket) của chúng.

Dữ liệu ghi vào luồng đầu ra trên Socket của client sẽ nhận được trên luồng đầu vào của Socket tại
Server. Và ngược lại dữ liệu ghi vào luồng đầu ra trên ​Socket c​ ủa ​Server s​ ẽ nhận được trên luồng
đầu vào của Socket ​tại Client​.

Định nghĩa:

Một Socket là một điểm cuối của một giao tiếp 2 chiều giữa hai chương trình chạy trên mạng. Socket
được giàng buộc với một cổng (con số cụ thể) để các tầng ​TCP (TCP Layer) có thể định danh ứng
dụng mà dữ liệu sẽ được gửi tới.
2- Ví dụ đơn giản với Socket

SimpleServerProgram.java

?
1
2 package org.o7planning.tutorial.socket;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.BufferedWriter;
10
11 import java.io.IOException;
12
13
import java.io.InputStreamReader;
14
15
16 import java.io.OutputStreamWriter;
17
18 import java.net.ServerSocket;
19
20
import java.net.Socket;
21
22
23
24
25 public class SimpleServerProgram {
26
27
28
29
30 public static void main(String args[]) {
31
32
33
34
ServerSocket listener = null;
35
36
37 String line;
38
39 BufferedReader is;
40
41
42
43 BufferedWriter os;
44
45 Socket socketOfServer = null;
46
47
48
49
50
51
52
53
54
// Mở một ServerSocket tại cổng 9999.
55
56
57 // Chú ý bạn không thể chọn cổng nhỏ hơn 1023 nếu không là người dùng
58
59 // đặc quyền (privileged users (root)).
60
61
try {
62
63
64 listener = new ServerSocket(9999);
65
66 } catch (IOException e) {
67
68
System.out.println(e);
69
70
71 System.exit(1);
72
73 }
74
75
76
77
try {

System.out.println("Server is waiting to accept user...");


// Chấp nhận một yêu cầu kết nối từ phía Client.

// Đồng thời nhận được một đối tượng Socket tại server.

socketOfServer = listener.accept();

System.out.println("Accept a client!");

// Mở luồng vào ra trên Socket tại Server.

is = new BufferedReader(new
InputStreamReader(socketOfServer.getInputStream()));

os = new BufferedWriter(new
OutputStreamWriter(socketOfServer.getOutputStream()));

// Nhận được dữ liệu từ người dùng và gửi lại trả lời.

while (true) {

// Đọc dữ liệu tới server (Do client gửi tới).


line = is.readLine();

// Ghi vào luồng đầu ra của Socket tại Server.

// (Nghĩa là gửi tới Client).

os.write(">> " + line);

// Kết thúc dòng

os.newLine();

// Đẩy dữ liệu đi

os.flush();

// Nếu người dùng gửi tới QUIT (Muốn kết thúc trò chuyện).

if (line.equals("QUIT")) {

os.write(">> OK");

os.newLine();

os.flush();

break;

}
}

} catch (IOException e) {

System.out.println(e);

e.printStackTrace();

System.out.println("Sever stopped!");

SimpleClientDemo.java

?
1
2 package org.o7planning.tutorial.socket;
3
4
5
6
import java.io.*;
7
8
9 import java.net.*;
10
11
12
13
public class SimpleClientDemo {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 // Địa chỉ máy chủ.
24
25 final String serverHost = "localhost";
26
27
28
29
30 Socket socketOfClient = null;
31
32 BufferedWriter os = null;
33
34
BufferedReader is = null;
35
36
37
38
39 try {
40
41
42
43 // Gửi yêu cầu kết nối tới Server đang lắng nghe
44
45 // trên máy 'localhost' cổng 9999.
46
47
socketOfClient = new Socket(serverHost, 9999);
48
49
50
51
52 // Tạo luồng đầu ra tại client (Gửi dữ liệu tới server)
53
54
os = new BufferedWriter(new
55
OutputStreamWriter(socketOfClient.getOutputStream()));
56
57
58
59
60 // Luồng đầu vào tại Client (Nhận dữ liệu từ server).
61
62
is = new BufferedReader(new
63
InputStreamReader(socketOfClient.getInputStream()));
64
65
66
67
68 } catch (UnknownHostException e) {

System.err.println("Don't know about host " + serverHost);

return;

} catch (IOException e) {

System.err.println("Couldn't get I/O for the connection to " + serverHost);

return;

}
try {

// Ghi dữ liệu vào luồng đầu ra của Socket tại Client.

os.write("HELO");

os.newLine(); // kết thúc dòng

os.flush(); // đẩy dữ liệu đi.

os.write("I am Tom Cat");

os.newLine();

os.flush();

os.write("QUIT");

os.newLine();

os.flush();

// Đọc dữ liệu trả lời từ phía server

// Bằng cách đọc luồng đầu vào của Socket tại Client.

String responseLine;

while ((responseLine = is.readLine()) != null) {


System.out.println("Server: " + responseLine);

if (responseLine.indexOf("OK") != -1) {

break;

os.close();

is.close();

socketOfClient.close();

} catch (UnknownHostException e) {

System.err.println("Trying to connect to unknown host: " + e);

} catch (IOException e) {

System.err.println("IOException: " + e);

Chạy ví dụ:
Trước hết bạn cần chạy class SimpleServerProgram​:

Tiếp theo chạy class SimpleClientDemo​.

3- Ví dụ Socket + Thread
Thông thường một kết nối giữa chương trình chủ (Server) và 1 Client được tạo ra, bạn nên để chúng
nói chuyện với nhau trên một luồng (Thread), như vậy mỗi khi có một kết nối mới một luồng mới lại
được tạo ra.

ServerProgram.java

?
1
2 package org.o7planning.tutorial.socketthread;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.BufferedWriter;
10
11 import java.io.IOException;
12
13
import java.io.InputStreamReader;
14
15
16 import java.io.OutputStreamWriter;
17
18 import java.net.ServerSocket;
19
20
import java.net.Socket;
21
22
23
24
25 public class ServerProgram {
26
27
28
29
30 public static void main(String args[]) throws IOException {
31
32
33
34
ServerSocket listener = null;
35
36
37
38
39 System.out.println("Server is waiting to accept user...");
40
41
42
43 int clientNumber = 0;
44
45
46
47
48
49
50 // Mở một ServerSocket tại cổng 7777.
51
52 // Chú ý bạn không thể chọn cổng nhỏ hơn 1023 nếu không là người dùng
53
54
// đặc quyền (privileged users (root)).
55
56
57 try {
58
59 listener = new ServerSocket(7777);
60
61
} catch (IOException e) {
62
63
64 System.out.println(e);
65
66 System.exit(1);
67
68
}
69
70
71
72
73 try {
74
75
while (true) {
76
77
78
79
80
81
82
83
84 // Chấp nhận một yêu cầu kết nối từ phía Client.
85
86 // Đồng thời nhận được một đối tượng Socket tại server.
87
88
89
90
91 Socket socketOfServer = listener.accept();
92
93 new ServiceThread(socketOfServer, clientNumber++).start();
94
95
}
96
97
98 } finally {
99
10 listener.close();
0
10
}
1

private static void log(String message) {

System.out.println(message);

private static class ServiceThread extends Thread {


private int clientNumber;

private Socket socketOfServer;

public ServiceThread(Socket socketOfServer, int clientNumber) {

this.clientNumber = clientNumber;

this.socketOfServer = socketOfServer;

// Log

log("New connection with client# " + this.clientNumber + " at " +


socketOfServer);

@Override

public void run() {

try {
// Mở luồng vào ra trên Socket tại Server.

BufferedReader is = new BufferedReader(new


InputStreamReader(socketOfServer.getInputStream()));

BufferedWriter os = new BufferedWriter(new


OutputStreamWriter(socketOfServer.getOutputStream()));

while (true) {

// Đọc dữ liệu tới server (Do client gửi tới).

String line = is.readLine();

// Ghi vào luồng đầu ra của Socket tại Server.

// (Nghĩa là gửi tới Client).

os.write(">> " + line);

// Kết thúc dòng

os.newLine();

// Đẩy dữ liệu đi

os.flush();
// Nếu người dùng gửi tới QUIT (Muốn kết thúc trò chuyện).

if (line.equals("QUIT")) {

os.write(">> OK");

os.newLine();

os.flush();

break;

} catch (IOException e) {

System.out.println(e);

e.printStackTrace();

ClientDemo.java

?
1
2 package org.o7planning.tutorial.socketthread;
3
4
5
6
import java.io.*;
7
8
9 import java.net.*;
10
11 import java.util.Date;
12
13
14
15
16 public class ClientDemo {
17
18
19
20
public static void main(String[] args) {
21
22
23
24
25 // Địa chỉ máy chủ.
26
27
final String serverHost = "localhost";
28
29
30
31
32 Socket socketOfClient = null;
33
34
BufferedWriter os = null;
35
36
37 BufferedReader is = null;
38
39
40
41
42
43 try {
44
45 // Gửi yêu cầu kết nối tới Server đang lắng nghe
46
47
// trên máy 'localhost' cổng 7777.
48
49
50 socketOfClient = new Socket(serverHost, 7777);
51
52
53
54
// Tạo luồng đầu ra tại client (Gửi dữ liệu tới server)
55
56
57 os = new BufferedWriter(new
58 OutputStreamWriter(socketOfClient.getOutputStream()));
59
60
61
62
// Luồng đầu vào tại Client (Nhận dữ liệu từ server).
63
64
65 is = new BufferedReader(new
66 InputStreamReader(socketOfClient.getInputStream()));
67
68
69

} catch (UnknownHostException e) {

System.err.println("Don't know about host " + serverHost);

return;

} catch (IOException e) {

System.err.println("Couldn't get I/O for the connection to " + serverHost);

return;
}

try {

// Ghi dữ liệu vào luồng đầu ra của Socket tại Client.

os.write("HELO! now is " + new Date());

os.newLine(); // kết thúc dòng

os.flush(); // đẩy dữ liệu đi.

os.write("I am Tom Cat");

os.newLine();

os.flush();

os.write("QUIT");

os.newLine();

os.flush();

// Đọc dữ liệu trả lời từ phía server

// Bằng cách đọc luồng đầu vào của Socket tại Client.

String responseLine;
while ((responseLine = is.readLine()) != null) {

System.out.println("Server: " + responseLine);

if (responseLine.indexOf("OK") != -1) {

break;

os.close();

is.close();

socketOfClient.close();

} catch (UnknownHostException e) {

System.err.println("Trying to connect to unknown host: " + e);

} catch (IOException e) {

System.err.println("IOException: " + e);

}
}

4- Java Socket API

4.1- ServerSocket class

Contructor:

TT Phương thức và mô tả

1 public ServerSocket(int port) throws IOException

Tạo một đối tượng Server Socket giàng buộc với một cổng cụ thể. Một ngoại lệ sẽ được ném
ra nếu cổng đó đã bị giàng buộc (Sử dung) bởi một chương trình khác.

2 public ServerSocket(int port, int backlog) throws IOException

Tương tự như cấu tử trên, tham số backlog định rõ có bao nhiêu client đến để lưu trữ trên
hàng đợi.

3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException

Tương tự như cấu tử trên, tham số InetAddress chỉ rõ địa chỉ IP địa phương sẽ được nối (bind)
tới. InetAddress được sử dụng cho các máy chủ có thể có nhiều địa chỉ IP, cho phép các máy
chủ để xác định các địa chỉ IP của nó để chấp nhận yêu cầu của client.

4 public ServerSocket() throws IOException

Tạo một Server Socket chưa định rõ cổng, địa chỉ. Khi sử dụng cấu tử này, sử dụng phương
thức bind(..)​ khi bạn sẵn sàng để nối với địa chỉ, cổng cụ thể.

Phương thức:

TT Phương thức và mô tả
1 public int getLocalPort()

Trả về cổng mà Server Socket đang lắng nghe. Phương thức này rất có ích, nếu bạn đưa vào
giá trị cổng bằng 0 trong cấu tử, nghĩa là nói với server tự tìm một cổng phù hợp, sau đó sử
dụng phương thức này để lấy ra giá trị thực.

2 public Socket accept() throws IOException

Đợi một yêu cầu kết nối từ client. Phương thức này sẽ khóa ứng dụng cho tới khi có một yêu
cầu kết nối từ client đến trên cổng cụ thể hoặc hết thời gian chờ (Time-out), giả sử rằng thời
gian time-out được thiết lập sử dụng phương thức setSoTimeout().​ Ngược lại method sẽ bị
khóa vô thời hạn.

3 public void setSoTimeout(int timeout)

Sét thời gian chờ tối đa (time-out) nghĩa là thời gian Server Socket sẽ chờ yêu cầu kết nối từ
người dùng trong quá trình accept().

4 public void bind(SocketAddress host, int backlog)

Nối Server Socket tới một server cụ thể có cổng định sẵn trong đối tượng SocketAddress. Sử
dụng phương thức này nếu bạn khởi tạo ServerSocket sử dụng cấu tử mặc định (Không tham
số).

4.2- Socket class

Constructor:

TT Cấu tử và mô tả

1 public Socket(String host, int port) throws UnknownHostException, IOException.

Cấu tử này tạo Socket kết nối tới Server cụ thể tại cổng xác định trong tham số, Nếu nó không
ném ra ngoại lệ, nghĩa là việc kết nối thành công, client đã kết nối với server.
2 public Socket(InetAddress host, int port) throws IOException

Cấu tử này giống hệt với các nhà xây dựng trước đó, ngoại trừ Server được biểu thị bằng một
đối tượng InetAddress.

3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.

Kết nối tới host, port cụ thể, tạo ra một Socket trên host địa phương, và cổng địa phương được
chỉ định trong tham số.

4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.

Cấu tử này giống hệt với cấu tử trên, ngoại trừ server được biểu thị bằng một đối tượng
InetAddress thay vì một String

5 public Socket()

Tạo một Socket chưa kết nối. Sử dụng phương thức connect() để kết nối socket này tới server.

Phương thức:

TT Phương thức và mô tả

1 public void connect(SocketAddress host, int timeout) throws IOException

Phương thức này kết nối socket này tới host chỉ định. Phương thức này cần thiết chỉ khi bạn
khởi tạo một đối tượng Socket thông qua cấu tử mặc định (Không tham số).

2 public InetAddress getInetAddress()

Phương thức này trả về địa chỉ của máy tính mà socket này kết nối tới.
3 public int getPort()

Trả về cổng giàng buộc tới máy tính từ xa.

4 public int getLocalPort()

Trả về cổng socket là ràng buộc để trên máy địa phương.

5 public SocketAddress getRemoteSocketAddress()

Trả về địa chỉ của socket từ xa (remote socket).

6 public InputStream getInputStream() throws IOException

Trả về luồng đầu vào của Socket. Luồng đầu vào này được kết nối với luồng đầu ra của Socket
từ xa (remote socket).

7 public OutputStream getOutputStream() throws IOException

Trả về luồng đầu ra của Socket. Luồng đầu ra này kết nối với luồng đầu vào của Socket từ xa.

8 public void close() throws IOException

Đóng socket, nghĩa là làm cho Socket này không còn khả năng trò chuyện với máy kia.

4.3- InetAddress

Phương thức:

TT Phương thức và mô tả

1 static InetAddress getByAddress(byte[] addr)


Trả về đối tượng InetAddress cho bởi địa chỉ IP thô.

2 static InetAddress getByAddress(String host, byte[] addr)

Trả về đối tượng InetAddress dựa trên tên máy chủ được cung cấp và địa chỉ IP.

3 static InetAddress getByName(String host)

Xác định địa chỉ IP của host, cho bởi tên host.

4 String getHostAddress()

Trả về địa chỉ IP.

5 String getHostName()

Trả về host name

6 static InetAddress getLocalHost()

Trả về địa chỉ địa phương.

7 String toString()

Chuyển đối tượng thành String.

Xem thêm các chuyên mục:

Java cơ bản
Các nền tảng nào bạn nên chọn để lập trình ứng dụng Java Desktop?

Xem thêm các chuyên mục:

Eclipse Org
Eclipse RCP
Eclipse RAP
Java cơ bản
Công nghệ của Eclipse

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ iới thiệu
1- G

​ ập trình Java ứng dụng Desktop


2- L

2.1- ​Swing

2.2- ​SWT (Standard Widget Toolkit)

2.3- ​So sánh SWT và Swing

2.4- ​Bạn nên chọn SWT hay Swing?

​ ông nghệ của Eclipse


3- C

​ CP làm được những gì?


4- R

​ AP làm được những gì?


5- R

​ AP & RCP - Tại sao code rất giống nhau?


6- R

​ ạn nên bắt đầu từ đâu?


7- B

1- Giới thiệu
Thực tế có một số câu hỏi thông dụng với Java:

● Tôi nên chọn giải pháp nào để lập trình một ứng dụng Desktop
● Có một giải pháp nào để lập trình một website có giao diện giống ứng dụng Desktop ​không?

Trong tài liệu này tôi sẽ trả lời tổng quan về câu hỏi trên đồng thời có các giải pháp giúp bạn làm
được điều đó.

Ứng dụng Desktop:

Đây là một ứng dụng Desktop ​viết bằng Java ​( ​Java Swing​):

Ứng dụng web:

Và đây là một ứng dụng ​Web ​có giao diện giống giao diện một ứng dụng ​Desktop​, nó được viết trên
Eclipse RAP​:

● http://rap.eclipsesource.com/demo/release/workbench/
2- Lập trình Java ứng dụng Desktop
Thực tế để lập trình ứng dụng Desktop ​bạn có 2 lựa chọn

● Sử dụng Swing - Là một thư viện tích hợp sẵn trên JDK và có khả năng chạy trên mọi hệ điều
hành khác nhau (​Windows, Unix, Mac OS​,..)
● Sử dụng SWT - Là một thư viện để lập trình ứng dụng Desktop ​được phát triển bởi IBM​. Nó
có khả năng chạy trên mọi hệ điều hành khác nhau (Window, Unix, Mac OS​,..)

Đây là hình ảnh một ứng dụng Desktop v​ iết bằng SWT v​ à chạy trên các hệ điều hành khác nhau:

Đây là hình ảnh ứng dụng ​Desktop ​viết bằng S​ wing​. Với ​"Look And Feel" mặc định trông nó khá
ngô nghê. Trong lập trình bạn có thể chọn một L​ -A-F khác để có được giao diện giống với ​Windows
​ ếu muốn.
hoặc Linux n
2.1- Swing

AWT (Abstract Window Toolkit) - là một bộ thư viện được phát triển dành cho lập trình ​Desktop ​có
sẵn trong ​JDK​, tuy nhiên đáng tiếc là nó hoạt động không như mong muốn trên các hệ điều hành
khác nhau. Đó là lý do ​Swing được ra đời thay thế cho ​AWT​, để đảm bảo rằng nó chạy tốt trên các
hệ điều hành khác nhau.

Swing ​xây dựng giao diện đồ họa hoàn toàn bằng ​Java​. Và chạy trên mọi hệ điều hành. Nó không
thay thế ​AWT ​mà thừa kế từ ​AWT​, đây là một điểm yếu của nó là bối rối những người lập trình, một
số lượng lớn các lớp thuộc ​AWT g ​ iờ đã không còn được dùng nữa, hoặc nó lại là lớp để các lớp của
Swing t​ hừa kế. Theo tôi chính điều này làm Swing b​ ị đánh giá thấp.

2.2- SWT (Standard Widget Toolkit)

SWT (Standard Widget Toolkit) là một thư viện lập trình ứng dụng ​Desktop đ ​ ược phát triển bởi
IBM​. Nó không phát triển đồ họa hoàn toàn bằng ​Java​. Khi chạy trên hệ điều hành nào, nó cố gắng
tận dụng các giao diện đồ họa của hệ điều hành đó ( ​Button​, ​Label​, ...) và chỉ tạo đồ họa thành phần
mà hệ điều hành đó không có bằng Java​.

Nếu lập trình ​SWT t​ ốt nhất bạn chọn E


​ clipse IDE để lập trình. E
​ clipse c​ ó thể tích hợp plugin
WindowBuilder ​hỗ trợ kéo thả các thành phần giao diện vô cùng dễ dàng. W ​ indowBuilder ​vốn là
một sản phẩm thương mại nay đã được miễn phí sử dụng khi tích hợp vào Eclipse.​

2.3- So sánh SWT và Swing

Swing ​là một thư viện thuần ​Java​, khi bạn lập trình xong ứng dụng bạn có thể sét đặt ​Look And Feel
(Nhìn và cảm nhận) để có một giao diện giống của ​Windows​, hoặc ​Linux h ​ oặc ​Mac Os​,... Có sẵn
một số ​Look And Feel trên ​JDK b ​ ạn có thể sử dụng hoặc có thể mua các ​L-A-F​. Như vậy bạn có
chạy một ứng dụng ​Swing ​trên hệ điều hành ​Windows ​mà giao diện hiển thị lên lại là của ​Linux​, ​Mac
Os​, ..
Đây là một link giới thiệu về các L-A-F​ đẹp:

● http://www.jwrapper.com/blog/6-great-look-and-feels-to-make-your-java-app-pretty

SWT - Đây là một thư viện không viết hoàn toàn bằng ​Java​. Khi nó chạy trên hệ điều hành nào nó cố
gắng tận dụng các thư viện thành phần của hệ điều hành đó (chẳng hạn tận dụng các ​Button​, ​Label​,
Frame​, ...), và chỉ dùng ​Java đ
​ ể vẽ các thành phần nếu nó không có trên hệ điều hành. Như vậy về
tốc độ SWT ​nhanh hơn ​Swing​.

Với ​SWT ​chúng ta không có khái niệm ​Look And Feel như ​Swing​. Khi bạn chạy ứng dụng trên nền
hệ điều hành nào, giao diện sẽ mang đặc tính của hệ điều hành đó.

So sánh tốc độ:

2.4- Bạn nên chọn SWT hay Swing?

Tôi nghĩ rằng bạn nên chọn ​SWT ​cho việc lập trình ứng dụng ​Desktop ​vì đây là một bộ thư viện
phong phú các thành phần giao diện khác nhau. Hơn nữa nó là bộ thư viện ra đời sau ​Swing​, nó học
hỏi và giải quyết các yếu điểm của Swing​.
SWT​ với các bộ thư viện mở rộng đang được phát triển thêm, chẳng hạn như:

● Nebula

Eclipse ​phát triển một nền tảng mới gọi là ​RAP (Remote Application Platform) ​- ​RAP cho phép bạn
lập trình các ứng dụng có giao diện giống các ứng dụng ​Desktop​, và lại sử dụng các class quen
thuộc có trong ​SWT​. Như vậy bạn có thể viết một ứng dụng mà có thể chạy cả trên nền ​Web ​và chạy
cả trên nền Desktop​. Đây là một điểm mạnh nếu bạn chọn SWT​.

Hãy xem một Demo (​ bản giới thiệu) chương trình viết bằng RAP​:

● http://eclipse.org/rap/demos/
3- Công nghệ của Eclipse
Chúng ta cần có một cái nhìn về công nghệ của Eclipse

RCP (Rich Client Platform) ​: Là một ​platform s​ ử dụng thư viện ​SWT ​để lập trình các ứng dụng
Desktop​. Có thể chạy trên mọi hệ điều hành khác nhau.

(Chi tiết hơn về RCP được đề cập ở phần sau.)

RAP (Remote Application Platform): Là một Platform sử dụng thư viện ​RWT để lập trình các ứng
dụng chạy trên Web giống ứng dụng Desktop.

● RWT (RAP Widget Toolkit)​ là bộ thư viện với các class cùng tên với class của SWT​, và có
các method tương tự, giúp bạn lập trình các ứng dụng RAP c​ hạy trên Web​. Chính vì đặc tính
này chỉ cần 1 source code​, bạn có thể chạy ứng dụng trên nền Desktop ​hoặc trên nền Web​.

RAP c​ hạy tốt trên các trình duyệt khác nhau.


Tabris - Là một bộ thư viện viết cho các ứng dụng ​Mobile​, và chạy được trên các loại ​Mobile ​khác
nhau.

4- RCP làm được những gì?


RCP (Rich Client Platform) ​: Là một Platform sử dụng thư viện ​SWT để lập trình các ứng dụng
Desktop​. Chạy trên mọi hệ điều hành khác nhau, nó chính là platform viết ra Eclipse IDE​.

Như vậy ​RCP ​là một Platform sử dụng ​SWT ​làm cơ sở để xây dựng lên. Bạn có thể sử dụng Platform
​ ể lập trình lên ứng dụng Desktop​.
RCP đ

Hình minh họa dưới đây là một ứng dụng đơn giản (Chỉ dùng tới ​SWT​, chưa dùng gì tới những thứ
cao cấp của RCP Platform​):
RCP Platform đã xây dựng một nền tảng cho phép bạn lập trình ra các ​giao diện có cấu trúc phức
tạp giống Eclipse IDE​, nó bao gồm các hệ thống Menu, Toolbar, View, Editor,​ ...

RCP c​ ũng cho phép bạn phát triển các Plugin ​tích hợp vào Eclipse ​mà bạn đang sử dụng.
5- RAP làm được những gì?
RAP (Remote Application Platform): Là một Platform sử dụng thư viện ​RWT ​để lập trình các ứng
​ iống ứng dụng Desktop​.
dụng chạy trên Web g

● RWT (RAP Widget Toolkit)​ là bộ thư viện với các class cùng tên với class của SWT​, và có
các method tương tự, giúp bạn lập trình các ứng dụng RAP c​ hạy trên Web​. Chính vì đặc tính
này chỉ cần 1 source code​, bạn có thể chạy ứng dụng như một ứng dụng Desktop ​hoặc trên
Web​.

Cũng giống như ​RCP, RAP là một Platform, nó cũng cho phép tạo ra các ứng dụng có giao diện phức
tạp giống Eclipse IDE​.
6- RAP & RCP - Tại sao code rất giống nhau?
Đây là cấu trúc 2 Platform:

● RCP sử dụng SWT (Standard Widget Toolkit)


● RAP sử dụng RWT (RAP Widget Toolkit)

Đây là một ví dụ, thêm một Button v​ ào một Composite​:


** MyApplicationWindow **

1
2 import org.eclipse.swt.widgets.Display;
3
4 import org.eclipse.swt.widgets.Shell;
5
6
import org.eclipse.swt.layout.FillLayout;
7
8
9 import org.eclipse.swt.SWT;
10
11 import org.eclipse.swt.widgets.Composite;
12
13
import org.eclipse.swt.layout.GridLayout;
14
15
16 import org.eclipse.swt.widgets.Button;
17
18
19
20
public class MyApplicationWindow {
21
22
23

.......

protected void createContents() {

.......

Composite composite = new Composite(shell, SWT.NONE);


composite.setLayout(new GridLayout(1, false));

Button btnMyButton = new Button(composite, SWT.NONE);

btnMyButton.setText("My Button");

SWT​, và ​RWT ​đều sử dụng class org.eclipse.swt.widgets.Button​ để tạo Button .

Code của lớp ​Button ​trong ​SWT ​(chạy trên desktop) rõ ràng khác với code class ​Button c​ ủa ​RWT
(vốn để chạy trên WEB).

● Class ​Button c​ ủa SWT ​được đóng gói trong file jar ​có tên ​org.eclipse.swt_*.jar
● Class B​ utton c​ ủa RWT đ
​ ược đóng gói trong file jar ​có tên ​org.eclipse.rap.rwt_*.jar

Target Platform​ là một môi trường thư viện, bạn có thể khai báo.
Bạn có thể khai báo ra 2 ​Target Platform​. Một cái gồm các thư viện RCP, và một cái gồm các thư
viện RAP.

● RCP Target Platform


● RAP Target Platform

Cùng một code bạn chạy với ​RCP Target Platform sẽ là một ứng dụng Desktop. Khi chạy với ​RAP
Target Platform​ sẽ là một ứng dụng chạy trên Web.

Tất nhiên ​RAP ​và ​RCP ​có đôi chút khác biệt, không phải tất cả các thành phần của ​SWT đ ​ ều có
tương ứng trên ​RWT​, và ngược lại. Tùy trường hợp có thể sử lý các khác biệt này. Các ứng dụng có
thể chạy trên trên cả nền Desktop và Web được biết tới với khái niệm "Single Sourcing".​

7- Bạn nên bắt đầu từ đâu?


Nếu bạn theo hướng lập trình ​RAP-RCP​. Bạn cần phải tìm hiểu về ​SWT​, điều đó cũng có nghĩa là
bạn sẽ dễ dàng biết RWT​.

Làm việc với ​SWT nghĩa là làm việc với các đối tượng ​Widget ​( ​Button​, ​Label​, ..) và xử lý ​Layout​.
WindowBuilder là một plugin cho phép kéo thả các thành phần lên giao diện, và tự động tạo ra code
tương ứng.

Bạn có thể tham khảo tài liệu dưới đây, nó hướng dẫn lập trình ​SWT v​ ới ​WindowBuilder là công cụ
trực quan, dễ dàng kéo thả các thành phần giao diện.

● Hướng dẫn lập trình Java Desktop sử dụng SWT


​ ạn có thể tiếp tục với RCP ​hoặc RAP​.
Sau khi bạn thành thạo lập trình với SWT b

SWT:
● Hướng dẫn lập trình Java Desktop sử dụng SWT

RCP

● Hướng dẫn lập trình Eclipse RCP 4 cho người mới bắt đầu - Ứng dụng e4 Workbench

RAP

● Hướng dẫn lập trình Eclipse RAP cho người mới bắt đầu - Ứng dụng cơ bản

Xem thêm các chuyên mục:

Eclipse Org
Eclipse RCP
Eclipse RAP
Java cơ bản
Công nghệ của Eclipse
Mục lục

1- ​Giới thiệu

2- ​Thư viện

3- ​Tạo project

4- ​IOUtils

5- ​FileUtils

6- ​FilenameUtils

7- ​FileSystemUtils

8- ​Line iterator

9- ​File filters (Bộ lọc file)

​ ile comparators (Bộ so sánh File)


10- F

​ treams (Luồng vào ra dữ liệu)


11- S

Apache Org
Java cơ bản

Hướng dẫn sử dụng Java Commons IO

Xem thêm các chuyên mục:

Apache Org
Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ iới thiệu
1- G
​ hư viện
2- T

​ ạo project
3- T

4- ​IOUtils

5- ​FileUtils

6- ​FilenameUtils

7- ​FileSystemUtils

8- ​Line iterator

​ ile filters (Bộ lọc file)


9- F

​ ile comparators (Bộ so sánh File)


10- F

​ treams (Luồng vào ra dữ liệu)


11- S

1- Giới thiệu

2- Thư viện

● http://mvnrepository.com/artifact/commons-io/commons-io
3- Tạo project
Tạo một Maven Project.
● Group ID: org.o7planning
● Artifact ID: CommonsIOTutorial
Đây là hình ảnh project được tạo ra.

​ ể sử dụng Commons IO​:


Cấu hình Maven đ
pom.xml

1
2 <project xmlns="​http://maven.apache.org/POM/4.0.0​"
3 xmlns:xsi="​http://www.w3.org/2001/XMLSchema-instance​"
4
5 xsi:schemaLocation="​http://maven.apache.org/POM/4.0.0
6 http://maven.apache.org/xsd/maven-4.0.0.xsd​">
7
8
<modelVersion>4.0.0</modelVersion>
9
10
11 <groupId>org.o7planning</groupId>
12
13 <artifactId>CommonsIOTutorial</artifactId>
14
15
<version>0.0.1-SNAPSHOT</version>
16
17

<dependencies>

<dependency>

<groupId>commons-io</groupId>

<artifactId>commons-io</artifactId>

<version>2.4</version>

</dependency>

</dependencies>
</project>

4- IOUtils
IOUtils là một class tiện ích hỗ trợ để xử lý vào ra dữ liệu một cách nhanh chóng hơn. Nếu bạn sử
dụng ​java.io chuẩn của java bạn có thể làm được những thứ mình muốn. Nhưng muốn viết code
nhanh hơn, tiết kiệm thời gian hơn, hãy sử dụng IOUtils​.

Xem Javadoc của IOUtils​ tại đây:

● http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/I
OUtils.html

Hãy xem một đoạn code được xử lý theo cách thông thường (Dùng những gì có sẵn trong JDK​).

1
2 InputStream in = new URL("​http://commons.apache.org​").openStream();
3
4 try {
5
6
InputStreamReader inR = new InputStreamReader(in);
7
8
9 BufferedReader buf = new BufferedReader(inR);
10
11 String line;

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

System.out.println(line);

} finally {
in.close();

Và đây là đoạn code sử dụng class IOUtils​:

1
2 InputStream in = new URL("​http://commons.apache.org​").openStream();
3
4 try {
5
6
System.out.println(IOUtils.toString(in));

} finally {

IOUtils.closeQuietly(in);

Nhìn vào 2 đoạn code trên chúng ta thấy rõ ràng cùng làm một mục tiêu, nhưng sử dụng ​IOUtils ngắn
gọn hơn hẳn.

ReadURL1.java

?
1
2 package org.o7planning.tutorial.commonsio.io;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.IOException;
10
11 import java.io.InputStream;
12
13
import java.io.InputStreamReader;
14
15
16 import java.net.MalformedURLException;
17
18 import java.net.URL;
19
20
21
22
23 public class ReadURL1 {
24
25
26
27
public static void readURL() throws MalformedURLException, IOException {
28
29
30 InputStream in = new URL("​http://commons.apache.org​").openStream();
31
32 try {
33
34
InputStreamReader inR = new InputStreamReader(in);

BufferedReader buf = new BufferedReader(inR);

String line;
while ((line = buf.readLine()) != null) {

System.out.println(line);

} finally {

in.close();

public static void main(String[] args) {

try {

readURL();

} catch (Exception e) {

e.printStackTrace();

ReadURL2.java

?
1
2 package org.o7planning.tutorial.commonsio.io;
3
4
5
6
import java.io.IOException;
7
8
9 import java.io.InputStream;
10
11 import java.net.MalformedURLException;
12
13
import java.net.URL;
14
15
16
17
18 import org.apache.commons.io.IOUtils;
19
20
21
22
23 public class ReadURL2 {
24
25
26
27
public static void readURL() throws MalformedURLException, IOException {
28
29
InputStream in = new URL("​http://commons.apache.org​").openStream();

try {

System.out.println(IOUtils.toString(in));

} finally {

IOUtils.closeQuietly(in);
}

public static void main(String[] args) {

try {

readURL();

} catch (Exception e) {

e.printStackTrace();

5- FileUtils
Class ​FileUtils chứa các method tiện ích để làm việc với các đối tượng File. Bao gồm đọc, viết, copy,
và so sánh các file.

Tra cứu Javadoc của FileUtils​:

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

FileUtilsReadFile.java

?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
7
8
9 import java.io.File;
10
11 import java.io.IOException;
12
13
import java.util.List;
14
15
16
17
18 import org.apache.commons.io.FileUtils;
19
20
21
22
23 public class FileUtilsReadFile {
24
25
26
27
28
29
30 public static void readFile() throws IOException {

File file= new File("D:/test.txt");

List<String> lines= FileUtils.readLines(file);

for(String s: lines) {
System.out.println(s);

public static void main(String[] args) {

try {

readFile();

} catch (IOException e) {

e.printStackTrace();

FileUtilsTouchFile.java

?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
import java.io.IOException;
7
8
9 import org.apache.commons.io.FileUtils;
10
11 import java.io.File;
12
13
14
15
16 public class FileUtilsTouchFile {
17
18
19
20
public static void main(String[] args) {
21
22
23
24
25 try {
26
27
// E:/test.txt chưa có trên hệ thống.
28
29
30 File testFile = new File("E:/test.txt");
31
32
33

// Lấy ra thời gian sửa đổi lần cuối của file.

long fileTimestamp = testFile.lastModified();


System.out.println("Time in milis " + fileTimestamp);

// Sử dụng method touch(...)

// Nếu file chưa tồn tại nó sẽ tạo ra file rỗng

// Và thay đổi thời gian sửa lần cuối của file bằng thời gian hiện tại.

FileUtils.touch(testFile);

System.out.println("Time in milis updated "

+ testFile.lastModified());

} catch (IOException ex) {

ex.printStackTrace();

Chạy lần đầu tiên (Lúc E:/test.txt​ thực sự chưa tồn tại trên ổ cứng)
Chạy lần thứ 2 (Khi E:/test.txt​ đã được tạo ra và được sét đặt thời gian sửa đổi lần cuối trước đó)

Sử dụng ​FileUtils cho phép bạn dễ dàng copy và paste file từ nơi nọ sang nơi kia, hoặc copy các file
từ thư mục nọ sang thư mục kia.

FileUtilsCopyDirectory.java

?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11
12
13
import org.apache.commons.io.FileUtils;
14
15
16
17
18 public class FileUtilsCopyDirectory {
19
20

public static void main(String[] args) {

File srcDir = new File("C:/test");

File destDir = new File("D:/test/abc");

try {

FileUtils.copyDirectory(srcDir, destDir);

} catch (IOException e) {

e.printStackTrace();

}
}

6- FilenameUtils
Class ​FilenameUtils có các method hữu ích để làm việc với tên tập tin mà không sử dụng các đối
tượng ​File​. Class này nhằm mục đích phù hợp ở giữa ​Unix và ​Windows​, để hỗ trợ quá trình chuyển
đổi giữa các môi trường tổng hợp (chẳng hạn như di chuyển từ môi trường lập trình phát triển sang
môi trường sản phẩm hoàn chỉnh).

FilenameUtils javadoc:

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FilenameUtils.
html

Ví dụ minh họa, bỏ đi hai dấu chấm trên đường dẫn file:

FilenameUtilsNormalize.java

?
1
2 package org.o7planning.tutorial.commonsio.filenameutils;
3
4
5
6
import org.apache.commons.io.FilenameUtils;
7
8
9
10
11 public class FilenameUtilsNormalize {
12
13
14

public static void main(String[] args) {

String filename = "C:/commons/io/../lang/project.xml";

String normalized = FilenameUtils.normalize(filename);

System.out.println(normalized);

Chạy và nhận kết quả:


FilenameUtils​ có tới hơn 40 method tiện ích, chi tiết bạn có thể xem trong Javadoc.

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FilenameUtils.
html

7- FileSystemUtils
Class ​FileSystemUtils có các method hữu ích để làm việc với hệ thống tập tin để truy cập vào các
chức năng không được hỗ trợ bởi ​JDK​. Hiện tại, class này mới chỉ có các method để có được không
gian trống trên ổ đĩa. Chú ý là nó sử dụng các lệnh ​command line​. Không sử dụng mã tự nhiên
(native code).

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileSystemUtil
s.html

FileSystemUtilsFreeSpaceKb.java

?
1
2 package org.o7planning.tutorial.commonsio.filesystemutils;
3
4
5
6
import java.io.IOException;
7
8
9
10
11 import org.apache.commons.io.FileSystemUtils;
12
13
14
15
16 public class FileSystemUtilsFreeSpaceKb {
17
public static void main(String[] args) {

try {

Long kb = FileSystemUtils.freeSpaceKb("C:/");

System.out.println("Free Space: " + kb + "KB");

} catch (IOException e) {

e.printStackTrace();

8- Line iterator
Class ​org.apache.commons.io.LineIterator Cung cấp một cách linh hoạt để làm việc với một tập tin
dựa trên dòng. Một ví dụ có thể được tạo ra trực tiếp, hoặc thông qua các method của ​FileUtils hoặc
IOUtils​. Bạn nên sử dụng theo cách:

1
2 LineIterator it = FileUtils.lineIterator(file, "UTF-8");
3
4 try {
5
6
while (it.hasNext()) {
7
8
9 String line = it.nextLine();

// / do something with line

} finally {

LineIterator.closeQuietly(it);

LineIteratorExample.java

?
1
2 package org.o7planning.tutorial.commonsio.lineiterator;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11
12
13
import org.apache.commons.io.FileUtils;
14
15
16 import org.apache.commons.io.LineIterator;
17
18
19
20
public class LineIteratorExample {
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
File file = new File("D:/test.txt");
28
29
30 LineIterator it = FileUtils.lineIterator(file, "UTF-8");

try {

while (it.hasNext()) {

String line = it.nextLine();

//
if (line != null && line.startsWith("##")) {

System.out.println(line.substring(2));

} finally {

LineIterator.closeQuietly(it);

} catch (IOException e) {

e.printStackTrace();

9- File filters (Bộ lọc file)


Package ​org.apache.commons.io.filefilter định nghĩa ra một interface ( ​IOFileFilter​) kết hợp của cả
2 interface: ​java.io.FileFilter và ​java.io.FilenameFilter.​ Bên cạnh đó nó có sẵn một loạt các class
thực hiện (implements) ​IOFileFilter đ ​ ể bạn sẵn sàng sử dụng, và nó cũng có class ( ​FileFilterUtils​)
tiện ích, cho phép bạn kết hợp các bộ lọc (filters) đó với nhau để tạo ra bộ lọc mới. Chúng được sử
dụng để lọc danh sách file theo yêu cầu của bạn hoặc sử dụng trong FileDialog

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/packa
ge-summary.html
Ví dụ, ​java.io.FileFilter có thể được dùng để bạn lọc lấy ra các ​File ​theo ý bạn trong 1 thư mục nào
đó. Nhưng sẽ là tốt hơn nếu bạn sử dụng các lớp có trong package
org.apache.commons.io.filefilter​. Nó có nhiều cái viết sẵn cho bạn, và chỉ cần sử dụng.

Hãy xem một ví dụ không sử dụng org.apache.commons.io.filefilter

FileFilterExample1.java

?
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
public class FileFilterExample1 {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 FileFilter filter = new MyFileFilter();
24
25
26
27
File dir = new File("C:/test");
28
29
30
31
32 // Lấy ra danh sách file có phần mở rộng js hoặc css
33
34
File[] list = dir.listFiles(filter);
35

for (File file : list) {


System.out.println("File " + file.getAbsolutePath());

// Bộ lọc chấp nhận các file kiểu (*.js , *.css)

static class MyFileFilter implements FileFilter {

public boolean accept(File pathname) {

String abstractPath = pathname.getAbsolutePath();

if (abstractPath.endsWith(".js") || abstractPath.endsWith(".css")) {

return true;

return false;

}
}

Và ví dụ sử dụng class SuffixFileFilter​, nằm trong package org.apache.commons.io.filefilter

HiddenFileFilterExample.java

1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9
10
11 import org.apache.commons.io.filefilter.HiddenFileFilter;
12
13
14
15
16 public class HiddenFileFilterExample {
17

public static void main(String[] args) {

File dir = new File("C:/test");

String[] files = dir.list(HiddenFileFilter.HIDDEN);

for (int i = 0; i < files.length; i++) {

System.out.println(files[i]);

}
}

FileFilterExample2.java

1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
import org.apache.commons.io.filefilter.SuffixFileFilter;
14
15
16
17
18 public class FileFilterExample2 {
19
20
21
22
23 public static void main(String[] args) {

String[] suffixs = new String[] { ".js", ".css" };

FileFilter filter = new SuffixFileFilter(suffixs);

File dir = new File("C:/test");


// Danh sách các file có phần mở rộng js hoặc css nằm trong thư mục C:/test

File[] list = dir.listFiles(filter);

for (File file : list) {

System.out.println("File " + file.getAbsolutePath());

Ví dụ kết hợp 2 bộ lọc với nhau:

CombineTwoFilterExample.java

?
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
import org.apache.commons.io.filefilter.FileFilterUtils;
14
15
16 import org.apache.commons.io.filefilter.HiddenFileFilter;
17
18 import org.apache.commons.io.filefilter.IOFileFilter;
19
20
import org.apache.commons.io.filefilter.SuffixFileFilter;
21
22
23
24
25 public class CombineTwoFilterExample {
26
27
28
29
30 public static void main(String[] args) {
31
32
33
34
String[] suffixs = new String[] { ".js", ".css" };

IOFileFilter filter1 = new SuffixFileFilter(suffixs);

//
IOFileFilter filter2 = HiddenFileFilter.VISIBLE;

//

// Bộ lọc mới chấp nhận các file có đuôi js, css và phải là file không ẩn.

IOFileFilter newFilter = FileFilterUtils

.andFileFilter(filter1, filter2);

File dir = new File("C:/test");

File[] list = dir.listFiles((FileFilter) newFilter);

for (File file : list) {

System.out.println("File " + file.getAbsolutePath());

10- File comparators (Bộ so sánh File)


Package ​org.apache.commons.io.comparator cung cấp một số class thực hiện
java.util.Comparator cho ​java.io.File​. Các bộ so sánh (comparators) này có thể dùng để sắp xếp
danh sách hoặc một mảng các file.

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/comparator/p
ackage-summary.html

SizeFileComparatorExample.java

?
1
2 package org.o7planning.tutorial.commonsio.comparator;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11 import java.util.Arrays;
12
13
14
15
16 import org.apache.commons.io.FileUtils;
17
18 import org.apache.commons.io.comparator.SizeFileComparator;
19
20
21
22
23 public class SizeFileComparatorExample {
24
25
26
27
public static void main(String[] args) throws IOException {
28
29
30 // Thư mục hiện tại (Thư mục của project)
31
32 File directory = new File(".");
33
34
File[] files = directory.listFiles();
35
36
37
38
39 System.out.println("Sap xep mac dinh");
40
41
42
43 displayFiles(files);
44
45
46
47
Arrays.sort(files, SizeFileComparator.SIZE_COMPARATOR);
48
49
50 System.out
51
52 .println("\nSizeFileComparator.SIZE_COMPARATOR (Tang dan, thu muc coi
53 nhu kich thuoc bang 0)");
54
55
displayFiles(files);
56
57
58
59
60 Arrays.sort(files, SizeFileComparator.SIZE_REVERSE);

System.out

.println("\nSizeFileComparator.SIZE_REVERSE (Giam dan, thu muc coi nhu


kich thuoc bang 0)");

displayFiles(files);

Arrays.sort(files, SizeFileComparator.SIZE_SUMDIR_COMPARATOR);

System.out

.println("\nSizeFileComparator.SIZE_SUMDIR_COMPARATOR (Tang dan,


su dung kich thuoc thu muc)");

displayFilesWithDirectorySizes(files);
Arrays.sort(files, SizeFileComparator.SIZE_SUMDIR_REVERSE);

System.out

.println("\nSizeFileComparator.SIZE_SUMDIR_REVERSE (Giam dan, su


dung kich thuoc thu muc)");

displayFilesWithDirectorySizes(files);

public static void displayFiles(File[] files) {

for (File file : files) {

System.out.printf("%-20s Size:" + file.length() + "\n",

file.getName());

public static void displayFilesWithDirectorySizes(File[] files) {

for (File file : files) {

if (file.isDirectory()) {
System.out.printf(

"%-20s Size:" + FileUtils.sizeOfDirectory(file) + "\n",

file.getName());

} else {

System.out.printf("%-20s Size:" + file.length() + "\n",

file.getName());

Kết quả chạy class SizeFileComparatorExample​:


?

1
2 Sap xep mac dinh
3
4 .classpath Size:1431
5
6
.project Size:569
7
8
9 .settings Size:4096
10
11 pom.xml Size:547
12
13
src Size:0
14
15
16 target Size:0
17
18 test.txt Size:0
19
20
21
22
23 SizeFileComparator.SIZE_COMPARATOR (Tang dan, thu muc coi nhu kich thuoc
24 bang 0)
25
26 .settings Size:4096
27
28
src Size:0
29
30
31 target Size:0
32
33 test.txt Size:0
34
35
pom.xml Size:547
36
37
38 .project Size:569
39
40
41 .classpath Size:1431
42
43
44
45
SizeFileComparator.SIZE_REVERSE (Giam dan, thu muc coi nhu kich thuoc bang 0)

.classpath Size:1431

.project Size:569

pom.xml Size:547

.settings Size:4096

src Size:0

target Size:0

test.txt Size:0

SizeFileComparator.SIZE_SUMDIR_COMPARATOR (Tang dan, su dung kich thuoc


thu muc)

test.txt Size:0

.settings Size:489

pom.xml Size:547

.project Size:569

.classpath Size:1431
src Size:11611

target Size:22459

SizeFileComparator.SIZE_SUMDIR_REVERSE (Giam dan, su dung kich thuoc thu


muc)

target Size:22459

src Size:11611

.classpath Size:1431

.project Size:569

pom.xml Size:547

.settings Size:489

test.txt Size:0

11- Streams (Luồng vào ra dữ liệu)


Package ​org.apache.commons.io.input và ​org.apache.commons.io.output chứa một vài các class
xử lý vào ra dữ liệu. Chúng bao gồm:

● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/package
-summary.html
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/packag
e-summary.html

Xem thêm các chuyên mục:

Apache Org
Java cơ bản
Mục lục

1- ​Giới thiệu

2- ​Thư viện

3- ​Tạo Project

4- ​Chú ý cho Gmail

5- ​Ví dụ gửi email đơn giản

6- ​Gửi Email có đính kèm

7- ​Gửi Email có định dạng HTML

8- ​Gửi một Email có định dạng HTML, nhúng thêm ảnh

9- ​Phụ lục: Download thư viện Commons Email

Apache Org
Java cơ bản

Hướng dẫn sử dụng Java Commons Email

Xem thêm các chuyên mục:

Apache Org
Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ iới thiệu
1- G

​ hư viện
2- T

​ ạo Project
3- T
4- ​Chú ý cho Gmail

​ í dụ gửi email đơn giản


5- V

​ ửi Email có đính kèm


6- G

​ ửi Email có định dạng HTML


7- G

​ ửi một Email có định dạng HTML, nhúng thêm ảnh


8- G

​ hụ lục: Download thư viện Commons Email


9- P

1- Giới thiệu

Commons Email là một thư viện Java của Apache liên quan tới Email. Trong thực tế để làm việc với
Java Email bạn có thể sử dụng ​JavaMail API đã được tích hợp sẵn trong ​JDK6​. ​Commons Email
đơn giản chỉ là giúp bạn làm việc với ​JavaMail API dễ dàng hơn, nó không thay thế cho ​JavaMail
API​.

Cũng giống như ​Commons IO không thay thế cho J ​ avaIO mà chỉ bao gồm nhiều class, method tiện
ích để bạn làm việc với Java IO​ dễ dàng hơn, tiết kiệm thời gian code cho bạn.

2- Thư viện

● http://mvnrepository.com/artifact/org.apache.commons/commons-email
Maven:

** pom.xml **

1
2 <!--​ ​http://mvnrepository.com/artifact/org.apache.commons/commons-email​ -->
3
4
5
6
<dependency>
7

<groupId>org.apache.commons</groupId>

<artifactId>commons-email</artifactId>

<version>1.3.2</version>

</dependency>
Xem thêm:

● Hướng dẫn sử dụng Spring Email

3- Tạo Project
Tạo một Maven Project dùng cho việc test các ví dụ trong tài liệu này. Bạn có thể tạo một Project
thông thường, sau đó download thư viện và khai báo vị trí của chúng theo cách thông thường.

Nếu bạn sử dụng ​Commons Email trong một project thông thường, bạn cần download các thư viện
cần thiết, bạn có thể xem ở phụ lục ở cuối tài liệu.
Đây là hình ảnh Project được tạo ra.

Khai báo các thư viện sẽ sử dụng trong pom.xml

pom.xml

?
1
2 <project xmlns="​http://maven.apache.org/POM/4.0.0​"
3
4 xmlns:xsi="​http://www.w3.org/2001/XMLSchema-instance​"
5
6
xsi:schemaLocation="​http://maven.apache.org/POM/4.0.0
7
8
9 ​http://maven.apache.org/xsd/maven-4.0.0.xsd​">
10
11
12
13
<modelVersion>4.0.0</modelVersion>
14
15
16 <groupId>org.o7planning</groupId>
17
18 <artifactId>CommonsEmailTutorial</artifactId>
19
20
<version>0.0.1-SNAPSHOT</version>
21

<dependencies>

<!--​ ​http://mvnrepository.com/artifact/org.apache.commons/commons-email​ -->

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-email</artifactId>

<version>1.4</version>
</dependency>

</dependencies>

</project>

4- Chú ý cho Gmail


Nếu muốn bạn gửi email từ ứng dụng ​Java ​sử dụng ​Gmail​, bạn cần cho phép:ứng dụng ít bảo mật
hơn (Allow less secure apps):

Trên trình duyệt đăng nhập vào Gmail c​ ủa ban, và truy cập đường dẫn sau:

● https://www.google.com/settings/security/lesssecureapps

Bạn sẽ nhận được một cảnh báo của Google:

Một số ứng dụng và thiết bị sử dụng công nghệ đăng nhập ít bảo mật hơn, làm cho tài khoản của
bạn dễ bị tổn thương hơn. Bạn có thể tắt quyền ( T ​ urn Off)​ truy cập cho các ứng dụng này mà
chúng tôi đề xuất hoặc bật quyền ( Turn On​) truy cập nếu bạn muốn sử dụng chúng bất chấp rủi ro.
5- Ví dụ gửi email đơn giản

Trước hết là một ví dụ gửi một Email đơn giản với Commons-Email
Constants.java

1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
public class Constants {
7
8
9
10
11

public static final String MY_EMAIL = "yourEmail@gmail.com";

public static final String MY_PASSWORD ="your password";

public static final String FRIEND_EMAIL = "friendEmail@gmail.com";

SimpleTextEmail.java

?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import org.apache.commons.mail.DefaultAuthenticator;
7
8
9 import org.apache.commons.mail.Email;
10
11 import org.apache.commons.mail.SimpleEmail;
12
13
14
15
16 public class SimpleTextEmail {
17
18
19
20
public static void main(String[] args) {
21
22
23 try {
24
25 Email email = new SimpleEmail();
26
27
28
29
30 // Cấu hình thông tin Email Server
31
32 email.setHostName("smtp.googlemail.com");
33
34
email.setSmtpPort(465);
35
36
37 email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,
38
39 Constants.MY_PASSWORD));
// Với gmail cái này là bắt buộc.

email.setSSLOnConnect(true);

// Người gửi

email.setFrom(Constants.MY_EMAIL);

// Tiêu đề

email.setSubject("Test Email");

// Nội dung email

email.setMsg("This is a test mail ... :-)");

// Người nhận

email.addTo(Constants.FRIEND_EMAIL);

email.send();

System.out.println("Sent!!");
} catch (Exception e) {

e.printStackTrace();

Kết quả khi chạy ví dụ trên:

6- Gửi Email có đính kèm


Ví dụ gửi email có đính kèm một file trên ổ cứng.

EmailWithAttachment.java

?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import org.apache.commons.mail.DefaultAuthenticator;
7
8
9 import org.apache.commons.mail.EmailAttachment;
10
11 import org.apache.commons.mail.MultiPartEmail;
12
13
14
15
16 public class EmailWithAttachment {
17
18
19
20
public static void main(String[] args) {
21
22
23 try {
24
25 // Tạo một đối tượng đính kèm
26
27
EmailAttachment attachment = new EmailAttachment();
28
29
30 attachment.setPath("C:/mypictures/map-vietnam.png");
31
32 attachment.setDisposition(EmailAttachment.ATTACHMENT);
33
34
attachment.setDescription("Vietnam Map");
35
36
37 attachment.setName("Map");
38
39
40
41
42
43 // Tạo đối tượng Email
44
45 MultiPartEmail email = new MultiPartEmail();
46

// Cấu hình

email.setHostName("smtp.googlemail.com");

email.setSmtpPort(465);

email.setSSLOnConnect(true);

email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,

Constants.MY_PASSWORD));

email.setFrom(Constants.MY_EMAIL, "TRAN");

email.addTo(Constants.FRIEND_EMAIL, "Hong");

email.setSubject("The Map");

email.setMsg("Here is the map you wanted");

// Thêm đính kèm


email.attach(attachment);

// Gửi email

email.send();

System.out.println("Sent!");

} catch (Exception e) {

e.printStackTrace();

Kết quả:
Một ví dụ khác gửi Email có đính kèm file từ một liên kết (Link)

EmailWithAttachment2.java

?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.EmailAttachment;
14
15
16 import org.apache.commons.mail.MultiPartEmail;
17
18
19
20
public class EmailWithAttachment2 {
21
22
23
24
25 public static void main(String[] args) {
26
27
try {
28
29
30 // Tạo đối tượng đính kèm
31
32 EmailAttachment attachment = new EmailAttachment();
33
34
attachment.setURL(new URL(
35
36
37 "​http://www.apache.org/images/asf_logo_wide.gif​"));
38
39 attachment.setDisposition(EmailAttachment.ATTACHMENT);
40
41
42
43 attachment.setDescription("Apache logo");
44
45 attachment.setName("Apache logo");
46
47
48
49
// Tạo đối tượng email

MultiPartEmail email = new MultiPartEmail();

// Cấu hình

email.setHostName("smtp.googlemail.com");

email.setSmtpPort(465);

email.setSSLOnConnect(true);

email.setAuthenticator(new DefaultAuthenticator(

Constants.MY_EMAIL, Constants.MY_PASSWORD));

email.setFrom(Constants.MY_EMAIL, "TRAN");

email.addTo(Constants.FRIEND_EMAIL, "Hong");
email.setSubject("The logo");

email.setMsg("Here is Apache's logo");

// Thêm đính kèm

email.attach(attachment);

// Gửi email

email.send();

System.out.println("Sent!");

} catch (Exception e) {

e.printStackTrace();

Kết quả chạy ví dụ:


7- Gửi Email có định dạng HTML

SendHtmlEmail.java

?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.HtmlEmail;
14
15
16
17
18 public class SendHtmlEmail {
19
20
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
// Tạo đối tượng Email
28
29
30 HtmlEmail email = new HtmlEmail();
31
32
33
34
35
36
37 // Cấu hình
38
39 email.setHostName("smtp.googlemail.com");
40
41
42
43 email.setSmtpPort(465);
44
45 email.setAuthenticator(new DefaultAuthenticator(
46
47
Constants.MY_EMAIL,Constants.MY_PASSWORD));
48
49
50 email.setSSLOnConnect(true);
51
52 email.setFrom(Constants.MY_EMAIL, "TRAN");

// Người nhận

email.addTo(Constants.FRIEND_EMAIL);

// Tiêu đề

email.setSubject("Test Sending HTML formatted email");

// Nhúng image và lấy ra ID của nội dung (Content-ID)

URL url = new URL("​http://www.apache.org/images/asf_logo_wide.gif​");

String cid = email.embed(url, "Apache logo");


// Sét nội dung email định dạng HTML.

email.setHtmlMsg("<html><h2>The apache logo</h2> <img src=\"cid:"

+ cid + "\"></html>");

// Thiết lập các thông báo thay thế

// (Trong trường hợp chương trình đọc mail của người nhận ko hỗ trợ đọc
HTML Email)

email.setTextMsg("Your email client does not support HTML messages");

// Gửi email

email.send();

System.out.println("Sent!!");

} catch (Exception e) {

e.printStackTrace();

}
}

8- Gửi một Email có định dạng HTML, nhúng thêm ảnh

SendHtmlEmbedImageEmail.java

?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.ImageHtmlEmail;
14
15
16 import org.apache.commons.mail.resolver.DataSourceUrlResolver;
17
18
19
20
public class SendHtmlEmbedImageEmail {
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
// Mẫu nội dung Email gửi đi.
28
29
30 // Ở đây Img có đường dẫn tương đối (**)
31
32 String htmlEmailTemplate = "<h2>Hello!</h2>"
33
34
+"This is Apache Logo <br/>"
35
36
37 +"<img src='proper/commons-email/images/commons-logo.png'/>";
38
39
40
41
42
43 // Tạo đối tượng Email.
44
45 ImageHtmlEmail email = new ImageHtmlEmail();
46
47
48
49
50
51
52 // Cấu hình
53
54
email.setHostName("smtp.googlemail.com");
55

email.setSmtpPort(465);

email.setAuthenticator(new DefaultAuthenticator(

Constants.MY_EMAIL, Constants.MY_PASSWORD));

email.setSSLOnConnect(true);

email.setFrom(Constants.MY_EMAIL, "TRAN");

email.addTo(Constants.FRIEND_EMAIL);

email.setSubject("Sending HTML formatted email with embedded images");

// Định nghĩa URL cơ sở để xác định đúng vị trí nguồn dữ liệu (img,..)
// (Trong trường hợp nó có đường dẫn tương đối, ví dụ Img trên)

URL url = new URL("​http://commons.apache.org​");

email.setDataSourceResolver(new DataSourceUrlResolver(url) );

// Sét nội dung email

email.setHtmlMsg(htmlEmailTemplate);

// Sét đặt nội dung thay thế.

// (Trong trường hợp chương trình đọc email của người nhận ko hỗ trợ HTML).

email.setTextMsg("Your email client does not support HTML messages");

// Gửi email

email.send();

System.out.println("Sent!!");

} catch (Exception e) {
e.printStackTrace();

9- Phụ lục: Download thư viện Commons Email


Nếu bạn sử dụng ​Commons Email trong một project thông thường bạn cần phải download các thư
viện cần thiết. Commons Email​ dựa trên Email API​ vì vậy bạn cần download 2 thư viện:

● http://mvnrepository.com/artifact/org.apache.commons/commons-email
Tiếp theo download thư viện Email API​:

● http://mvnrepository.com/artifact/com.sun.mail/javax.mail
Cuối cùng, bạn download được 2 file jar.

Xem thêm các chuyên mục:


Apache Org
Java cơ bản
Mục lục

1- ​Commons Logging là gì?

2- ​Mục tiêu của tài liệu hướng dẫn

3- ​Commons Logging + Log4J Logger

​ hư viện (Library)
3.1- T

​ ạo project
3.2- T

​ í dụ đơn giản HelloWorld (Log ra màn hình Console)


3.3- V

​ í dụ phức tạp hơn (Log ra file)


3.4- V

Apache Org
Java cơ bản

Hướng dẫn sử dụng Java Commons Logging

Xem thêm các chuyên mục:

Apache Org
Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

1- ​Commons Logging là gì?

​ ục tiêu của tài liệu hướng dẫn


2- M

3- ​Commons Logging + Log4J Logger

3.1- ​Thư viện (Library)

3.2- ​Tạo project


3.3- ​Ví dụ đơn giản HelloWorld (Log ra màn hình Console)

3.4- ​Ví dụ phức tạp hơn (Log ra file)

1- Commons Logging là gì?


Trong ứng dụng Java của bạn, bạn muốn viết code để ghi ra thông điệp của ứng dụng trong quá trình
làm việc của nó? Bạn có thể sử dụng một trong 3 thư viện Logger​ sau:

● Log4J Logger
● Jdk14 Logger
● Simple Logger

Commons Logging là một thư viện cho phép bạn làm việc với một trong 3 bộ thư viện trên một cách
dễ dàng hơn. Như vậy để viết một chương trình ​Log​, một mình nó không thể là một ​Logger​. Một
cách tương tự bạn làm việc với ​java.io để sử lý vào ra dữ liệu, ​Commons IO là bộ thư viện viết dựa
trên ​java.io​ giúp bạn sử lý IO dễ dàng hơn, Common IO​ không thể thay thế java.io​.

Như vậy bạn có 3 lựa chọn:


Việc bạn chọn ​Logger nào không quan trọng chúng được sử lý một cách giống nhau với sự hỗ trợ
của Commons Logging​.

2- Mục tiêu của tài liệu hướng dẫn


Trong tài liệu hướng dẫn này tôi sẽ hướng dẫn bạn cách làm việc với:

● Commons Logging + Log4J Logger

3- Commons Logging + Log4J Logger

3.1- Thư viện (Library)

Thư viện Commons Logging​:

● http://mvnrepository.com/artifact/commons-logging/commons-logging
Maven:

1
2 <dependency>
3
4
<groupId>commons-logging</groupId>
5

<artifactId>commons-logging</artifactId>

<version>1.1.3</version>

</dependency>

Thư viện Log4J Logger​:


Maven:

1
2 <dependency>
3
4
<groupId>log4j</groupId>
5

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

3.2- Tạo project


pom.xml

?
1
2 <project xmlns="​http://maven.apache.org/POM/4.0.0​"
3
4
xmlns:xsi="​http://www.w3.org/2001/XMLSchema-instance​"
5
6
7 xsi:schemaLocation="​http://maven.apache.org/POM/4.0.0
8 http://maven.apache.org/xsd/maven-4.0.0.xsd​">
9
10
<modelVersion>4.0.0</modelVersion>
11
12
13 <groupId>org.o7planning</groupId>
14
15
<artifactId>CommonsLoggingTutorial</artifactId>
16
17
18 <version>0.0.1-SNAPSHOT</version>
19
20
21
22
<dependencies>

<dependency>

<groupId>commons-logging</groupId>

<artifactId>commons-logging</artifactId>

<version>1.1.3</version>

</dependency>

<dependency>

<groupId>log4j</groupId>
<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

</dependencies>

</project>

3.3- Ví dụ đơn giản HelloWorld (Log ra màn hình Console)

Trong bước này chúng ta sẽ làm một ví dụ đơn giản HelloWorld, nó sẽ ghi Log ra màn hình Console.

HelloWorld.java

?
1
2 package org.o7planning.tutorial.commonslogging;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class HelloWorld {
15
16
17

private static final Log log = LogFactory.getLog(HelloWorld.class);

public static void main(String[] args) {

log.debug("Example debug message ..");

log.info("Example info message ..");

log.warn("Example warn message ..");

log.error("Example error message ..");

log.fatal("Example fatal message ..");

}
}

commons-logging.properties

1
2 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
3

log4j.configuration=log4j.properties

log4j.properties

1
2 log4j.rootLogger=DEBUG, CA, NTEventLog
3
4
5
6
#Console Appender

log4j.appender.CA=org.apache.log4j.ConsoleAppender

log4j.appender.CA.layout=org.apache.log4j.PatternLayout

log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


Trong thực tế bạn có thể cấu hình ​Commons logging để sử dụng các thư viện ​Logging khác, không
phải log4j​:

Chạy class HelloWorld:


Với ​Log4j bạn có thể cấu hình trên file ​xml​, và việc cấu hình trên ​xml là dễ dàng và dễ hiểu hơn so
với properties​.

Mở file commons-logging.properties​ và thay đổi thành:

commons-logging.properties

1
2 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
3

log4j.configuration=log4j.xml
log4j.xml

1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="​http://jakarta.apache.org/log4j/​">
10
11
12
13
14
<appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
15
16
17 <param name="Target" value="System.out" />
18
19
20 <layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />

</layout>

</appender>
<root>

<priority value="debug" />

<appender-ref ref="MyConsole" />

</root>

</log4j:configuration>

Chạy class HelloWorld ​và xem Log trên màn hình ​Console​:

3.4- Ví dụ phức tạp hơn (Log ra file)

Tiếp theo chúng ta sẽ tiếp tục với một ví dụ phức tạp hơn, ghi Log​ ra file.
AdminApplication.java

?
1
2 package org.o7planning.tutorial.commonslogging.admin;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class AdminApplication {
15
16
17
18
19
20 private static final Log log = LogFactory.getLog(AdminApplication.class);
21
22
23
24
25 public static void main(String[] args) {
26
27 log.debug("Example debug message ..");

log.info("Example info message ..");

log.warn("Example warn message ..");

log.error("Example error message ..");

log.fatal("Example fatal message ..");


try {

raiseException();

} catch (Exception e) {

log.fatal("<Some Object>", e);

private static void raiseException() throws Exception {

throw new Exception("Test Exception");

FrontEndApplication.java

?
1
2 package org.o7planning.tutorial.commonslogging.frontend;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class FrontEndApplication {
15
16
17
18

private static final Log log = LogFactory.getLog(FrontEndApplication.class);

public static void main(String[] args) {

log.debug("Example debug message ..");

log.info("Example info message ..");

log.warn("Example warn message ..");

log.error("Example error message ..");

log.fatal("Example fatal message ..");

}
}

Cấu hình thêm vào trong log4j.xml​, thêm vào đoạn cấu hình:

1
2 <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
3
4
<param name="File" value="logs/admin.log" />
5
6
7 <layout class="org.apache.log4j.PatternLayout">
8
9
<param name="ConversionPattern"
10
11
12 value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
13
14
</layout>
15
16
17 </appender>
18
19
20
21
22 <appender name="FrontEndFileAppender" class="org.apache.log4j.FileAppender">
23
24
25 <param name="File" value="logs/frontEnd.log" />
26
27 <layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />


</layout>

</appender>

<!-- logger name phải là tên của package! -->

<logger name="org.o7planning.tutorial.commonslogging.admin">

<level value="ERROR" />

<appender-ref ref="AdminFileAppender" />

</logger>

<!-- logger name phải là tên của package! -->

<logger name="org.o7planning.tutorial.commonslogging.frontend">

<level value="DEBUG" />

<appender-ref ref="FrontEndFileAppender" />

</logger>

log4j.xml

?
1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="​http://jakarta.apache.org/log4j/​">
10
11
12
13
14
<appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
15
16
17 <param name="Target" value="System.out" />
18
19
20 <layout class="org.apache.log4j.PatternLayout">
21
22 <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
23
24
25 </layout>
26
27 </appender>
28
29
30
31
32
33
34
35
36
37
38
39
40 <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
41
42
43 <param name="File" value="logs/admin.log" />
44
45
<layout class="org.apache.log4j.PatternLayout">
46
47
48 <param name="ConversionPattern"
49
50
value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />

</layout>

</appender>

<appender name="FrontEndFileAppender" class="org.apache.log4j.FileAppender">

<param name="File" value="logs/frontEnd.log" />

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />

</layout>

</appender>

<!-- logger name phải là tên của package! -->


<logger name="org.o7planning.tutorial.commonslogging.admin">

<level value="ERROR" />

<appender-ref ref="AdminFileAppender" />

</logger>

<!-- logger name phải là tên của package! -->

<logger name="org.o7planning.tutorial.commonslogging.frontend">

<level value="DEBUG" />

<appender-ref ref="FrontEndFileAppender" />

</logger>

<root>

<priority value="debug" />

<appender-ref ref="MyConsole" />

</root>
</log4j:configuration>

Có một chú ý về thứ tự các thẻ khi bạn cấu hình log4j.xml​:

?
1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="​http://jakarta.apache.org/log4j/​">
10
11
12
13
14
<!-- render -->
15
16
17 <renderer></renderer>
18
19
20 <renderer></renderer>
21
22 <renderer></renderer>
23
24
25
26
27 <!-- appender -->
28
29
30 <appender></appender>
31
32
<appender></appender>
33
34
35 <appender></appender>
36
37
38
39
40
41
42
43 <!-- plugin -->
44
45
<plugin></plugin>
46
47
<plugin></plugin>

<plugin></plugin>

<!-- logger -->

<logger></logger>

<logger></logger>

<logger></logger>

<!-- category -->

<category></category>

<category></category>

<category></category>

<!-- root -->


<root></root>

<root></root>

<root></root>

<!-- loggerfactory -->

<loggerfactory></loggerfactory>

<loggerfactory></loggerfactory>

<loggerfactory></loggerfactory>

<!-- categoryfactory -->

<categoryfactory></categoryfactory>

<categoryfactory></categoryfactory>

<categoryfactory></categoryfactory>

</log4j:configuration>

Chạy class AdminApplication​:


Chạy class FrontEndApplication

Một thư mục logs đã được tạo ra và có 2 file log (admin.log & frontEnd.log)

Xem thêm các chuyên mục:

Apache Org
Java cơ bản
Mục lục

1- ​Ví dụ Encode và Decode

Java cơ bản

Ví dụ mã hóa và giải mã trong Java sử dụng Apache Base64 (Base64


encode/decode)

Xem thêm các chuyên mục:

Java cơ bản

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

langlearning.net

​ í dụ Encode và Decode
1- V

1- Ví dụ Encode và Decode
Một ví dụ sử dụng thư viện Apache Axis​ để mã hóa (encode) và giải mã (decode) một đoạn văn bản:

Thư viện Apache Axis​, bạn có thể download tại:

● http://mvnrepository.com/artifact/org.apache.axis/axis

Nếu bạn sử dụng Maven​:

* pom.xml *

1
2 <!--​ ​http://mvnrepository.com/artifact/org.apache.axis/axis​ -->
3
4 <dependency>
5
6
<groupId>org.apache.axis</groupId>

<artifactId>axis</artifactId>

<version>1.4</version>

</dependency>

EncodeDecodeExample.java

?
1
2 package org.o7planning.example.encode;
3
4
5
6
import java.io.UnsupportedEncodingException;
7
8
9
10
11 import org.apache.axis.encoding.Base64;
12
13
14
15
16 public class EncodeDecodeExample {
17
18
19
20
// Mã hóa một đoạn text
21
22
23 // Encode
24
25 public static String encodeString(String text)
26
27
throws UnsupportedEncodingException {
28
29
30 byte[] bytes = text.getBytes("UTF-8");
31
32 String encodeString = Base64.encode(bytes);
33
34
return encodeString;
35
36
37 }
38
39
40
// Giải mã hóa một đoạn text (Đã mã hóa trước đó).

// Decode

public static String decodeString(String encodeText)

throws UnsupportedEncodingException {

byte[] decodeBytes = Base64.decode(encodeText);

String str = new String(decodeBytes, "UTF-8");

return str;

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

String text = "Example Vietnamese text - Tiếng Việt";

System.out.println("Text before encode: "+ text);

String encodeText = encodeString(text);

System.out.println("Encode text: "+ encodeText);


String decodeText = decodeString(encodeText);

System.out.println("Decode text: "+ decodeText);

Kết quả chạy ví dụ:

Xem thêm các chuyên mục:

Java cơ bản

You might also like