I seem to be having what I believe is a ClassLoader problem using db4o with NetBeans. When I run the exact same code from the terminal with the same jar files from .../jre/lib/ext, everything works fine. The issue is that when I make a native query on some Classes that are loaded at runtime using a ClassLoader, I get an empty List from the database where I should definitely be getting a List with some elements (as I said, the same code works fine from the command line). I feel like this may be because the NetBeans ClassLoader works differently than the JVM ClassLoader, but I don't know, I'm certainly no expert on either. Here is the code from my main function.....
////////////////////////////////////////////////////////////////////////////////////////////
package gql;
import java.io.*;
import java.util.*;
import com.db4o.*;
public class GQL {
////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
////////////////////////////////////////////////////////////////////////////
private static ObjectSet dbObjects;
private static LinkedList classes = new LinkedList();
private static String dbPath, classPath;
private static ObjectContainer db;
private static ClassLoader coreClassLoader =
ClassLoader.getSystemClassLoader();
private static ClassLoader subClassLoader =
ClassLoader.getSystemClassLoader();
public static void main(String[] args) {
////////////////////////////////////////////////////////////////////////
// CREATE DATABASE OBJECT
////////////////////////////////////////////////////////////////////////
// If no path to a database is provided on the command line, print
// error and exit program
if (args.length < 1) {
System.err.println("\nError: no database path provided.\n");
return;
} else if (args.length > 1) {
dbPath = args[0];
// TODO - dubug command line classpath
classPath = args[1];
db = Db4o.openFile(dbPath);
} else { // We assume that the database Classes are stored somewhere
dbPath = args[0]; // along the CLASSPATH, and therefore classPath
classPath = ""; // can be left empty
db = Db4o.openFile(dbPath);
}
System.out.print("GQL> ");
// The prompt of the interpreter is within a do-while loop, which can
// be terminated by entering "exit"
do {
try {
/////////////////////////////////////////////////////////////////
// READ IN QUERY FILE
/////////////////////////////////////////////////////////////////
// We create a Scanner object to read tokens from the standard in
// stream - these will be our DLOG files provided by the user
Scanner fileScanner = new Scanner(System.in);
String GQLFile = fileScanner.next();
// Break loop and exit program if user enters "exit"
if (GQLFile.equalsIgnoreCase("exit")) {
break;
// If the user input is not preceeded by "#" and teminated with
// ";" then the input is invalid - the user is prompted again
} else if (!(GQLFile.substring(0,1).equals("#")) ||
!(GQLFile.substring(GQLFile.length()-1,
GQLFile.length()).equals(";"))) {
System.out.println("\nInvalid input.\nUsage: "
+ " #filename;\n");
System.out.print("GQL> ");
continue;
} else {
// Parse out the "#" and ";" from the user's input and send
// this to a file Reader object
GQLFile = GQLFile.substring(1,GQLFile.length()-1);
}
// Now we create a reader object and give it the user's parsed
// input - in the event of a FileNotFoundException, the user is
// prompted again
Reader reader;
try {
reader = new FileReader(GQLFile);
} catch (FileNotFoundException e) {
System.out.println("\nFile " + GQLFile +
" does not exist.\n");
System.out.print("GQL> ");
continue;
}
/////////////////////////////////////////////////////////////////
// PARSE QUERY
/////////////////////////////////////////////////////////////////
// The parser and Lexer objects are created in the parser.java
// and Lexer.java files, respectively - The parser takes the
// Lexer as an argument - the value variable generated by the
// parse() method will return the topmost grammar construct,
// which in this case is a Query object
parser p = new parser(new Lexer(reader));
Query query = (Query) p.parse().value;
/////////////////////////////////////////////////////////////////
System.out.println("\n----------------------------Input Query-----" +
"-----------------------\n");
System.out.println("\n SUCCESSFUL PARSE " +
" \n");
System.out.println("--------------------------------------" +
"------------------------------\n");
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// LOAD ALL CLASSES USED IN DATABASE INTO RUNTIME
/////////////////////////////////////////////////////////////////
// databse Classes should be kept on the CLASSPATH, or the path
// to these classes should be provided as a second command line
// argument
boolean coreClassesLoaded = loadCoreClasses(coreClassLoader,
classPath);
if (!coreClassesLoaded) {
System.err.println("\nError: one or more of core Classes"
+ "Node, Egge and SimplePath could not be found.\n");
db.close();
return;
}
//
System.out.println("Core classes loaded.\n");
boolean subclassesLoaded = query.loadSubclasses(subClassLoader,
classPath);
if (!subclassesLoaded) {
System.err.println("\nError: subclasses could not be" +
" loaded.\n");
db.close();
return;
}
//
System.out.println("Subclasses loaded.\n");
/////////////////////////////////////////////////////////////////
// MAKE SURE THE DATABASE ACTUALLY CONTAINS SOME OBJECTS AND,
// IF SO, PUT AN INSTANCE OF EACH CLASS REPRESENTED INTO THE
// LINKEDLIST CLASSLIST - SINCE WE LOADED THE DATABASE CLASSES
// INTO THE RUNTIME ENVIRONMENT, OBJECTS RETURNED BY DATABASE
// QUERIES WILL REMAIN TRUE TO THEIR TYPE; IF WE HADN'T DONE
// THIS, THESE OBJECTS WOULD BE RETURNED AS TYPE GENERICOBJECT
/////////////////////////////////////////////////////////////////
dbObjects = db.queryByExample(Object.class);
if (dbObjects.hasNext()) {
query.addClassesToList(dbObjects, classes);
} else {
System.err.println("\nError: no objects in database.\n");
db.close();
return;
}
//
System.out.println(classes);
/////////////////////////////////////////////////////////////////
// SEMANTIC CHECKS //
/////////////////////////////////////////////////////////////////
boolean headArgsAreSet = query.setHeadArgClasses(classes);
if (!headArgsAreSet) {
db.close();
return;
}
boolean typesMatch = query.checkQueryTypes(db);
if (!typesMatch) {
db.close();
return;
}
/////////////////////////////////////////////////////////////////
// EVALUATION
/////////////////////////////////////////////////////////////////
query.evaluateQuery(db);
} catch (Exception e) {
System.out.println("\nSYNTAX ERROR\n");
e.printStackTrace();
}
System.out.print("GQL> ");
} while (true);
System.out.println("\nExiting...\n");
db.close();
}
private static boolean loadCoreClasses(ClassLoader coreClassLoader,
String classPath) {
try {
coreClassLoader.loadClass("Node");
coreClassLoader.loadClass("Edge");
coreClassLoader.loadClass("SimplePath");
} catch (ClassNotFoundException cnfe) {
return false;
}
return true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
The strange thing is, the classes I need are definitely getting loaded into the runtime environment, as I use them to set some Class member variables, for example in the "SEMANTIC CHECKS" section. So it's like the application can see the dynamically loaded Classes, but the db4o API/database cannot. Also, I have the Class jar and the db4o jar set up as Netbeans libraries, not just in .../jre/lib/ext. Here's a snippet of the code in the Class where I actually use the db4o native query that's giving me problems...
////////////////////////////////////////////////////////////////////////////////////////////
public void evaluateQuery(ObjectContainer db) {
if (this.hasPredicate) {
;
} else {
if (this.isNode) {
List nodes = db.query(new Predicate() {
#Override
public boolean match(Node node) {
return (node.getName().equals("5"));
}
});
System.out.println("\n_________________RESULT__________________________");
System.out.println("\nNode: " + nodes.get(0).getName()
//+ ".\n");
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////
... if I do the following instead I still get an empty List...
////////////////////////////////////////////////////////////////////////////////////////////
public void evaluateQuery(ObjectContainer db) {
if (this.hasPredicate) {
;
} else {
if (this.isNode) {
List nodes = db.queryByExample(Node.class);
System.out.println(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
System.out.println("\nNode: " + nodes.get(i).getName());
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////
Hmm, I don't see any dynamic class loading problems here. You're using the system's classloader, which should be visible to db4o. You don't even need to load the classes, db4o will do that with the classloaders.
Are you sure that the application picks up the same database? Are you using a relative path?
Btw you can explicitly set the classloader for db4o, like this.
EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
JdkLoader classLookUp = new ClassLoaderLookup(
Thread.currentThread().getContextClassLoader(),
new URLClassLoader(new URL[]{new URL("file://./some/other/location")}));
configuration.common().reflectWith(new JdkReflector(classLookUp));
ObjectContainer container = Db4oEmbedded.openFile(configuration,"database.db4o");
Well it seems like this is a bug in Linux/Netbeans for Linux/Db4o. I used the exact same source files on a windows box and everything worked fine. I'm pretty disappointed, I don't want to have to use windows for this project. :/
Related
I'm trying to read a text file (dictionary.txt) which is located in src/main/resources, but I keep getting a file not found exception.
public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (Scanner sc = new Scanner(new File("/src/main/resources/dictionary/dictionary.txt"))){ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that d
}
System.out.println("Score is "+ ReviewScore);
}
}
public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (var resource = Review.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner sc = new Scanner(resource);{ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that is not found due to either typo or non-existence deduct 5pts
}
System.out.println("Score is "+ ReviewScore);
}
//frequentlyUsedWords (ReviewScore,Review);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new File. The name says it: That only works for FILES. Entries in jar files aren't themselves files.
If you write new File, or mention FileInputStream, you've lost. That cannot be made to work with this stuff.
Fortunately, you can just ask the JVM to give you a resource from the same place it loads class files, whereever those class files might be. In a jar, in a directory, live-loaded over a network - doesn't matter. You can get these resources in URL form and an InputStream form - any code that can work with those, can be made to work with 'resources that are in the same place my class files are, such as in the jar'.
Scanner is one of those things: It has a constructor that takes an inputstream. So, let's do that!
try (var resource = MyClassName.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner s = new Scanner(resource);
.. rest of code here
}
A few notes:
/dictionary/dictionary.txt means: Relative to the 'root of the jar'. If you want relative to your class file's package, don't start with a leading slash.
It's a resource, so it must be closed, hence, this code uses try-with-resources.
I have a login page and a sign up page in my program.
I want to run it only if the user says begin.
These pages are called in the main method of my class, and I have a speech recognizer class.
I want the program to continue only when String output.contains("begin") == true
I tried putting the Class.main(args) in my if(output.contains("begin") == true)) case, there was an unhandled exception, and when i surrounded that section with try and catch, it didn't work.
I was told that Inheriting and implementing the classes from my API will work, but I'm not quite sure how to do it.
final Microphone mic = new Microphone(FLACFileWriter.FLAC);
GSpeechDuplex duplex = new GSpeechDuplex("AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw");
duplex.setLanguage("en");
duplex.addResponseListener(new GSpeechResponseListener() {
String old_text = "";
public void onResponse(GoogleResponse gr) {
String output = gr.getResponse();
if (gr.getResponse() == null) {
this.old_text = response.getText();
if (this.old_text.contains("(")) {
this.old_text = this.old_text.substring(0,
this.old_text.indexOf('('));
}
System.out.println("Paragraph Line Added");
this.old_text = ( response.getText() + "\n" );
this.old_text = this.old_text.replace(")", "").replace("( ", "");
response.setText(this.old_text);
}
if (output.contains("(")) {
output = output.substring(0, output.indexOf('('));
}
if (!gr.getOtherPossibleResponses().isEmpty()) {
output = output + " (" + (String)
gr.getOtherPossibleResponses().get(0) + ")";
}
response.setText("");
response.append(this.old_text);
response.append(output);
System.out.println(output);
if(output.contains("begin") == true){
duplex.stopSpeechRecognition();
mic.close();
Trying_Different_Languages t = new Trying_Different_Languages();
frame.dispose();
}
}
});
Expect The program to begin when i say begin but
It it doesn't begin when I say begin.
The try and catch statements just help in error free compilation.
In a program there should exist only 1 public static void main(String[] args) method. That is the indicator which tells you there starts the program.
Instead of calling the main method you should add a different method which do the stuff you want at a specific point.
So in detail it can look like that:
public class SomeClass {
public static void someMethodName() {
//some stuff you want to execute
}
}
So and where you want to execute the code:
...
SomeClass.someMethodName(); //executes the stuff you want.
In this case it would work if you create different methods which do exactly that you need to do at a specific point.
I am trying to build a command parser which receives a block of data and parses that data into an instance of a specific command. This is basically then a factory whereby the instance returned from the factory is based on a key.
So more specifically, say a receive a block of raw binary data:
0x02 0x23 0x01 0x00 0x00 0x1f
And the 3rd byte in this stream defines the command, I want to create an instance of CommandOne. Obviously there will be additional methods to handle parsing the rest of the data according to the command, but the first step is getting that instance of the command from the command number. This where I say this is a factory using a key.
There are a lot of discussions on how to build factories in java, some very direct, some using various bits of generics and reflections; but I have had no luck finding a specific implementation that fits what I am trying to accomplish. I did however find bits and pieces that relate to what I am trying to accomplish and so I have put those together into an answer which is the first response below. Is this a good response or am I overlooking something simpler or something more complete?
The following is a generic form of the solution. This is all built into a single package containing all the commands and the factory. Note that adding a new command does not require any changes to the factory itself.
This is the abstract class which all commands must implement. It also contains the factory method getInstance.
public abstract class Commands
{
private static Map<Integer,Constructor<?>> commandConstructorMap = null;
private static void loadMap()
{
commandConstructorMap = new HashMap<Integer,Constructor<?>>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader == null) return;
String myPathName = Commands.class.getName();
String myPath[] = myPathName.split("\\.");
if(myPath == null || myPath.length <= 1) return;
int pkgLen = myPath.length - 1;
StringBuilder pkgNm = new StringBuilder();
pkgNm.append(myPath[0]);
for(int i=1;i<pkgLen;i++)
pkgNm.append(".").append(myPath[i]);
String packageName = pkgNm.toString();
String path = packageName.replace('.', '/');
Enumeration<URL> resources;
try
{
resources = classLoader.getResources(path);
}
catch(IOException ioe)
{
return; // failure, just leave constructor empty
}
List<File> dirs = new ArrayList<File>();
while(resources.hasMoreElements())
dirs.add(new File(resources.nextElement().getFile()));
for(File dir:dirs)
{
if(!dir.exists() || !dir.isDirectory()) continue;
File[] files = dir.listFiles();
for(File file:files)
{
if(!file.isFile()) continue;
String fileName = file.getName();
if(!fileName.endsWith(".class")) continue;
try
{
String className = packageName+'.'+fileName.substring(0, fileName.length()-6);
Class<?> clazz = Class.forName(className);
Constructor<?> cons = clazz.getConstructor();
Object instance = cons.newInstance();
if(instance instanceof Commands)
{
commandConstructorMap.put(new Integer(((Commands) instance).getCommand()),cons);
}
}
catch(Exception e){} // do nothing special for exception, just don't add to map
}
}
}
public static Commands getInstance(Integer command) throws Exception
{
if(commandConstructorMap == null)
{
loadMap();
}
if(commandConstructorMap.containsKey(command))
return (Commands)commandConstructorMap.get(cmd).newInstance();
throw new Exception();
}
abstract Integer getCommand();
}
Note the return type of the abstracted getCommand is the same as the type used as the key, this is the relationship conrtol and can be almost any desired object type. One caveat of this mechanism is that this does create and ultimately discard one instance of every command object, but it does this only once, future calls will only create a single instance of the class indicated by the key.
This is an example of one of the command file implementations, obviously there would need to be other code related to building all the specifics of that command, the goal here is just to demonstrate how to build the part of the command class that is utilized in the factory.
public class CommandOne
extends Commands
{
Integer getCommand()
{
return new Integer(1);
}
}
And finally a demonstration of how this works
public static void main(String[] args)
{
try
{
Commands cmd = Commands.getInstance(new Integer(1));
if(cmd instanceof CommandOne)
System.out.println("Command using key 1 is: "+cmd.getClass().getSimpleName());
cmd = Commands.getInstance(new Integer(2));
if(cmd instanceof CommandTwo)
System.out.println("Command using key 2 is: "+cmd.getClass().getSimpleName());
cmd = Commands.getInstance(new Integer(3));
if(cmd instanceof CommandThree)
System.out.println("Command using key 3 is: "+cmd.getClass().getSimpleName());
}
catch(Exception e)
{
System.out.println("Command instantiation failed");
}
}
The results of running this (assuming there are definitions for commands CommandTwo and CommandThree as well as the demonstrated CommandOne) would be something like this:
Command using key 1 is: CommandOne
Command using key 2 is: CommandTwo
Command using key 3 is: CommandThree
I'm having problems with my try-catch exception here. Actually what it does is to prompt the user for the name of a text file say, Robot.txt but if say the file does not exist, I have to make sure that the application reprompts the user for the file name. Hope you guys can understand I'm still a newbie here so please feel free to provide suggestions or advices on my coding etc. Cheers!
Main method class:
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
class TestVector3 {
public static void main(String [] args)
{
System.out.println("Please enter the name of the text file to read: ");
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
KillerRobot robot;
Scanner fileInput = null;
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :"); //Reprompt user for name of the text file
fileInput = new Scanner(userInput.nextLine());
}
while(fileInput.hasNext())
{
robot = new KillerRobot();
String first = fileInput.next();
robot.setName(first);
String second = fileInput.next();
robot.setMainWeapon(second);
int third = fileInput.nextInt();
robot.setNumberOfKills(third);
robotDetails.add(robot);
}
for(KillerRobot i : robotDetails)
{
System.out.println(i);
}
fileInput.close();
}
}
KillerRobot class file:
class KillerRobot {
private String name;
private String mainWeapon;
private int numberOfKills;
KillerRobot()
{
}
public String getName()
{
return name;
}
public String getMainWeapon()
{
return mainWeapon;
}
public int getNumberOfKills()
{
return numberOfKills;
}
public String toString()
{
return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}
public void setName(String a)
{
name = a;
}
public void setMainWeapon(String b)
{
mainWeapon = b;
}
public void setNumberOfKills(int c)
{
numberOfKills = c;
}
}
As you state that you are a beginner, let us first look at the relevant part of your code, to make sure that we talk about the same thing:
Scanner fileInput = null;
try {
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You have an input and you want to check this input for a condition and require a new input until this condition is fulfilled. This problem can be solved using a loop like the following:
Scanner fileInput = null;
do {
System.out.println("Enter file name :");
try {
fileInput = new Scanner(new File(userInput.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
}
} while(fileInput == null);
So finally, why does this work? The fileInput variable is set to null and will remain null until the given file is successfully read from standard input because an exception is thrown otherwise what prevents the fileInput variable to be set. This procedure can be repeated endlessly.
On a side note, for performance reasons, it is normally not a good idea to implement control flow that is based on exceptions. It would be better to check for a condition if a file exists via File::exists. However, if you read the file after checking for its existence, it might have been deleted in the meantime which introduces a racing condition.
Answer to your comment: In Java (or almost any programming language), you can inline expressions. This means that instead of calling two methods in two different statements as in
Foo foo = method1();
Bar bar = method2(foo);
you can simply call
Bar bar = method2(method1());
This way, you save yourself some space (what becomes more and more important if your code gets longer) as you do not need the value that you saved in foo at any other place in your code. Similarly, you can inline (which is how this pattern is called) from
File file = new File(userInput.nextLine())
fileInput = new Scanner(file);
into
fileInput = new Scanner(new File(userInput.nextLine()));
as the file variable is only read when creating the Scanner.
Try putting the try-catch in a loop like below:
Scanner fileInput = null;
while (fileInput==null)
{
try
{
System.out.println("Please enter the file name.");
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
}
}
Next you could think of moving the File creation part into separate method, so that the code was cleaner.
Do not fall for try-catch instead add this as your functionality. Exceptions are naturally for run time error handling not for logic building.
Check if file exists at given location.
File textFile = new File(userInput.nextLine());
// Check if file is present and is not a directory
if(!textFile.exists() || textFile.isDirectory()) {
System.out.println("Error - file not found!");
//Reprompt user for name of the text file
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You can put while loop instead of if loop if you want to continuously prompt user until correct path is entered.
You can call back your main(), like following
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
main(args); // recursively call main() method
}
Now if user first attempt wrong then your code will asked to re enter file name.
How to check isFile exist?
File file = new File(filePathString);
if(file.exists() && !file.isDirectory()){
System.out.println("file exist");
}
This really is an XY problem because you assumed the only way to check for a file existence is by catching a FileNotFoundException (hence asking about try-catch exception handling) whereas other means exist to help you avoid a try-catch idiom in an elegant manner.
To check if a file exists at the given path or not you can simply use the File.exists method. Please also see the File.isFile method and/or the File.isDirectory method to verify the nature of the targeted File object.
EDIT : As stated by raphw, this solution is best used in simple scenario since it can incur a race condition in the case of concurrent file deletion happening during the file existence check. See his answer for handling more complex scenario.
I am not a good programmer. In school, I learned MATLAB. So i have no idea what I am doing.
I am working with the ThingMagic M6 reader. They have their own API. I wanted to create my own application to read the program. I want to use a sample program that they have supplied (since my program doesn't seem to work). However, the supplied program only accepts command line arguments. How do i change it so I can pass arguments to it in my code.
This is the supplied code: (at the command line I input tmr://10.0.0.101)
/**
* Sample program that reads tags for a fixed period of time (500ms)
* and prints the tags found.
*/
// Import the API
package samples;
import com.thingmagic.*;
public class read
{
static void usage()
{
System.out.printf("Usage: demo reader-uri <command> [args]\n" +
" (URI: 'tmr:///COM1' or 'tmr://astra-2100d3/' " +
"or 'tmr:///dev/ttyS0')\n\n" +
"Available commands:\n");
System.exit(1);
}
public static void setTrace(Reader r, String args[])
{
if (args[0].toLowerCase().equals("on"))
{
r.addTransportListener(r.simpleTransportListener);
}
}
static class TagReadListener implements ReadListener
{
public void tagRead(Reader r, TagReadData t) {
System.out.println("Tag Read " + t);
}
}
public static void main(String argv[])
{
System.out.println(argv.getClass().toString());
// Program setup
TagFilter target;
Reader r;
int nextarg;
boolean trace;
r = null;
target = null;
trace = false;
nextarg = 0;
if (argv.length < 1)
usage();
if (argv[nextarg].equals("-v"))
{
trace = true;
nextarg++;
System.out.println("Trace");
}
// Create Reader object, connecting to physical device
try
{
TagReadData[] tagReads;
r = Reader.create(argv[nextarg]);
if (trace)
{
setTrace(r, new String[] {"on"});
}
r.connect();
if (Reader.Region.UNSPEC == (Reader.Region)r.paramGet("/reader/region/id"))
{
r.paramSet("/reader/region/id", Reader.Region.NA);
}
r.addReadListener(new TagReadListener() );
// Read tags
tagReads = r.read(500);
// Print tag reads
for (TagReadData tr : tagReads)
System.out.println(tr.toString());
// Shut down reader
r.destroy();
}
catch (ReaderException re)
{
System.out.println("Reader Exception : " + re.getMessage());
}
catch (Exception re)
{
System.out.println("Exception : " + re.getMessage());
}
}
}
This is me trying to use it: (arg comes from a JTextField)
String[] argv = new String[1];
argv[0] = arg;
readOnceApp(argv);
I have a feeling there is a really simple answer to this problem, I just can't figure it out. I searched the internet for a few days and read books, and still can't figure it out. Any help is appreciated. Thank You.
edit: readOnceApp is one method I wrote. It is basically just the main method of the supplied code. I can include it, if it will help. I just didn't want to post too much code.
If you want to call the "main" method of a class from another class, do it like this:
String [] args = new String [1];
args[0]= "some param";
readOnceApp.main(args);
This is making the assumption that "readOnceApp" is the name of your class. (BTW, you should follow the convention of using capitalized class names, e.g. ReadOnceApp).
Hope this helps.