0% found this document useful (0 votes)
10 views26 pages

Java I/O, Threads, and Swing Examples

The document contains code examples and explanations related to various Java programming concepts including IO, threading, Swing GUI components, and client-server communication. It covers file handling, sorting arrays, creating threads, building a Swing application with forms and tables, and implementing a TCP client-server model. Additionally, it includes a folder monitoring server application with a graphical interface for managing client connections and folder lists.

Uploaded by

Vu Vu van
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views26 pages

Java I/O, Threads, and Swing Examples

The document contains code examples and explanations related to various Java programming concepts including IO, threading, Swing GUI components, and client-server communication. It covers file handling, sorting arrays, creating threads, building a Swing application with forms and tables, and implementing a TCP client-server model. Additionally, it includes a folder monitoring server application with a graphical interface for managing client connections and folder lists.

Uploaded by

Vu Vu van
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MỤC LỤC

IO...................................................................................................................................1
Thread...........................................................................................................................3
Swing.............................................................................................................................4
Message Between Client / Server (TCP).....................................................................8
Folder Monitor...........................................................................................................10
UDP..............................................................................................................................15
URL Direct..................................................................................................................17
Copy File/Folder to Other Folder.............................................................................18
Send File......................................................................................................................20
JDBC...........................................................................................................................22
Unicode........................................................................................................................23
Exception.....................................................................................................................26

IO

package ExamPrac;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Exer6 {
public static void main(String[] args) {
createFiles();
sortArrAndWrite();
test();
}
public static void sortArrAndWrite(){
try(
DataInputStream inA = new DataInputStream(new FileInputStream("[Link]"));
DataInputStream inB = new DataInputStream(new FileInputStream("[Link]"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("[Link]"));
)
{

1
int M = [Link]();
int N = [Link]();
int []arr = new int[M + N];
for(int i = 0 ; i < M; i++){
arr[i] = [Link]();
}
for(int i = 0; i < N; i++){
arr[M + i] = [Link]();
}
[Link](arr);
[Link](M + N);
for(int i = 0; i < M + N; i++){
[Link](arr[i]);
}
} catch(IOException e){
[Link]();
}
}
public static void createFiles(){
Random rand = new Random();

try(
DataOutputStream dos1 = new DataOutputStream(new
FileOutputStream("[Link]"));
DataOutputStream dos2 = new DataOutputStream(new
FileOutputStream("[Link]"));
){
int N = 5;
int M = 6;
[Link](N);
[Link](M);
for(int i = 0; i < N; i++){
[Link]([Link](1000));
}
for(int i = 0; i < M; i++){
[Link]([Link](1000));
}
} catch(IOException e){
[Link]();
}
}
public static void test() {
try (
DataInputStream dis = new DataInputStream(new FileInputStream("[Link]"))
){
int total = [Link]();
[Link]("N + M = " + total);
for (int i = 0; i < total; i++) {

2
[Link]("So " + (i + 1) + ": " + [Link]());
}
} catch (IOException e) {
[Link]();
}
}
}
//writeint -> 4 byte, write-> 1 byte
//binary -> consecutive, writeInt and readInt or other values to get value, no read line ,
so use DataInputStream , DataOutputStream with FileInput/OutputStream

Thread

package ExamPrac;

public class Exer12 {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link](); // tạo luồng mới
[Link]();
}
}
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + " - " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

class MyRunnable implements Runnable {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " - " + i);
try {
[Link](500);
} catch (InterruptedException e) {

3
[Link]();
}
}
}
}

public class Main {


public static void main(String[] args) {
Runnable task = new MyRunnable();
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
[Link]();
[Link]();
}
}

Swing

import [Link].*;
import [Link].*;

