2
$\begingroup$

I have a jar file so I tried to run the class from Mathematica following these steps, but I get all these:

Java::excptn: A Java exception occurred: java.lang.ClassNotFoundException: Buscar
    at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:471)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:398).

LoadJavaClass::fail: Java failed to load class Buscar.

This is the code in my notebook

Needs["JLink`"]
InstallJava[]
AddToClassPath["C:\Users\Amada\Documents\Buscar.java"]
LoadJavaClass["Buscar"]

And this is the Java codel I made it with Apache-Neatbeans 11.2 and I have JDK 12 and Mathematica 12 (if it's useful)

package buscar;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Buscar {

    public static void main(String[] args) {
        buscador("issue");
    }
    
    public static void buscador(String palabra){
     Scanner entrada= null;
        String linea;
        int numdelinea= 1;
        boolean contiene= false;
        Scanner sc = new Scanner(System.in);
        
         try{
            
            File f= new File("C:/Program Files/Wolfram Research/Mathematica/12.1/Documentation/English/System/ExampleData/USConstitution.txt");
            entrada= new Scanner(f);
            System.out.println("Archivo: " + f.getName());
            System.out.println("Texto a bucar: " + palabra);
            
            while(entrada.hasNext()){
                linea= entrada.nextLine();
                if(linea.contains(palabra)){
                    System.out.println("Línea " + numdelinea + ": " + linea);
                    contiene = true;
                }
                numdelinea++;
            }
            if( !contiene){
                System.out.println(palabra + "no se ha encontrado");
            }
        } catch (FileNotFoundException e){
            System.out.println(e.toString());
        }catch (NullPointerException e){
            System.out.println(e.toString()+ "No se ha seleccionado ningún archivo");
        }catch (Exception e){
            System.out.println(e.toString());
        }finally{
            if(entrada !=null){
                entrada.close();
                }
            }
        }
    }

Thank you everyone.

-Luisa

$\endgroup$
2
  • $\begingroup$ You need to either add the jar file containing the Buscar class or the actual .class file (not .java) to the classpath. e.g. AddToClassPath["C:\\Users\\Amada\\Documents\\Buscar.class"] $\endgroup$ Commented Aug 4, 2020 at 13:48
  • $\begingroup$ Thank you, I tried this but it failed again. $\endgroup$ Commented Aug 11, 2020 at 1:01

1 Answer 1

2
$\begingroup$

There are a number of issues that must be addressed.

  1. The AddToClassPath call should reference the directory or JAR file containing the compiled Java classes, not the source file. Since you are using NetBeans, the class files are normally compiled into the subfolder build\classes within the project folder (or possibly just build depending on the NetBeans vintage). Also, if it is a normal Java application project, then a JAR file will also have been generated into the subfolder dist.

  2. When loading the Java class, the package name must be included in the class name. In this case, LoadJavaClass["buscar.Buscar"].

  3. The class uses System.out.println to display its results. To see this output, you must use ShowJavaConsole[].

The following code puts this all together. You will need to adjust it to match your actual project directory structure (here, C:\NetBeansProjects\myapp):

Needs["JLink`"]
InstallJava[];

AddToClassPath["C:\NetBeansProjects\myapp\build\classes"]
(* or possibly: AddToClassPath["C:\NetBeansProjects\myapp\dist\myapp.jar"] *)

LoadJavaClass["buscar.Buscar"]

ShowJavaConsole[]

Having done all this, we can run the main program:

Buscar`main[{}]

(* output in the Java console:

Archivo: USConstitution.txt
Texto a bucar: issue
Línea 42: Authority thereof shall issue Writs of Election to fill such Vacancies.
Línea 545: no Warrants shall issue, but upon probable cause, supported by Oath or
Línea 699: executive authority of such State shall issue writs of election to fill such
Línea 845: Congress shall decide the issue, assembling within forty eight hours for that
*)

... or we can run the static method buscador instead:

Buscar`buscador["issue"]

(* same output as above *)

Manipulating the Result

You might want to consider changing the method buscador to return its result instead of printing it to the console. This would make it easier to manipulate the result within Mathematica. Perhaps it could return a string or list of strings... or something more structured like JSON. But such changes to the Java code are beyond the scope of this response.

Alternatively, you could run your application directly with Java and Import the result (no JLink required):

Import[
  "!java -cp C:\\NetBeansProjects\\myapp\\build\\classes buscar.Buscar"
, "Text"
]

(* Same output as before, but returned as a string *)
$\endgroup$
5
  • $\begingroup$ Thank you, I tried what you wrote but now I have a new message: A Java exception occurred: "java.lang.UnsupportedClassVersionError: \ buscador/Buscador has been compiled by a more recent version of the \ Java Runtime (class file version 56.0), this version of the Java \ Runtime only recognizes class file versions up to 55.0 I read a post in other forum about a similar situation and they said it's necessary to change the directory of the java executable, that'd work? $\endgroup$ Commented Aug 11, 2020 at 1:08
  • 1
    $\begingroup$ Java class file version 55 indicates Java 11 whereas version 56 is Java 12. You will need to either 1) download the older version of the Java SDK and use it to compile your source or 2) configure Mathematica to use a newer Java installation (e.g. the one from your NetBeans). $\endgroup$
    – WReach
    Commented Aug 11, 2020 at 1:34
  • $\begingroup$ Thank you very much. I tried both options but no one worked so I decided to download Netbeans 8.2 and problem solved. $\endgroup$ Commented Aug 24, 2020 at 1:07
  • $\begingroup$ Hi again, I changed my Java code and now it returns the result but I don't know how to show it in the notebook @WReach $\endgroup$ Commented Sep 1, 2020 at 2:28
  • $\begingroup$ If you have defined a method that returns String or List<String> or similar, then simply calling it from Mathematica should show the result in the notebook. If your new method is static then you can call it like in the example in this response. Otherwise, you will have to create an instance of the class first. If you have tried those things and it still isn't working, perhaps post a new question showing your updated code. $\endgroup$
    – WReach
    Commented Sep 1, 2020 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.