What Are My args[]? - java

I've gotten ahead of myself and am taking a semester, which requires that I have knowledge of Java beyond what I've learned. I have no idea how I command like arguments are passed to the main argument, apart from "echo Java foo bar" through the command line
I'm trying to parse JSON through java; I hope that the code below is enough
This is my method:
public static void parseCrewWithListMapping(String filePath) {
ObjectMapper mapper = new ObjectMapper();
try {
List<Crew> crews = mapper.readValue(new File(filePath),
mapper.getTypeFactory().constructCollectionType(List.class, Crew.class));
for(Crew crew : crews) {
System.out.println(crew);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is my main method trying to run this method.
public class CrewParsing {
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException, XMLStreamException {
if(args.length < 1)
throw new RuntimeException("No argument exception");
System.out.println("Parsing Crew Names");
CrewParser.parseCrewWithListMapping(args[2]);
System.out.println("Finished\n\n");
}
}
All my files are in the correct places, I'm trying to recreate this:
public static void parseJSONWithListMapping(String filePath) {
ObjectMapper mapper = new ObjectMapper();
try {
List<Employee> employees = mapper.readValue(new File(filePath),
mapper.getTypeFactory().constructCollectionType(List.class, Employee.class));
for(Employee employee : employees){
System.out.println(employee);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Method:
public static void parseJSONWithListMapping(String filePath) {
ObjectMapper mapper = new ObjectMapper();
try {
List<Employee> employees = mapper.readValue(new File(filePath),
mapper.getTypeFactory().constructCollectionType(List.class, Employee.class));
for(Employee employee : employees){
System.out.println(employee);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
main method (which worked):
public class Practice1Test {
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException, XMLStreamException {
if(args.length < 1)
throw new RuntimeException("No argument exception");
System.out.println("Parsing Crew Names");
CrewParser.parseJSONWithListMapping(args[2]);
System.out.println("Finished\n\n");
}
}
When passing args[2] as the arguments for parseJSONWithListMapping in the code that worked, I got my json results just fine.
But when I tried my code, the "no argument exception" was run, which I assume is telling me that there were no arguments passed.
What could be the problem? I really hope that this is enough detail ;_;

You're checking args.length < 1 and throwing the "No argument exception", but then you're trying to use args[2], which is the third command-line argument.
If you want the first, it's args[0], the second is args[1], and so on. If you require one argument, your args.length < 1 is correct and you'd use args[0]. If you require two arguments, you'd use args.length < 2 for the error and then use args[0] and args[1].

When you run your program from the command-line, you may pass in the list of arguments, such as:
java CrewParsing jsonPath1 jsonPath2 jsonPath3
If you are running from an IDE such as Eclipse, you are probably just clicking the Run or Debug and forgetting to enter in any arguments. In Eclipse - right-click your main class and when you hover over the Run(or Debug) as... choose run(debug) configuration. There is a tab for arguments, and you can enter them there. The program you are copying from probably has them set up already.
If you want some more information on arguments I find the Oracle command line tutorial explains it well: (All taken from link)
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter:
java Sort friends.txt
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt".
The Echo example displays each of its command-line arguments on a line by itself:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java
Drink
Hot
Java
//3 separate arguments are all printed out - args[0], args[1], args[2]
If you're still not sure what arguments you actually have, I would try printing out your arguments like that tutorial shows you.

Related

Encog Image Recognition, Invalid command Error

I am trying to run image recognition code in Encog framework.
This one
But I am having problems with the input. I am getting the following error
I am trying to get the picture into the program. I did it the following way.
public static void main(final String[] args) {
/*
if (args.length < 1) {
System.out
.println("Must specify command file. See source for format.");
} else {
*/
String string = "/Users/hehe/Downloads/Screenshot_2023-01-08_at_08.11.24-removebg-preview.png";
try {
final ImageNeuralNetwork program = new ImageNeuralNetwork();
program.execute(string);
} catch (final Exception e) {
e.printStackTrace();
}
Encog.getInstance().shutdown();
}
I commented first part of the code because I can't run this program in command line.
When I try to compile it like this
javac /Users/hehe/IdeaProjects/TestRencognition/src/main/java/ImageNeuralNetwork.java
I am getting error that the package org.encog does not exist

Compile and run a Java program from another Java program

I am writing a program that takes the path to the input ".java" file with a main method. The program should then compile that file, and run it.
Let's say that the program I am trying to compile and run looks like this:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
The program that performs compilation and tries to run it:
Evaluator.java
/**
* Matches any .java file.
*/
private static final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.java");
private static String path;
/**
* Program entry point. Obtains the path to the .java file as a command line argument.
*
* #param args One argument from the command line: path to the .java file.
* #throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException(
"Expected exactly one argument from the command line.");
}
if (!matcher.matches(Paths.get(args[0]))) {
throw new IllegalArgumentException(
String.format("File %s is not a valid java file.", args[0]));
}
// path is in a valid format
path = args[0];
// compile a program
compile();
// run a program
run();
}
/**
* Compiles a program.
*
* #throws Exception
*/
private static void compile() throws Exception {
System.out.println("Compiling the program ...");
Process p = Runtime.getRuntime().exec("javac " + path);
output("Std.In", p.getInputStream());
output("Std.Out", p.getErrorStream());
p.waitFor();
System.out.println("Program successfully compiled!\n");
}
/**
* Runs a program.
*
* #throws Exception
*/
private static void run() throws Exception {
System.out.println("Executing the program ...");
Process p = Runtime.getRuntime().exec("java " + getProgramName(path));
output("Std.In", p.getInputStream());
output("Std.Out", p.getErrorStream());
p.waitFor();
System.out.println("Program finished!");
}
private static void output(String stream, InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, CS));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(String.format("%s: %s", stream, line));
}
}
private static String getProgramName(String path) {
return path.replace(".java", "");
}
}
My "Main.java" file is located in the project root. I am running the program with a command line argument "./Main.java". Doing so, compiles the program correctly and yields a new file "Main.class". However, the run method outputs as follows:
Std.Out: Error: Could not find or load main class ..Main
What should be the problem here?
Try to set to java process you're launching the correct working directory and then set the related classpath.
This should help.
Update
I suggest to use the method Runtime.getRuntime().exec(String command, String[] envp, File dir).
Last parameter dir is the process working directory.
The Problem here is you are passing argument
./Main.java
instead, you should pass Main.java as an argument else you need to change your getProgramName() method to return the Class name correctly.
Which will let you compile the program perfectly with javac command but problem happens when you need to run the program because that command should be
java Main
whereas you are trying to execute
java ./Main

Running Mac OSX commands from eclipse using java

I'm trying to make a simple java program to unhide the ~\Library\ folder on osx using terminal commands. As far as I have researched the code to run system commands from java is
Runtime.getRuntime().exec();
and is listed as such in every place I look it up.
However, my program doesn't work. Main method below.
public static void main(String[] args) throws IOException {
String[] noHide = {"chflags"," " ,"nohidden"," ", "~/Library/"};
try {
Runtime.getRuntime().exec(noHide);
System.out.println("library unhidden");
} catch (Exception e ) {
e.printStackTrace();
}
}
This program throws no exception, and compiles and executes fine, but the Library folder simply won't unhide. No matter what I reformat the cmd String. None of the formats below work
String noHide = "chflags nohidden ~/Library";
String[] noHide = {"chflags", "nohidden","~/Library"};
String[] noHide = {"chflags"," " ,"nohidden"," ", "~/Library/"};
If I remove the spaces they throw exceptions (well, not the String array objects). I can run the command (chflags noHidden ~/Library) absolutely fine from the osx terminal. Anyone have an idea why?
You need to use a try and catch, which you have. But, your main should be like this:
public static void main(String[] args) {
String[] noHide = {"chflags", "nohidden","~/Library"};
try {
Runtime.getRuntime().exec(noHide);
}
catch (Exception e) {
}
}
Basically, you don't need throws IOException. This worked for me, so if it still isn't working in your program, there may be a bigger problem with the way you have something set up.

How to call a class that accepts command line arguments?

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.

Java exception handling method

I'm having a little bit of trouble implementing the following method while handling the 3 exceptions I'm supposed to take care of. Should I include the try/catch blocks like I'm doing or is that to be left for the application instead of the class design?
The method says I'm supposed to implement this:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException
This method loads the info from the archive specified in a catalog of products and returns the catalog.
It starts by opening the file for reading. Then it proceeds to read and process each line of the file.
The method String.startsWith is used to determine the type of line:
If the type of line is "Product", the method readProduct is called.
If the type of line is "Coffee", the method readCoffee is called.
If the type of line is "Brewer", the method readCoffeeBrewer is called.
After the line is processed, loadCatalog adds the product (product, coffee or brewer) to the catalog of products.
When all the lines of the file have been processed, loadCatalog returns the Catalog of products to the method that makes the call.
This method can throw the following exceptions:
FileNotFoundException — if the files specified does not exist.
IOException — If there is an error reading the info of the specified file.
DataFormatException — if a line has errors(the exception must include the line that has the wrong data)
Here is what I have so far:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException{
String line = "";
try {
BufferedReader stdIn = new BufferedReader(new FileReader("catalog.dat"));
try {
BufferedReader input = new BufferedReader(
new FileReader(stdIn.readLine()));
while(! stdIn.ready()){
line = input.readLine();
if(line.startsWith("Product")){
try {
readProduct(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Coffee")){
try {
readCoffee(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Brewer")){
try {
readCoffeeBrewer(line);
} catch(DataFormatException d){
d.getMessage();
}
}
}
} catch (IOException io){
io.getMessage();
}
}catch (FileNotFoundException f) {
System.out.println(f.getMessage());
}
return null;
}
It depends on whether you want the class or another portion of the application that is using it to handle the exception and do whatever is required.
Since the code that will use the loadCatalog() probably won't know what to do with a file I/O or format exception, personally, I'd go with creating an exception like CatalogLoadException and throw it from within the loadCatalog() method, and put the cause exception (FileNotFoundException, IOException, DataFormatException) inside it while including an informative message depending on which exception was triggered.
try {
...
//do this for exceptions you are interested in.
} catch(Exception e) {
//maybe do some clean-up here.
throw new CatalogLoadException(e); // e is the cause.
}
This way your loadCatalog() method will only throw one single and meaningful exception.
Now the code that will use loadCatalog() will only have to deal with one exception: CatalogLoadException.
loadCatalog(String filename) throws CatalogLoadException
This also allows your method to hide its implementation details so you do not have to change its "exception throwing" signature when the underlying low level structure changes. Note that if you change this signature, every piece of code would need to change accordingly to deal with the new types of exceptions you have introduced.
See also this question on Exception Translation.
Update on the throwing signature requirement:
If you have to keep that signature then you don't really have a choice but to throw them to the application and not catch them inside the loadCatalog() method, otherwise the throws signature would be sort of useless, since we aren't going to throw the exact same exception that we have just dealt with.
The general idea is that you percolate exceptions up to the appropriate place to handle them. I am going to guess that your instructor expects them to be handled in main. In this case I can guess that because of the throws clause you were given. A simple rule of thumb is that if the method declares the exception in the throws clause you do not catch it in that method. So the method you are writing should have no catch statements.
To do that you would change your code something like:
public Catalog loadCatalog(String filename)
throws FileNotFoundException,
IOException,
DataFormatException
{
String line = "";
BufferedReader stdIn = new BufferedReader(new FileReader("catalog.dat"));
BufferedReader input = new BufferedReader(new FileReader(stdIn.readLine()));
while(!stdIn.ready())
{
line = input.readLine();
if(line.startsWith("Product"))
{
readProduct(line);
}
else if(line.startsWith("Coffee"))
{
readCoffee(line);
}
else if(line.startsWith("Brewer"))
{
readCoffeeBrewer(line);
}
}
return null;
}
and then in the method (presumably main) that calls loadCatalog you would have:
try
{
loadCatalog(...);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(DataFormatException ex)
{
ex.printStackTrace();
}
replacing the printStackTrace with something appropriate.
That way the method, loadCatalog, doesn't deal with displaying the error messages, so you can call the method in GUI or console code and the code that calls it can choose how to display the error to the user (or deal with it in some way).
Here is an excellent article of Heinz Kabutz, dealing with exception handling.
http://www.javaspecialists.eu/archive/Issue162.html

Categories

Resources