public class Prac extends JPanel {


public Prac() {
setLayout(new BorderLayout());
// --- Top panel ---
JPanel topPanel = new JPanel(new FlowLayout([Link], 10, 10));
JLabel districtLabel = new JLabel("Choose District:");
String[] districts = {"District 1", "District 2", "District 3", "District 4", "District
5"};
JComboBox<String> cbbox = new JComboBox<>(districts);
[Link](districtLabel);
[Link](cbbox);
add(topPanel, BorderLayout.PAGE_START);
// --- Scrollable list ---
String[] districtWards = {"Ben Thanh", "Da Kao", "Ben Nghe"};
JList<String> list = new JList<>(districtWards);
JScrollPane wardScroll = new JScrollPane(list);
[Link](new Dimension(200, 100));
add(wardScroll, [Link]);
// Bottom Panel
JPanel bottomPanel = new JPanel();
[Link](new BoxLayout(bottomPanel,
BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("OK");
JButton cancelBtn = new JButton("Cancel");

4
[Link](e -> OK());
[Link](okBtn);
[Link]([Link](new Dimension(30,0)));
[Link](cancelBtn);
JPanel bottomPanel2 = new JPanel();
[Link](new BoxLayout(bottomPanel2,
BoxLayout.PAGE_AXIS));
[Link]([Link](new Dimension(0,5)));
[Link](bottomPanel);
[Link]([Link](new Dimension(0,5)));
add(bottomPanel2,BorderLayout.PAGE_END);
}
private static void OK(){
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("District and Wards");
[Link](JFrame.EXIT_ON_CLOSE);
// Add your panel to the frame
[Link](new Prac());
[Link]();
[Link]("Provider");
[Link](null); // center on screen
[Link](true);
}
public static void main(String[] args) {
// Always run GUI code on the Event Dispatch Thread
[Link](() -> createAndShowGUI());
}
}

package ExamPrac;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;

public class Exer14 extends JFrame {


CardLayout cardLayout = new CardLayout();
JPanel centerPanel = new JPanel(cardLayout);
JProgressBar progressBar = new JProgressBar(0, 100);
Timer timer;
public Exer14() {
setTitle("Swing All Components Demo");
setSize(900, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setJMenuBar(createMenu());

5
add(createLeftMenu(), [Link]);
add(centerPanel, [Link]);
add(createStatusBar(), [Link]);
[Link](createFormPanel(), "FORM");
[Link](createListTablePanel(), "DATA");
[Link](createProgressPanel(), "PROGRESS");
}
/* ================= MENU ================= */
JMenuBar createMenu() {
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
[Link](e -> [Link](0));
[Link](exit);
[Link](file);
return bar;
}
/* ================= LEFT MENU ================= */
JPanel createLeftMenu() {
JPanel panel = new JPanel();
[Link](new BoxLayout(panel, BoxLayout.Y_AXIS));
[Link](new Dimension(150, 0));
JButton btnForm = new JButton("Form");
JButton btnData = new JButton("List & Table");
JButton btnProgress = new JButton("Progress");
[Link](e -> [Link](centerPanel, "FORM"));
[Link](e -> [Link](centerPanel, "DATA"));
[Link](e -> [Link](centerPanel,
"PROGRESS"));
[Link](btnForm);
[Link](btnData);
[Link](btnProgress);
return panel;
}
/* ================= FORM PANEL ================= */
JPanel createFormPanel() {
JPanel panel = new JPanel(new GridLayout(8, 2, 5, 5));
JTextField txtName = new JTextField();
JPasswordField txtPass = new JPasswordField();
JTextArea txtNote = new JTextArea(3, 10);
JCheckBox cbJava = new JCheckBox("Java");
JCheckBox cbPython = new JCheckBox("Python");
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup gender = new ButtonGroup();
[Link](male);
[Link](female);

6
JComboBox<String> combo = new JComboBox<>(new String[]{"IT",
"Business", "Design"});
JButton submit = new JButton("Submit");
[Link](e ->
[Link](this,
"Name: " + [Link]())
);
[Link](new JLabel("Name:"));
[Link](txtName);
[Link](new JLabel("Password:"));
[Link](txtPass);
[Link](new JLabel("Note:"));
[Link](new JScrollPane(txtNote));
[Link](new JLabel("Skills:"));
[Link](new JPanel(new FlowLayout()) {{
add(cbJava);
add(cbPython);
}});
[Link](new JLabel("Gender:"));
[Link](new JPanel(new FlowLayout()) {{
add(male);
add(female);
}});
[Link](new JLabel("Major:"));
[Link](combo);
[Link](new JLabel());
[Link](submit);
return panel;
}
/* ================= LIST + TABLE ================= */
JPanel createListTablePanel() {
JPanel panel = new JPanel(new GridLayout(1, 2));
JList<String> list = new JList<>(new String[]{"Apple", "Banana", "Orange"});
[Link](new JScrollPane(list));
String[] cols = {"ID", "Name"};
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
[Link](new Object[]{1, "Java"});
[Link](new Object[]{2, "Python"});
[Link](new JScrollPane(table));
return panel;
}
/* ================= PROGRESS ================= */
JPanel createProgressPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton start = new JButton("Start");
[Link](true);
[Link](e -> {

7
[Link](0);
timer = new Timer(100, new ActionListener() {
int value = 0;
public void actionPerformed(ActionEvent e) {
value += 5;
[Link](value);
if (value >= 100) [Link]();
}
});
[Link]();
});
[Link](progressBar, [Link]);
[Link](start, [Link]);
return panel;
}
/* ================= STATUS BAR ================= */
JPanel createStatusBar() {
JPanel panel = new JPanel(new FlowLayout([Link]));
[Link](new JLabel("Ready"));
return panel;
}
public static void main(String[] args) {
[Link](() ->
new Exer14().setVisible(true)
);
}
}

Message Between Client / Server (TCP)

package ExamPrac.Exer11;

import [Link].*;
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
try (
Socket socket = new Socket("localhost", 3000);
BufferedReader br = new BufferedReader(
new InputStreamReader([Link]()));
BufferedWriter bw = new BufferedWriter(

8
new OutputStreamWriter([Link]()));
Scanner scanner = new Scanner([Link])
){
[Link]("Connected to server");
while (true) {
[Link]("You: ");
String message = [Link]();
[Link](message);
[Link]();
[Link]();
//wait until server reply
String reply = [Link]();
if (reply == null) {
[Link]("Server disconnected");
break;
}
[Link]("Server: " + reply);
}
} catch (Exception e) {
[Link]();
}
}
}

package ExamPrac.Exer11;

import [Link].*;
import [Link];
import [Link];
public class ClientHandler implements Runnable {
private Socket socket;
// CHỈ 1 Scanner dùng chung cho server
private static final Scanner scanner = new Scanner([Link]);
public ClientHandler(Socket socket) {
[Link] = socket;
}
@Override
public void run() {
try (
BufferedReader br = new BufferedReader(
new InputStreamReader([Link]()));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter([Link]()))
){

while(true){
String message = [Link]();
[Link]("Client: " + message)

9
[Link]("Server: ");
String reply = [Link]();
[Link](reply);
[Link]();
[Link]();
}

} catch (IOException e) {
[Link]("Client disconnected");
}
}
}

