0% found this document useful (0 votes)
4 views2 pages

Java Exp 7

The document presents a Java program that sorts the content of a text file containing Java-related sentences. It checks if the input file exists, creates it with predefined content if not, sorts the lines using the Collections Framework, and writes the sorted content to a new output file. The program also handles exceptions for file not found and I/O errors.

Uploaded by

mohitcse24
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)
4 views2 pages

Java Exp 7

The document presents a Java program that sorts the content of a text file containing Java-related sentences. It checks if the input file exists, creates it with predefined content if not, sorts the lines using the Collections Framework, and writes the sorted content to a new output file. The program also handles exceptions for file not found and I/O errors.

Uploaded by

mohitcse24
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

EXPERIMENT- 7

AIM: Write a program in java to sort the content of a given text file.

Code:

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<String> 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<String> 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:

You might also like