How to import packages in java [duplicate] - java

This question already has answers here:
How to use 3rd party packages in Java
(3 answers)
Closed 6 years ago.
I am new in Java programming language and i want to use a library by importing their packages . Can anyone tell me how can i import packages in Java using text editor?
I found this library in github and i wanted to use their packages for my java code i am developing by using import. I tried just to call these packages on my code by using import but in compiler there was an error which states: packages not found.
import com.tiemens.secretshare.main.cli.*;
import com.tiemens.secretshare.main.cli.*;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Integer.min;
import static java.util.Arrays.copyOfRange;
public class Shamir {
//The encoding that will be used when splitting and combining files.
static String encoding = "ISO-8859-1";
//The number of bytes per piece (except maybe the last one)!
static int pieceSize = 128;
//Mode 0 for strings, 1 for ints.
public static ArrayList<String> shamirSplit(String inputString, int numPieces, int minPieces, int mode) {
String type = "-sS";
if (mode == 1) {
type = "-sN";
}
ArrayList<String> parts = new ArrayList<>();
String[] splitArgs = {"-n", Integer.toString(numPieces), "-k", Integer.toString(minPieces), type, inputString, "-primeNone"};
MainSplit.SplitInput splitInput = MainSplit.SplitInput.parse(splitArgs);
MainSplit.SplitOutput splitOutput = splitInput.output();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
splitOutput.print(ps);
String content = baos.toString(); // e.g. ISO-8859-1
BufferedReader reader = new BufferedReader(new StringReader(content));
String line;
int i = 0;
try {
while ((line = reader.readLine()) != null && i < numPieces) {
if (line.startsWith("Share (x")) {
i++;
parts.add(line.trim());
}
}
} catch (Exception e)
So my class i want to implement is Shamir class but i need to import com.tiemens.secretshare.main.cli.*;
Can anyone tell me how to make this package work for my Shamir class?

I am guessing you aren't using maven. Download the jar files for packages you want to import and put then in your build path

If I am not mistaken, when I do what you did:
import com.tiemens.secretshare.main.cli.*;
public class Foo {
}
and then try to compile using javac Foo.java, I get:
Error:(2, 1) java: package com.tiemens.secretshare.main.cli does not exist
This means that when the compiler javac is trying to compile your class (Shamir.java) it needs either the source files or the bytecode (class files) for the classes in the package com.tiemens.secretshare.main.cli. Since you seem to have neither, the compilation fails.
Thus, you need the jar file that contains the classes they you want to compile against. There are two ways to achieve this:
Use Maven. But that means you need to learn Maven. That's life. Use mvn repo to compile against.
If you think it is too much of work to learn Maven, you will need to build secretshare code on GitHub yourself. This means you will need to learn gradle. Again, that's life.
Too bad you couldn't download the JAR file as a "release download" for this project.

Download the jar for your library and include it in your project classpath. Then you can import it in your class.
For setting the classpath use this link

Related

Java Compiler Completed but Didn't Create the Executable?

(I am new to Java, I don't know what 'classes' or 'api's' are.)
I was trying to compile (javac -g Sphinx.java) this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
public class Sphinx {
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("models/en-us/en-us");
configuration.setDictionaryPath("models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("models/en-us/en-us.lm.bin");
PrintWriter pw = new PrintWriter(new PrintWriter("status.txt"));
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
pw.print("running");
SpeechResult result = recognizer.getResult();
recognizer.stopRecognition();
pw.print("stopped");
pw.close();
PrintWriter pw2 = new PrintWriter(new PrintWriter("result.txt"));
pw2.println(result);
pw2.close();
}
}
And I got this message:
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
So, I re-compiled with -Xlint:deprecation, like it told me to, and it didn't give me any errors this time, so I'm assuming the compiler was finished, and that it compiled successfully.
And then I look, and there's no .jar file, just a new .class file.
Now, I don't really know much about the java compiler, I was just told online that it would give me an executable for the code I had written, which in this case is a .jar file.
I don't know if the compiler sends newly created executables to a special system directory or what, but it's not here, and I don't know why.
Would someone more knowledgeable with Java please give me some context here.
You need just add the next step - look at: docs.oracle.com/javase/tutorial/deployment/jar/build.html
jar cf jar-file input-file(s)

How do I get 'import java.net.*' to work?

I am learning to program in java. I have programmed in other languages. I have tried import java.net.*; at the start of my code file. But it ghosts out. I have looked in my External Libraries directory and it is not there. I found that java.net was deprecated in 201x <-- some recent year. I am using jdk 10. I am using IntelliJ IDE. I have gotten some import statements to work.
I saw on github that they took over hosting oracle classes that were deprecated at Oracle.
I know I have to use the classpath command if I put the .jar or the .zip file containing the class in another directory. I have searched my laptop and i don't have any other .jar or .zip files other than specific other programs I have installed which also don't contain the java.net class (e.g. Aptana Studio 3)
I am using Mac with OS Sierra.
package com.robinhoodcomputer.myfirstprojects;
import java.io.FileReader; <<-- these import ok
import java.io.*;
import java.net.*; <<--- these don't import
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Myreader {
public static void main(String[] args) throws Exception {
int intVal;
char myChar;
String st;
File file = new File("/java/file");
BufferedReader br = new BufferedReader(new FileReader(file));
// FileReader fr = new
FileReader("/java/HelloWorld/resources/file.txt");
while ((intVal = br.read()) != -1) {
myChar = (char) intVal;
System.out.print(myChar);
}
myHostName = getLocalHost(); <<-- this doesn't show being available
}
}
I have searched and cannot find any articles that actually do anything but explain how to connect to the class file and that you have to import it in your code. No one talks about getting the java.net class itself.
I found one reference to jdk.net in an oracle jdk 10 API specification page.
What am I suppose to use to get the IP address using a hostname in java these days??
thx
P.S. I know this code really doesn't have anything to do with networking, most of it is just reading a file and displaying what's in the file. I wanted to use this code file just to try getting an IP address also. My question is mainly just about making the import statement to work. thx
Your imports are grayed out, since you do not call any method of the imported libraries. As soon as you start using the getLocalHost() method properly, the import will not be grayed out any more. This is a convenience functionality of your IDE it seems.
getLocalHost() is a method of InetAddress and can't be just called without such an instance.
Look at this question for how to use this:
java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

Importing a package with an interface and a class

I am trying to create a Java package to interface with Excel, so I am using the org.apache.poi libraries. I've found the documentation on the POI site that shows the following:
Reading and Rewriting Workbooks
(truncated)
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
When I attempt to create a Workbook object, I get errors that it doesn't know the type. The documentation above doesn't show the import statements, but if I'm reading these POI docs correctly, I should be able to import org.apache.poi.ss.usermodel.Workbook, (and it's distinctly possible that I'm wrong because I'm very new to Java) but trying all of the following import statements all result in errors for the Workbook type.
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
I should note that I'm using Eclipse Neon for this, and the editor is not complaining that it can't find the packages, so I'm not sure where the issue lies.
Workbook wb = WorkbookFactory.create(inp);
The actual error I'm getting in the editor is that "Workbook cannot be resolved to a type", and the same error for WorkbookFactory.
So the TL;DR is that the POI docs show that Workbook is an Interface in org.apache.poi.ss.usermodel and that WorkbookFactory is a class in the same usermodel package, but I can't figure out how to import/use them correctly.
EDIT:
The build time error I receive is
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook cannot be resolved to a type
WorkbookFactory cannot be resolved
at spreadsheet.conversion.ConvertXLSXtoCSV.main(ConvertXLSXtoCSV.java:31)
The message I posted before was the editor popup... I was able to take a screenshot:
EDIT: Posting the full code, because, why not. (The multiple import statements
were just trying things out, mostly in desperation.)
package spreadsheet.conversion;
import java.text.ParseException;
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ConvertXLSXtoCSV {
private static String inputfilename = "";
private static String outputfilename = "";
private static int debug = 0;
private static void test(String arg) {
System.out.println(arg);
}
public static void main(String[] args) throws ParseException, Exception {
if (args.length != 1) {
throw new Exception("Requires 1 parameter. Usage: ConvertXLSXtoCSV <filename>");
}
inputfilename = args[0];
if(debug==1) {
test(inputfilename);
}
InputStream inp = new FileInputStream(inputfilename);
Workbook wb = WorkbookFactory.create(inp);
}
Any help is appreciated.
As unhelpful to others as this may be, it's the solution I've come up with so I'm posting it as an answer. Many thanks for the comments about this, but I've always hated Eclipse, and decided to go with NetBeans IDE instead. It was extremely trivial to right click on Libraries, Add JAR/Folder, and select the POI jar files, and it (and the integrated Maven install) took care of the details and it worked perfectly right off the bat and resolved all library dependencies.
I believe this due to jar file corrupted ( most probably during download for the first time). Here what you can do.
You can delete all poi folder in maven repository .m2/repository/org/apache/poi then you can update maven by Right Click on the project > Maven > Update Project. Eclipse will automatically download the dependencies and auto rebuild the workspace.
im facing the same thing like yours and manage to get it clean.

Calling A Java Library From Pentaho Kettle

I have developed a java class exported into a .jar library that will be called by a Pentaho Kettle 'modified java script'. The .jar is compiled in Eclipse with JDC Compliance level 1.7.
When I try to use this class inside a 'modified java script', I get the error: ReferenceError: “xeroCallPackage” is not defined. I have tried lots of things without much luck so far.
My file xeroCallPackage.jar is in the path with the other *.jar files in Pentaho (..\data-integration\lib)
For info:
The stripped down (for simplicity) java library code is here:
package xeroCallPackage;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;
public class xeroURLCall {
public String getResponse(String CONSUMER_KEY, String CONSUMER_PRIVATE_KEY, String URL) throws IOException, OAuthException, URISyntaxException {
// stripped out code here
return response.readBodyAsString();
}
}
The stripped down Pentaho 'modified java script' is here:
var CONSUMER_KEY = "ffffff";
var CONSUMER_PRIVATE_KEY = "aaaaa";
var URL = "https://gggggggg.rrrrr.wwww";
var ResponseAsString;
ResponseAsString = new xeroCallPackage.xeroURLCall.getResponse(CONSUMER_KEY,CONSUMER_PRIVATE_KEY,URL);
You will either have to have org as top-most package or prefix the fully qualified name of your class with Packages.
So in your case the fully qualified name of your class that can be used for calling from Spoon will be Packages.xeroCallPackage.xeroURLCall
Apart from that the supplied JavaScript code won't work (but maybe that's just because of the stripped down code). You'd have to create a xeroURLCall object first and then call the getResponse method on that object:
var call = new Packages.xeroCallPackage.xeroURLCall(...);
var responseAsString = call.getResponse(CONSUMER_KEY,CONSUMER_PRIVATE_KEY,URL);

Discovering jni4net samples

I'm discovering the jni4net. This is the technology used to provide the bridge between Java and .NET. So, I created new Eclipse Java project and copied the sample code from jni4net-0.8.6.0-bin/samples/myCSharpDemoCalc->MyCalcUsageInJava.java into this project. However the code cannot be compiled because two imports "mycsharpdemocalc.DemoCalc" and "mycsharpdemocalc.ICalc" cannot be found. I don't understand how to integrate/import mycsharpdemocalc.c into the Java project so that the code could be compiled.
import net.sf.jni4net.Bridge;
import java.io.IOException;
import mycsharpdemocalc.DemoCalc;
import mycsharpdemocalc.ICalc;
public class MyCalcUsageInJava {
public static void main(String arsg[]) throws IOException {
Bridge.init();
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("MyCSharpDemoCalc.j4n.dll"));
ICalc calc = new DemoCalc();
final int result = calc.MySuperSmartFunctionIDontHaveInJava("Answer to the Ultimate Question of Life, the Universe, and Everything");
System.out.printf("Answer to the Ultimate Question is : " + result);
}
}
There is ReadMe in each sample directory.
You have to use proxygen tool to generate the proxies (which are used in the java code).
There is generateProxies.cmd batch to do that.
More complex things may need config file for proxygen.
Also there is community Wiki

Categories

Resources