package ExamPrac.Exer11;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
public static void main(String[] args) {
try(ServerSocket ss = new ServerSocket(3000)){
[Link]("Server start at port 3000....");
while(true){
Socket s = [Link]();
[Link]("New client come");
new Thread(new ClientHandler(s)).start();
}
} catch(Exception e){
[Link]();
}
}
}
//javac ExamPrac/Exer11/[Link]
//java [Link]

Folder Monitor

import [Link].*;
import [Link].*;
import [Link];
import [Link];

10
import [Link].*;

//javac -cp [Link] [Link] [Link] [Link]


//java -cp .;[Link] Client
//java -cp .;[Link] Server
public class Server {
private JFrame frame;
private JTextArea logArea;
private DefaultListModel<String> clientListModel;
private JList<String> clientList;
private DefaultListModel<String> folderListModel;
private JList<String> folderList;
private Map<String, ClientHandler> clients = new HashMap<>();
private Map<String, List<String>> clientFolders = new HashMap<>();

private final Map<String, Long> dedup = new HashMap<>();


public static void main(String[] args) throws Exception {
new Server().start();
}
public void start() throws Exception {
frame = new JFrame("Folder Monitor Server");
[Link](800, 600);
[Link](JFrame.EXIT_ON_CLOSE);
logArea = new JTextArea();
[Link](false);
clientListModel = new DefaultListModel<>();
clientList = new JList<>(clientListModel);
folderListModel = new DefaultListModel<>();
folderList = new JList<>(folderListModel);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(clientList),
new JScrollPane(folderList));
[Link](200);
[Link]().add(splitPane, "West");
[Link]().add(new JScrollPane(logArea), "Center");
[Link](true);
[Link](e -> {
String selectedClient = [Link]();
[Link]();
if (selectedClient != null) {
List<String> folders = [Link](selectedClient);
[Link](folderListModel::addElement);
}
});
[Link](e -> {
if ([Link]()) return;
String selectedClient = [Link]();
String selectedFolder = [Link]();

11
if (selectedClient != null && selectedFolder != null) {
ClientHandler ch = [Link](selectedClient);
Map<String, String> cmd = new HashMap<>();
[Link]("type", "watchFolder");
[Link]("folder", selectedFolder);
[Link](cmd);
log("Watching folder " + selectedFolder + " on client " + selectedClient);
}
});
ServerSocket serverSocket = new ServerSocket(9999);
log("Server started on port 9999");
while (true) {
Socket clientSocket = [Link]();
ClientHandler ch = new ClientHandler(clientSocket, this);
new Thread(ch).start();
}
}
public void addClient(ClientHandler ch, List<String> folders) {
[Link]([Link](), ch);
[Link]([Link](), folders);
[Link]([Link]());
log("Client connected: " + [Link]());
}
public void removeClient(ClientHandler ch) {
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
log("Client disconnected: " + [Link]());
}
public void logEvent(Map<String, Object> event) {
String key = [Link]("event") + ":" + [Link]("path");
long now = [Link]();
Long last = [Link](key);
if (last != null && now - last < 200) {
return; // skip duplicate
}
[Link](key, now);

String msg = [Link]("time") + " | " + [Link]("clientName") + " | "


+ [Link]("event") + " | " + [Link]("path");
log(msg);
}
private void log(String msg) {
[Link](() -> [Link](msg + "\n"));
}
}

