Control program from command line arguments - java

How do I pick the methods in my program to run using command line arguments? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.

You can parse arguments with a function like this:
private void parseArguments(String[] args)
{
int i = 0;
String curArg;
while (i < args.length && args[i].startsWith("-"))
{
curArg = args[i++];
if ("-S".compareTo(curArg) == 0)
{
if (i < args.length)
{
String image = args[i++];
processImage()
}
else
{
// ERROR
}
}
}
}
Your main method should always have String[] args which contains arguments split on the space character. There are also plenty of libraries you can use to parse command line arguments. This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).

http://commons.apache.org/cli/
This should help. and here's how to use it:
http://commons.apache.org/cli/usage.html

You may need to write different methods for each purpose and have if/else conditions based on command input.

why not read the arguments passed and read subsequent value to do the required stuff
ie,
java yourprogram -a1 something -a2 somethingelse
and in your program
public static void main(String[] args){
for(int i=0;i<args.length;i++){
switch(args[i]){//you can use if-else to deal with string...
case "-a1":read args[i+1] to get value to do somethng
case "-a2": read args[i+1] to get value to do something else
}
}

Related

Can anybody tell what error or where am i going wrong in code?

I am getting error while taking input with Integer.parseInt(args[0]); error is in args section i know i can change it to scanner but i want to know this method.
Can anybody point out or show the solution to my problem?
class NegativeOutputException extends Exception{
private final int ex;
NegativeOutputException(int a){
ex = a;
}
public String toString(){
return "NegativeOutputException!("+ex+")";
}
}
public class practice6_creating_custom_exception {
public static void main(String args[]){
int x = Integer.parseInt(args[0]);//Error Here argument at position one
int y = Integer.parseInt(args[1]);//argument at position two
//argument at position twenty one which doesn't exsist
int a;
try{
a = x * y;
if(a < 0)
throw new NegativeOutputException(a);
System.out.println("Output >>" + a);
}
catch(NegativeOutputException e){
System.out.println("Caught >>" + e);
}
}
}
Output::
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at practice6_creating_custom_exception.main(practice6_creating_custom_exception.java:21)
Process finished with exit code 1
It gives you a java. lang.ArrayIndexOutOfBoundsException because you are trying to access a position in an empty array.
parseInt() is not used for taking inputs in such a case you need to use Scanner
For your case, you need first take input (by using Scanner) and then assign it to an integer variable, directly parsing the argument array will not provide the input.
Scanner sc = new Scanner();
int x = sc.nextInt(); //Scans the next token of the input as an int
parseInt() function -
The parseInt() method parses a value as a string and returns the first integer.
Source
Scanner Class -
Scanner object holds the address of InputStream object present in the
System class. Input Stream object of system class reads data from the
keyboard which is byte stream/byte form. The Scanner class converts
this read byte into a specific data type.
Source
The parseInt() function cannot read data from the input stream which is byte stream/byte form, hence you cannot directly parse the args[] array and assign it to an integer variable as it is empty since it is not yet scanned.
If you are looking for different ways of taking input in Java then here they are:
Using Buffer Reader Class,
Using Scanner Class,
Using Console Class,
Using Command Line Argument,
Source
Most probably you are simply not passing any arguments.
One way to pass arguments to the main method in Java is with the command to run the application in terminal. You can simply add the arguments after the java command to run the application separating them with a space. If you want the user to input the data, then you should use Scanner instead.
In your case, navigate to the folder where your java file sits and run the following:
java practice6_creating_custom_exception 0 1
In this example, 0 and 1 are the arguments you are passing.
If you are using an IDE then this can usually be done in the run configurations.
Side note, you might need to compile the application before running it and the command for that is the following:
javac practice6_creating_custom_exception.java

how to clear console in java (using eclipse) [duplicate]

Can any body please tell me what code is used for clear screen in Java?
For example, in C++:
system("CLS");
What code is used in Java to clear the screen?
Since there are several answers here showing non-working code for Windows, here is a clarification:
Runtime.getRuntime().exec("cls");
This command does not work, for two reasons:
There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.
When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.
To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.
You can use following code to clear command line console:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
Caveats:
This will work on terminals that support ANSI escape codes
It will not work on Windows' CMD
It will not work in the IDE's terminal
For further reading visit this
This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).
public final static void clearConsole()
{
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
⚠️ Note that this method generally will not clear the console if you are running inside an IDE.
A way to get this can be print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.
Here is a sample code:
for (int i = 0; i < 50; ++i) System.out.println();
Try the following :
System.out.print("\033\143");
This will work fine in Linux environment
Create a method in your class like this: [as #Holger said here.]
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).
As an alternate method is to write this code in clrscr():
for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
System.out.print("\b"); // Prints a backspace
I will not recommend you to use this method.
If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.
Something like the following code worked for me:
import jline.console.ConsoleReader;
public class JLineTest
{
public static void main(String... args)
throws Exception
{
ConsoleReader r = new ConsoleReader();
while (true)
{
r.println("Good morning");
r.flush();
String input = r.readLine("prompt>");
if ("clear".equals(input))
r.clearScreen();
else if ("exit".equals(input))
return;
else
System.out.println("You typed '" + input + "'.");
}
}
}
When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.
Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -
for(int clear = 0; clear < 1000; clear++)
{
System.out.println("\b") ;
}
Hope this is useful
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
Try this: only works on console, not in NetBeans integrated console.
public static void cls(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c",
"cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This will work if you are doing this in Bluej or any other similar software.
System.out.print('\u000C');
You can use an emulation of cls with
for (int i = 0; i < 50; ++i) System.out.println();
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
You need to use JNI.
First of all use create a .dll using visual studio, that call system("cls").
After that use JNI to use this DDL.
I found this article that is nice:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

How do I set the size of the array my command line arguments will be stored in?

I basically want to store my user input in an array of size 3. When I seem to put 3 in the main (String [3] args), it doesn't seem to do what I want. How do I resolve this issue?
If it helps, the exercise is asking me to: Fill in the class method main of class Ex4 with code that
create an array of size 3 containing strings and fills it with command line arguments.
Thanks.
public class Ex4 {
public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(args[0]);
}
else if (args.length == 2 || args.length == 3)
{
System.out.println(args[0]);
System.out.println(args[1]);
}
else
System.out.println("Too many arguments");
}
}
You can't control the size of the array passed to the main method. It will automatically be allocated with the size of the arguments passed to the program.
You get it backwards.
You define the size of that array implicitly, by the number of arguments that you pass when starting the JVM.
At runtime, within your Java code you can only check the actual length of that array. For example to give an error message to the user telling him about the required number of arguments and their meaning.

