Java Online Compiler
Example: Display Own Source Code in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Display Own Source Code import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; // Main class containing the entry point of the program public class DisplaySourceCode { // Note: Class name must match file name (DisplaySourceCode.java) public static void main(String[] args) { // Step 1: Specify the name of the source file. // For this program to work, the Java source file must be named "DisplaySourceCode.java" // and be located in the directory from which the compiled .class file is executed. String sourceFileName = "DisplaySourceCode.java"; // Step 2: Utilize a try-with-resources statement for efficient and safe file handling. // This ensures that the FileReader and BufferedReader are automatically closed // once the try block is exited, regardless of whether an exception occurred. try (BufferedReader reader = new BufferedReader(new FileReader(sourceFileName))) { String line; System.out.println("--- SOURCE CODE DISPLAY START ---"); // Step 3: Read the file line by line until the end of the file is reached. while ((line = reader.readLine()) != null) { // Step 4: Print each line read from the source file to the console. System.out.println(line); } System.out.println("--- SOURCE CODE DISPLAY END ---"); } catch (IOException e) { // Step 5: Catch and handle any IOException that might occur during file operations. // This includes scenarios like the file not being found, permissions issues, or read errors. System.err.println("Error: Could not read the source file '" + sourceFileName + "'."); System.err.println("Please ensure 'DisplaySourceCode.java' exists in the current directory."); System.err.println("Details: " + e.getMessage()); // For more detailed debugging, uncomment the following line: // e.printStackTrace(); } } }
Output
Clear
ADVERTISEMENTS