0% found this document useful (0 votes)
3 views15 pages

Java Practical File (Final) Manik

The document outlines a practical file for a Java programming lab, detailing various experiments including sorting text files, web scraping, and client-server communication using socket programming. Each experiment includes aims, program code, and specific implementations using Java libraries such as Jsoup and Selenium. Additionally, it covers database operations with H2, demonstrating CRUD functionalities and transaction management.

Uploaded by

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

Java Practical File (Final) Manik

The document outlines a practical file for a Java programming lab, detailing various experiments including sorting text files, web scraping, and client-server communication using socket programming. Each experiment includes aims, program code, and specific implementations using Java libraries such as Jsoup and Selenium. Additionally, it covers database operations with H2, demonstrating CRUD functionalities and transaction management.

Uploaded by

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

PRACTICAL FILE

SESSION: 2025-26
Programming in Java Lab
(CIC-258)
IInd Year, IVth Sem

Submitted to: Submitted by:


Name: Ms. Preeti Pandey Name: Manik Khurana
Designation: Assistant Professor Enrollment No.: 00618002724
Section: A

Department of Computer Science and Engineering


Delhi Technical Campus, Greater Noida
EXPERIMENT 7
AIM: Write a program in java to sort the content of a given text file.

Program:
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class exp7 {

public static void main(String[] args) {

String inputFilePath = "java_facts.txt";

String outputFilePath = "sorted_java_facts.txt";

try {

Path path = [Link](inputFilePath);

// Create a file with Java-related sentences if it doesn't exist

if ([Link](path)) {

List javaContent = [Link](

"Java is platform-independent due to Bytecode.",

"The JVM (Java Virtual Machine) executes the compiled code.",

"Garbage Collection automatically manages memory in the Heap.",


"Write Once, Run Anywhere (WORA) is Java's core philosophy.",

"Strong type checking prevents many common programming errors."

);

[Link](path, javaContent);

// 1. Loading the file into the JVM Memory (Heap)

List lines = [Link](path);

// 2. Sorting using the Collections Framework (uses TimSort algorithm) [Link](lines);

// 3. Writing the persistent data back to the disk [Link]([Link](outputFilePath), lines);

[Link]("Sorting successful. Content of " + outputFilePath + ":\n"); [Link](line


-> [Link]("- " + line));

} catch (NoSuchFileException e) { [Link]("File not found: " + [Link]());

} catch (IOException e) {

[Link]("I/O Error: " + [Link]()); }

Output:
EXPERIMENT 8
AIM: Create a Java application that performs advanced web scraping to
extract and analyze data from a real-world website.

Program:

XML Code:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

<artifactId>LavaExp9</artifactId>

<version>1.0-SNAPSHOT</version>

<properties>

<[Link]>17</[Link]>
<[Link]>17</[Link]>

</properties>

<dependencies>

<dependency>

<groupId>[Link]</groupId>

<artifactId>jsoup</artifactId>

<version>1.17.2</version>
</dependency>

<dependency>

<groupId>[Link]</groupId>

<artifactId>selenium-java</artifactId>

<version>4.18.1</version>

</dependency>

</dependencies>

</project>

Scrapper Code:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link]; import


[Link];

import [Link];

import [Link]; import [Link];

publicclass AdvancedScraper {

publicstatic void main(String[] args) {

//[Link] Headless Chrome for dynamic content ChromeOptions options = new


ChromeOptions(); [Link]("--headless");

WebDriver driver = new ChromeDriver(options);


List prices = new ArrayList<>();

try{

//Target: A practice scraping site

Stringurl = "[Link] [Link](url);

//[Link] the page source with Jsoup

Document doc = [Link]([Link]()); Elements teamRows =


[Link](".team"); // CSS Selector

[Link]("--- Scraped Data ---");

for(Element row : teamRows) {

Stringname = [Link](".name").text();

StringwinsStr = [Link](".wins").text();

if(![Link]()) {

doublewins = [Link](winsStr); [Link](wins);

[Link]("Team: %s | Wins: %.0f%n", name, wins); }

//[Link] Analysis

analyzeData(prices);

}catch(Exception e) {

[Link]();

} finally {

[Link]();

privatestatic void analyzeData(List data) { if([Link]()) return;


DoubleSummaryStatistics stats = [Link]() .mapToDouble(Double::doubleValue)

.summaryStatistics();

[Link]("\n--- Analysis Report ---"); [Link]("Total Records: " +


[Link]()); [Link]("Average Wins: " + [Link]());
[Link]("Max Wins: " + [Link]()); [Link]("Min Wins: " +
[Link]());

Output:
EXPERIMENT 9
AIM: Implement a client–server communication system using Java
Socket programming, demonstrating data exchange between
multiple clients and a server.
Program:
Server Code:

import [Link].*;

import [Link].*;

import [Link].*;

public class Server {

private static final int PORT = 1234;

private static Set clients = new HashSet<>();

public static void main(String[] args) {

[Link]("Server started...");

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

while (true) {

Socket socket = [Link](); [Link]("Client connected");

ClientHandler client = new ClientHandler(socket); [Link](client);

new Thread(client).start();

class ClientHandler implements Runnable {

} catch (IOException e) {
[Link]();

public static void broadcast(String msg, ClientHandler sender) {

for (ClientHandler client : clients) {

[Link](msg);

private Socket socket;

private BufferedReader reader;

private PrintWriter writer;

public ClientHandler(Socket socket) {

[Link] = socket;

try {

reader = newBufferedReader(new InputStreamReader([Link]())); writer = new


PrintWriter([Link](), true);

} catch (IOException e) {

[Link]();

public void run() {

String msg;

try {

while ((msg = [Link]()) != null) {

[Link]("Received: " + msg);


[Link](msg, this);

} catch (IOException e) {

[Link]("Client disconnected");

public void sendMessage(String msg) {

[Link](msg);

Client Code:

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

public class Client {

public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 1234);

BufferedReader keyboard = new BufferedReader(new

InputStreamReader([Link]));

BufferedReader serverInput = new BufferedReader(new

InputStreamReader([Link]()));

PrintWriter output = new PrintWriter([Link](), true);


[Link]("Connected to server");

// Receive messages

new Thread(() -> {


String msg;

try {

while ((msg = [Link]()) != null) { [Link]("Message: " + msg);

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

}).start();

// Send messages

String userMsg;

while ((userMsg = [Link]()) != null) { [Link](userMsg);

} catch (IOException e) {

[Link]();

Output:
EXPERIMENT 10
AIM: Implement a client–server communication system using Java Socket
programming, demonstrating data exchange between multiple clients and a
server.

Program:
XML Code:

<projectxmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]
v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>$[Link]</groupId>

<artifactId>$JMD_Database_Project</artifactId>

<version>$1.0-SNAPSHOT</version>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.1</version>

<scope>test</scope>

</dependency>

</dependencies>

</project>
Database Code:

import [Link].*;

public class DatabaseApp {

// This creates a database file named jmd_db in your Mac's home folder

private

static

final

String

"jdbc:h2:~/jmd_db;MODE=MySQL;DB_CLOSE_DELAY=-1";

AUTO_INCREMENT VARCHAR(100))";

private static final String USER = "sa"; private static final String PASS = "";

public static void main(String[] args) {

try (Connection conn = [Link](URL, USER, PASS)) {

[Link]("Connected to H2 Database successfully!");

// STEP 1: CREATE TABLE

String createTable = "CREATE TABLE IF NOT EXISTS students (id INT email

PRIMARY

KEY,

name

VARCHAR(100),

[Link]().execute(createTable);

// STEP 2: TRANSACTION START

[Link](false);
try {

// CREATE (Insert)

String insertSql = "INSERT INTO students (name, email) VALUES (?, ?)";

try (PreparedStatement pstmt = [Link](insertSql)) { [Link](1, "Ravi


Shankar");

[Link](2, "ravi@[Link]");

[Link]();

// READ (Select)

String selectSql = "SELECT * FROM students";

try (ResultSet rs = [Link]().executeQuery(selectSql)) {

while ([Link]()) {

[Link]("Found: " + [Link]("name") + " [" + [Link]("email") + "]");

// UPDATE

String updateSql = "UPDATE students SET email = ? WHERE name = ?";

try (PreparedStatement pstmt = [Link](updateSql)) { [Link](1,


"[Link]@[Link]");

[Link](2, "Ravi Shankar");

[Link]();

[Link]("Record updated successfully.");

// COMMIT TRANSACTION
[Link]();

[Link]("Transaction Committed!");

} catch (SQLException e) {

[Link]();

[Link]("Error occurred, rolling back changes.");

[Link]();

} catch (SQLException e) {

[Link]();

Output:

You might also like