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: