2

So, I'm new to Java, and I was looking at how to use a class from a Jar file. I created a java file with all the classes I wanted and then got a Jar file from it, I imported it using this interface but now how can I actually use it? I'm not using Maven or anything. Just plain java project from VSCode (Java Extension Pack and Jar Builder installed).

I know that maybe I should use a different program but I really like VSCode so If u could help here I would appreciate it :)

Here is the java file that I built the Jar from

import java.io.*;
public class Ler {
    public static String umaString (){
        String s = "";
        try{
            BufferedReader in = new BufferedReader ( new InputStreamReader (System.in));
            s= in.readLine();
        }
        catch (IOException e){
        System.out.println("Erro ao ler fluxo de entrada.");
        }
    return s;
    }

    public static int umInt(){
        while(true){
            try{
                return Integer.valueOf(umaString().trim()).intValue();
            }
            catch(Exception e){
                System.out.println("Não é um inteiro válido!!!");
            }
        }
    }
    
    public static char umChar(){
        while(true){
            try{
                return umaString().charAt(0);
            }
            catch(Exception e){
                System.out.println("Não é um char válido!!!");
            }
        }
    }
    
    public static short umShort(){
        while(true){
            try{
                return Short.valueOf(umaString().trim()).shortValue();
            }
            catch(Exception e){
                System.out.println("Não é um short válido!!!");
            }
        }
    }        
}
VEX Enzo
  • 33
  • 3

2 Answers2

1

You can verify your work with the tips written in the answer to similar problem here: https://stackoverflow.com/a/54535301/14056755

When you import the library into your plain Java project, you can just summon classes from jar library by using import keyword. Your class inside jar library should be placed inside a package.

Example (assuming Ler class is placed inside org.xyz package):

import org.xyz.Ler;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marcin Rzepecki
  • 578
  • 4
  • 10
1

Here's the solution:

1.Use the command javac Ler.java to compile Ler.java;

2.Type the command jar --create --file Ler.jar Ler.class to generate Ler.jar;

Attention: If Ler.java is under the subfolder, please enter it then compile and generate .jar.

enter image description here

3.Add Ler.jar to Referenced Libraries;

4.Code like Ler.function().

enter image description here

Molly Wang-MSFT
  • 7,943
  • 2
  • 9
  • 22