12
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];

public class ClientHandler implements Runnable {


private Socket socket;
private Gson gson = new Gson();
private Server server;
private String clientName;
private PrintWriter out;
public ClientHandler(Socket socket, Server server) {
[Link] = socket;
[Link] = server;
}
public String getClientName() {
return clientName;
}
public void sendCommand(Map<String, String> cmd) {
[Link]([Link](cmd));
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
out = new PrintWriter([Link](), true);
String line;
while ((line = [Link]()) != null) {
Map<String, Object> msg = [Link](line, [Link]);
String type = (String) [Link]("type");
if ("folderList".equals(type)) {
clientName = (String) [Link]("clientName");
[Link](this, (List<String>) [Link]("folders"));
} else if ("event".equals(type)) {
[Link](msg);
}
}
} catch (Exception e) {
[Link](this);
}
}
}

import [Link];
import [Link].*;
import [Link];

13
import [Link].*;
import [Link];
import [Link].*;

public class Client {


private static final String SERVER_IP = "[Link]";
private static final int SERVER_PORT = 9999;
private static Gson gson = new Gson();
public static void main(String[] args) throws Exception {
String clientName = "CLIENT 02";
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
List<String> allFolders = getRootFolders();
Map<String, Object> folderMsg = new HashMap<>();
[Link]("type", "folderList");
[Link]("clientName", clientName);
[Link]("folders", allFolders);
[Link]([Link](folderMsg));
new Thread(() -> {
try {
String line;
while ((line = [Link]()) != null) {
Map<String, String> cmd = [Link](line, [Link]);
if ("watchFolder".equals([Link]("type"))) {
String folder = [Link]("folder");
[Link]("Start watching folder: " + folder);
watchFolder(folder, out, clientName);
}
}
} catch (Exception e) {
[Link]();
}
}).start();
}
// Get all root drives (Windows: C:\, D:\ ... ; Linux/Mac: /)
private static List<String> getRootFolders() {
List<String> roots = new ArrayList<>();
File[] drives = [Link]();
for (File f : drives) {
[Link]([Link]());
}
return roots;
}
private static void watchFolder(String folderPath, PrintWriter out, String
clientName) throws IOException {
Path folder = [Link](folderPath);

14
WatchService watchService = [Link]().newWatchService();
[Link](
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY
);
new Thread(() -> {
try {
while (true) {
WatchKey key = [Link]();
for (WatchEvent<?> event : [Link]()) {
Map<String, String> msg = new HashMap<>();
[Link]("type", "event");
[Link]("clientName", clientName);
[Link]("event", [Link]().name());
[Link]("path", [Link]((Path) [Link]()).toString());
[Link]("time", [Link]().toString());
[Link]([Link](msg));
}
[Link]();
}
} catch (Exception e) {
[Link]();
}
}).start();
}
}