Passing a file argument in Java

I am wondering how to pass a file as an argument on linux command line.
public class Main {
public static void main(String[] args){
System.out.println(args[0]);
}
}
For the above code if I do:
java -jar myJava.jar blah.txt
It prints blah.txt to the screen.
But I have a sample line of code that looks like this:
java -jar myJava.jar < blah.txt
How am I able to get the value of blah.txt from the above command?
Use one of the techniques for reading from System.in where the file is being redirected such as Scanner
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
try the following
java -jar myJava.jar 'blah.txt'
The quotes indicate that the argument is literal.
double quotes will also work, but will not prevent things like variable expansion, so single quotes is better when trying to pass a literal string.

why testing args.length?

I'm a Java beginner and I'm confused about testing args.length at the begining of many codes, and why it's never gets higher than 0 in any of my codes?
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
public class LowPortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of "
+ host);
}
catch (UnknownHostException ex) {
System.err.println(ex);
break;
}
catch (IOException ex) {}
} // end for
} // end main
} // end PortScanner
You have to inputs to main mathod from Command prompt.
like below
java LowPortScanner TEST1 TEST2
Because if it is not tested then an exception would be thrown because host = args[0]; would illegal.
However, this doesn't look like it's going to help much, an empty or null host looks like it would cause further problems.
If the length of args is always 0, then be sure you're actually passing in parameter arguments.
If there are no command arguments the args[0] will fail. This is why it must be protected.
It depends on how you invoke the Java class file. In command prompt or bash shell:
java LowPortScanner Argument1
typing the above line in the command prompt/bash will cause the argument count to increase to 1. (because Argument1 is one argument, after the class file LowPortScanner)
java LowPortScanner Argument1 Argument2
the above line will make argument count to increase to 2.
hence args.length will be 2 in the second case and 1 in the first case.
If you are calling your program from CMD or bash you can asign ARGuments it like
java LowPortScanner google.com
Then "google.com" is your args[0]. When your program supports commandline attributes it is recommended to test if the given arguments are corret.
The variable String[] args hold all the parameter pass to the program thorough command line if you are not passing any argument then the length of args become 0. Now it's better to check it's length before accessing it other wise there is chance to get ArrayIndexOutOfBoundsException if it's size is 0
args in public static void main(String[] args is the String array of arguments passed from command line.
java LowPortScanner argument1 argument2
if you try the above command args.length will return 2.
As far as question of checking the length it is done for java programs which can take command line arguments and if arguments are not passed then they prompt for input.
if(args.length >0 ){
//proceed using passed arguments
}else{
//proceed with some default value
}
You are running your program using java LowPortScanner hence no arguments are passed and args.length is always zero.
Moreover if you don't pass any argument and use host=args[0] you will get ArrayIndexOutOfBoundsException.

Categories