Frankly, I do not know even it is possible or not.
But what I am trying to do is just like below.
I made a class file from ClassFile.java via javac command in terminal.
Then I want to get an instance from .java file or .class file.
Next, I made another project in eclipse, As you guess this project path and upper file path are completely different. For instance, ClassFile.java/class file can be located in '~/Downloads' folder, the other hand, new eclipse project can be in '~/workspace/'.
So I read file which referred in step 1 by FileInputStream.
From here, I just paste my code.
public class Main {
private static final String CLASS_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.class";
private static final String JAVA_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.java";
private static Class getClassFromFile(File classFile) throws Exception {
System.out.println("get class from file : [" + classFile.getCanonicalPath() + " ]");
Object primativeClz = new Object();
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream(classFile));
primativeClz = ois.readObject();
ois.close();
return primativeClz.getClass();
}
public static void main(String[] args) throws Exception {
getClassInfo(getClassFromFile(new File(CLASS_FILE_PATH)));
}
}
just like your assumption, this code has errors.
For example, it shows :
java.io.StreamCurruptedException: invalid stream header : CAFEBABE
this there any way to get object instance from .class file or .java file?
P.S.
I wish do not use extra libraries.
private static final String CLASS_FOLDER =
"/Users/juneyoungoh/Downloads/";
private static Class getClassFromFile(String fullClassName) throws Exception {
URLClassLoader loader = new URLClassLoader(new URL[] {
new URL("file://" + CLASS_FOLDER)
});
return loader.loadClass(fullClassName);
}
public static void main( String[] args ) throws Exception {
System.out.println((getClassFromFile("ClassFile"));
}
Related
public class TestResourceBundle {
private static final Path frZoo = Paths.get("./src/Zoo_fr.properties");
private static final Path enZoo = Paths.get("./src/Zoo_en.properties");
private static void createFiles() {
try {
Files.createFile(frZoo);
Files.createFile(enZoo);
try (BufferedWriter enWriter = Files.newBufferedWriter(enZoo);
BufferedWriter frWriter = Files.newBufferedWriter(frZoo);) {
enWriter.write("hello=Hello\nopen=The zoo is open");
frWriter.write("hello=Bonjour\nopen=Le zoo est ouvert");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void createBundle() {
Locale us = new Locale("en", "US");
Locale france = new Locale("fr", "FR");
ResourceBundle usBundle = ResourceBundle.getBundle("Zoo", us);
ResourceBundle frBundle = ResourceBundle.getBundle("Zoo", france);
System.out.println(usBundle.getString("hello"));
System.out.println(frBundle.getString("hello"));
}
}
In the main function, if I run the following, it will throw java.util.MissingResourceException
public static void main(String[] args) {
createFiles();
createBundle();
}
but if I run these two functions separately (in two programs), it works and does not have any problem.
First run
public static void main(String[] args) {
createFiles();
// createBundle();
}
then run the following, in this case, it works
public static void main(String[] args) {
// createFiles();
createBundle();
}
I don't know why, please help
The problem is that you are trying to load a bundle that is not present in the classpath the application knows about.
When you call ResourceBundle.getBundle it will try to load the resource bundle from the application classpath. But the application classpath was already defined at the application startup, so your brand new files are not listed there.
Two options I can think of: Load the bundle from a file input stream or, define your own classloader to load the files.
1. Load the bundle from a File Input Stream
Create a new PropertyResourceBundle from a FileInputStream that loads each file directly.
Warning: Stream closing and exception handling omitted for brevity.
FileInputStream enFileStream = new FileInputStream("./src/Zoo_en.properties");
FileInputStream frFileStream = new FileInputStream("./src/Zoo_fr.properties");
ResourceBundle usBundle = new PropertyResourceBundle(enFileStream);
ResourceBundle frBundle = new PropertyResourceBundle(frFileStream);
2. Create a URL ClassLoader to load the new files
This is a more scalable approach. Create a new URLClassLoader and use that class loader as an argument for getBundle.
Warning: Stream closing and exception handling omitted for brevity.
File bundleRootPath = new File("./src");
URL[] urls = new URL[]{bundleRootPath.toURI().toURL()};
ClassLoader classLoader = new URLClassLoader(urls);
ResourceBundle usBundle = ResourceBundle.getBundle("Zoo", us, classLoader);
ResourceBundle frBundle = ResourceBundle.getBundle("Zoo", france, classLoader);
Hope that helps.
I have two java projects MASTER and PLUGIN. PLUGIN has dependencies to MASTER and its intent is to extend a class found in MASTER, called SCRIPT.
Once I have declared a SCRIPT (myScript), I want to move the .class file to a folder that MASTER can access. I want MASTER to dynamically load and instantiate that class as a SCRIPT.
I've looked for quite a bit and tried different solutions, but I always get a ClassNotFoundException exception.
I would prefer to do this without passing arguments to the JVM at startup.
Is it even possible? This is my current solution: "currentPath" is "etc/etc/myScript.class
try {
OUT.ln("initiating script " + currentPath);
File file = new File(currentPath);
File parent = file.getParentFile();
String name = file.getName().split(".class")[0];
// Convert File to a URL
URL url = parent.toURI().toURL();
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
#SuppressWarnings("resource")
ClassLoader cl = new URLClassLoader(urls);
current = (SCRIPT) cl.loadClass("main.script." + name).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to load script " + currentPath);
}
if the class you want to load is defined within a package like:
main.script.myScript
and you want to load this class from a folder like c:/myclasses,
then you have to put this class to c:/myclasses/main/script/myScript.class
and then instantate the classloader with the basefolder like:
URL[] urls = new URL[]{new URL("file://c:/myclasses")};
ClassLoader cl = new URLClassLoader(urls);
then the class can be loaded by using the qualified class name:
cl.loadClass("main.script.myScript").getDeclaredConstructor().newInstance()
if you want to keep the class at a specific folder without considering the package structure you could do something like this:
public static void main(String[] args) {
try {
File file = new File("etc/etc/myScript.class");
String className = file.getName().split(".class")[0];
String packageName = "main.script.";
byte[] bytes = Files.readAllBytes(Path.of(file.getPath()));
MyClassLoader myClassLoader = new MyClassLoader(Thread.currentThread().getContextClassLoader());
Object o = myClassLoader.getClass(packageName+className, bytes).getDeclaredConstructor().newInstance();
System.out.println(o);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to load script ");
}
}
public static class MyClassLoader extends ClassLoader {
public MyClassLoader(ClassLoader parent) {
super(parent);
}
public Class<?> getClass(String name, byte[] code) {
return defineClass(name, code, 0, code.length);
}
}
I am very lost with the concept of getResources.
I have put a simple text file in a bin folder which I would like to access as a resource so I can then build and deploy. However when I try to run the jar file I get a file not found error which I think is down to how I am accessing the resource. How can I use it?
public class Iterator {
static ArrayList<String> myFiles = new ArrayList<String>();
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
static String folderName;
static Path p;
public Iterator() { }
public static void main(String[] args) throws IOException, SAXException, TikaException, SQLException, ParseException, URISyntaxException, BackingStoreException {
Preferences userPrefs = Preferences.userNodeForPackage(TBB_SQLBuilder.class);
p = Paths.get(filename.toURI());
//This iterates through each of the files in the specified folder and copies them to a log.
//It also checks to see if that file has been read already so that it isn't re-inputted into the database if run again
//Loop through the ArrayList with the full path names of each folder in the outer loop
for (String line : Files.readAllLines(p)){
myFiles.add(line);
}
}
}
The error I get
Exception in thread "main" java.nio.file.FileSystemNotFoundException
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Paths.java:143)
at Overview.Iterator.main(Iterator.java:46)
**Edit with #BorisTheSpiders' answer:
public class Iterator {
static ArrayList<String> myFiles = new ArrayList<String>();
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
static String folderName;
static Path p;
public Iterator() {
}
public static void main(String[] args) throws IOException, SAXException, TikaException, SQLException, ParseException, URISyntaxException, BackingStoreException {
Preferences userPrefs = Preferences.userNodeForPackage(TBB_SQLBuilder.class);
InputStream in = filename.openStream( );
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
p = Paths.get(filename.toURI());
//This iterates through each of the files in the specified folder and copies them to a log.
//It also checks to see if that file has been read already so that it isn't re-inputted into the database if run again
//Loop through the ArrayList with the full path names of each folder in the outer loop
for (String line : Files.readAllLines(p)){
myFiles.add(line);
}
but I'm not really sure how I then use the reader to provide a Paths.get with a uri. I think I'm probably not understanding something fundamental here...
As pointed out in the comments, the file in question cannot be found in the file system.
As a suggestion, try replacing
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
with
static InputStream is = Iterator.class.getResourceAsStream("/Files/FilesLogged.txt");
and the block where the file is read with the following:
try (Scanner scanner = new Scanner(is)) {
while(scanner.hasNextLine()){
String line = scanner.nextLine();
myFiles.add(line);
}
}
I am trying to write object data to a file (how it's done in a standard java program) in an android program and am running in to some issues. Here's the code:
public static final String storeDir = "Adata";
public static final String storeFile = "albums";
public static void write(ArrayList<Album> albums) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(storeDir + File.separator + storeFile));
oos.writeObject(albums);
}
public static ArrayList<Album> read() throws IOException, ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream( new FileInputStream(storeDir + File.separator + storeFile));
return (ArrayList<Album>)ois.readObject();
}
At startup the app crashes and says, "java.io.FileNotFoundException: Adata/albums (No such file or directory)
The folder Adata folder is in the project folder at the same point as the src. Any help is appreciated. Thanks.
I assume that you want in to store in the external directory
Replace your storedir and storeFile as
public static final String storeDir = = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String storeFile = "Adata/albums";
Also you may need to provide permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
To get a better understanding, take a look at Developer site.
Why does my code (compiles fine) gives me the following error?
Main method not found in class ImageTool, please define the main method as: public static void main(String[] args)
Code:
public class ImageTool {
public static void main(String[] args) {
if (args.length <1) {
System.out.println("Please type in an argument");
System.exit(-1);
}
if (args[0].equals("--dump")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
print2DArray(image);
} else if (args[0].equals("--reflectV")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
int[][] reflect = reflectV(image); //reflectV method must be written
String outputFilename = args[2];
writeGrayscaleImage(outputFilename,reflect);
}
}
Your main method looks fine.
1) Probably your .class file does not correspond to your .java file.
I would try to clean up my project (if I was using an IDE and getting this).
That is: delete the .class file, regenerate it from the .java file.
2) Seems you're not running ImageFile but some other class,
even though you think you're running ImageFile. Check what
your IDE is running behind the scenes.
I hope one of these two suggestions would help.