UDP

import [Link].*;
import [Link].*;

class UDPClient1
{
public static void main(String[] args)
{
try
{
byte[] receivedBuf = new byte[100];
DatagramSocket utpSocket = new DatagramSocket(3400);

15
DatagramPacket receivedPacket = new DatagramPacket(receivedBuf,
[Link]);

[Link](receivedPacket);

[Link]("Received : " + new String(receivedBuf));


String sentMessage = "I had received your message";
byte[] sentBuf = new byte[100];
sentBuf = [Link]("ascii");

InetAddress add = [Link]("localhost");


DatagramPacket sentPacket = new DatagramPacket(sentBuf, [Link],
add, 3500);
[Link](sentPacket);
[Link]("Sent : " + sentMessage);
}
catch(Exception e)
{
[Link]();
}
}
}

import [Link].*;
import [Link].*;

class UDPClient2
{
public static void main(String[] args)
{
try
{
byte[] sentBuf = new byte[100];
String sentMessage = "Hello, there !";
[Link](" Sent : " + sentMessage);

InetAddress sentHost = [Link]("localhost");


DatagramSocket utpSocket = new DatagramSocket(3500);

sentBuf = [Link]("ascii");
DatagramPacket sentPacket = new DatagramPacket(sentBuf, [Link],
sentHost, 3400);

[Link](sentPacket);

byte[] receivedBuf = new byte[100];

16
DatagramPacket receivedPacket = new DatagramPacket(receivedBuf,
[Link]);
[Link](receivedPacket);
[Link](" Received : " + new String(receivedBuf));
}
catch (Exception e)
{
[Link]();
}
}
}

URL Direct

import [Link].*;
import [Link].*;

public class URLDirect


