Reputation: 1134
I want to print the source code of current program(the program which is running)on the console using File reader?How to do it? i.e using java.io.FileReader Class
Upvotes: 0
Views: 103
Reputation: 311
The only way I see to do that is to have your FileReader
object open the .java file from your workspace, loop through and print out each line.
EDIT: adding rough outline.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
public class Test {
public void printMe() {
try {
String classname = Test.class.toString();
// This gets the full class name, including package
classname= classname.replace("class ", "");
classname= classname.replace(".", "/");
BufferedReader br = new BufferedReader(new FileReader(<path_to_workspace/project_name/source_folder> + classname + ".java"));
String line = br.readLine();
while(line != null) {
System.out.println(line);
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Keep in mind, this will only work in a workspace. You cannot print the source code of a complied java class inside a jar, as the source is compiled and thus not human-readable.
Upvotes: 1