I read files from disc in my Java project. I find my hohoho.java file on D:/ and it's in File format, then I would like to add it as a class to existing package with my main class (Up.java). It should look like this - package -> Up.java, Hohoho.java.
And it should be done programmatically of course. I will use this .java file and it's functions in my Up.java.
Do you know any easy way to do this?
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
public class Up{
public static void main(String[] args) {
File root = new File("..\\.");
File myfile = null;
try {
String[] extensions = {"java"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
String path = file.getAbsolutePath();
System.out.println("File = " + path);
String[] tokens = path.split("\\\\");
for (String t : tokens)
if (t.equals("Hohoho.java")){
myfile = file;
}
}
System.out.println("Client class: " + myfile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
javafile, you have to call the compiler. If it's aclassfile, it's a little easier but still involved.