{
public static void main(String[] args)
{
try
{
URL url = new URL("[Link]
toi-khong-cam-thay-gi-ca-CkQT3IMydOo0");
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
String inputLine;
while ((inputLine = [Link]()) != null)
[Link](inputLine);
[Link]();
}
catch (MalformedURLException mue)
{
[Link]("Check your URL");
}
catch (IOException ioe)
{
[Link]("Check your IO stream");
}
}
}

17
Copy File/Folder to Other Folder

package ExamPrac;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Exer7 {
static JTextField src = null;
static JTextField dest = null;
static JLabel progress = null;
static long copiedBytes = 0;
public static void main(String[] args) {
[Link](() -> new Exer7().createUI());
}
public void createUI(){
JFrame frame = new JFrame();
[Link](300,300);
[Link](JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel(new GridLayout(2,3, 10,20));
src = new JTextField();
dest = new JTextField();
[Link](new JLabel("Source:"));
[Link](src);
[Link](new JLabel("Destination:"));
[Link](dest);
JButton download = new JButton("Download");
[Link](e -> copyFile());
progress = new JLabel("0%");

18
JPanel panel2 = new JPanel();
[Link](new BoxLayout(panel2, BoxLayout.Y_AXIS));
[Link](download);
[Link](progress);
JPanel panel3 = new JPanel(new FlowLayout([Link]));
[Link](panel2);

[Link](panel1, [Link]);
[Link](panel3, [Link]);
[Link](null);
[Link](true);
}
public static void copyFile(){
//check src dest exist
String sourcePath = [Link]();
String destPath = [Link]();
File source = new File(sourcePath);
File dest = new File(destPath);
if(![Link]() || ![Link]()){
[Link]("Source or dest not exist");
return;
}
//check dest is folder
if(![Link]()){
[Link]("Destination is not dir");
return;
}
//copy
long totalSize = getFoldersSize(source);
copiedBytes = 0;
File rootDest = new File(dest, [Link]());
[Link]();

new Thread(() -> {


copyHelper(source, rootDest, totalSize);
[Link]("Copy done!");
[Link]("0%");

}).start();
}
public static void copyHelper(File src, File des, long totalSize ){
try{
if([Link]()){
[Link]([Link](), [Link]());
copiedBytes += [Link]();
int percent = (int) (copiedBytes * 100 / totalSize);

19
[Link]([Link](percent) + "%");
}
else{
if(![Link]()) [Link]();
File []files = [Link]();
for(File f : files){
copyHelper(f, new File(des, [Link]()), totalSize);
}
}
} catch(IOException e){
[Link]();
}
}
public static long getFoldersSize(File file){
if([Link]()) return [Link]();
long size = 0;
File []files = [Link]();
for(File f : files){
size += getFoldersSize(f);
}
return size;
}
}

Send File

package ExamPrac.Exer13;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
public static void main(String[] args) {
File file = new File("[Link]");
try(
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = [Link]();
DataOutputStream dos =
new DataOutputStream([Link]());
FileInputStream fis =
new FileInputStream(file);
){
// 1. gửi tên file
[Link]([Link]());

20
// 2. gửi kích thước file
[Link]([Link]());

// 3. gửi dữ liệu file


byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
}
catch(Exception e){
[Link]();
}
}
}

package ExamPrac.Exer13;

import [Link];
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
try (
Socket socket = new Socket("localhost", 9999);
DataInputStream dis =
new DataInputStream([Link]());
){
// 1. Read file name
String fileName = [Link]();
// 2. Read file size
long fileSize = [Link]();
// 3. Create output file
try (FileOutputStream fos =
new FileOutputStream("received_" + fileName)) {
byte[] buffer = new byte[4096];
long received = 0;
int bytesRead;
// 4. Read file data
while (received < fileSize &&
(bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
received += bytesRead;
}
[Link]("File received successfully!");
}
} catch (Exception e) {
[Link]();

21
}
}
}
//javac ExamPrac/Exer13/[Link]
//java [Link]

JDBC

import [Link].*;

public class Prac {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/shop_db";
String user = "root";
String password = "Vuzdapoet1234";
try (Connection con = [Link](url, user, password)) {
[Link]("[Link]");
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM Students");
while ([Link]()) {
[Link]([Link](1) + " - " + [Link](2));
}
PreparedStatement ps =
[Link]("INSERT INTO Students(StudentID,
StudentName) VALUES (?, ?)");
[Link](1, "2000");
[Link](2, "Vu");
[Link]();
CallableStatement cs =
[Link]("{CALL insertStudent(?, ?)}");
[Link](1, "3000");
[Link](2, "Ha");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

22
Unicode

import [Link];
import [Link];

public class Vietnamese4{


public static void main(String[] args) {
String s1 = "vũ";
String s2 = "vũ";
Collator col = [Link](new Locale("vi"));
int ret = [Link](s1,s2);
[Link](ret);
}
}

import [Link].*;
import [Link];

// String s1 = "Đat";
// String s2 = "Minh";
// Collator collator = [Link](new Locale("vi"));
// int t1 = [Link](s1, s2);
// [Link](t1);

public class Vietnamese3 {


// ============================
// DETECT ENCODING BY BOM
// ============================
public static String detectEncoding(String filename) {
try (InputStream is = new FileInputStream(filename)) {
byte[] bom = new byte[3];
int read = [Link](bom);
if (read >= 2) {
if ((bom[0] & 0xFF) == 0xFF && (bom[1] & 0xFF) == 0xFE)
return "UTF-16LE";
if ((bom[0] & 0xFF) == 0xFE && (bom[1] & 0xFF) == 0xFF)
return "UTF-16BE";
}
if (read == 3) {
if ((bom[0] & 0xFF) == 0xEF &&
(bom[1] & 0xFF) == 0xBB &&
(bom[2] & 0xFF) == 0xBF)
return "UTF-8";
}
} catch (Exception e) {
[Link]();

23
}
return "UTF-8"; // no BOM → assume UTF-8
}
// ============================
// SAVE WITH ENCODING
// ============================
public static void saveWithEncoding(String filename, String encoding) {
try {
String content = readFile(filename);
String outName = filename + "_" + encoding + ".txt";
OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(outName), encoding);
[Link]("ufeff");
[Link](content);
[Link]();
[Link]("Saved to: " + outName + " with encoding: " + encoding);
} catch (Exception e) {
[Link]("Error saving file: " + [Link]());
}
}
// ============================
// READ FILE AS UTF-8 TEXT
// ============================
public static String readFile(String filename) {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(filename), "UTF-8"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line).append("\n");
}
} catch (Exception e) {
[Link]();
}
return [Link]();
}
// ============================
// MAIN MENU
// ============================
public static void main(String[] args) {
boolean end = false;
int choice;
Scanner sc = new Scanner([Link]);
String filename = null;
while (!end) {
[Link]("===== MENU =====");
[Link]("0. Exit");
[Link]("1. Save as UTF-8");

24
[Link]("2. Save as UTF-16LE");
[Link]("3. Save as UTF-16BE");
[Link]("4. Enter file name");
[Link]("Enter your choice:");
choice = [Link]();
[Link]();
switch (choice) {
case 1:
if (filename == null) {
[Link]("Please enter file name first!");
break;
}
saveWithEncoding(filename, "UTF-8");
break;
case 2:
if (filename == null) {
[Link]("Please enter file name first!");
break;
}
saveWithEncoding(filename, "UTF-16LE");
break;
case 3:
if (filename == null) {
[Link]("Please enter file name first!");
break;
}
saveWithEncoding(filename, "UTF-16BE");
break;
case 4:
[Link]("Enter file name: ");
filename = [Link]();
break;
case 0:
end = true;
break;
default:
[Link]("Invalid choice.");
break;
}
}
[Link]();
[Link]("Program ended.");
}
}

25
Exception

class Too_Cold_Exception extends Exception{


private int temp;

public void setTemp(int t){


temp = t;
}
public String toString(){
return "Temperature is too low: " + temp;
}
}

public class Prac{


public static void boilWater(int temp) throws Too_Hot_Exception,
Too_Cold_Exception, Super_Cold_Exception{
if(temp > -50 && temp < 0){
Too_Cold_Exception exception = new Too_Cold_Exception();
[Link](temp);
throw exception;
}
//................
}

public static void main(String[] args) {


try{
boilWater(-100);
}
catch(Too_Cold_Exception tce){
[Link](tce);
}
}
}

26

You might also like