How to read and write text files from the main in java - java

The static method main, which receives an array of strings. The array should have two elements: the path where the files are located (at index 0), and the name of the files to process (at index 1). For example, if the name was “Walmart” then the program should use “Walmart.cmd” (from which it will read commands) and “Walmart.pro” (from which it will read/write products).
I don't want anyone to write the code for me because this is something I need to learn. However I've been reading this through and the wording is confusing. If someone could help me understand what it wants from me through pseudo-code or an algorithm it would be greatly appreciated.

Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
The main method's String array input argument consists of whatever String arguments you pass to the program's main method when you run the program. For example, here is a simple program that loops over args and prints a nice message with each argument's index and value on a separate line:
package com.example;
public class MainExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.printf("args[%d]=%s\n", i, args[i]);
}
}
}
Once you've compiled the program, you can run it on the command-line and pass it some arguments:
java -cp . com.example.MainExample eh? be sea 1 2 3 "multiple words"
Output:
args[0]=eh?
args[1]=be
args[2]=sea
args[3]=1
args[4]=2
args[5]=3
args[6]=multiple words

So lets explain to you
Create a class Inventory : if you don't know how to create a class google it just as is
The static method main: Every executable class in java (at least from the console) has the main method you should google java main method and propably in the same place you find it you will see the default arguments that it receives
When you learn about the default arguments of method main you will undertand about the 'args' that has to be on it
You will have t study the class String google it "java String class"
You will have to study the class File google it "java File class"
At the end everything else would be just logic and I beleave you have learned some at this point.

public class Inventory { // class inventory
public static void main(String[] args) // main method
{
if(args.length==2){ // check if args contains two elements
String filePath = args[0];
String fileName = args[1];
filePath+= System.getProperty("file.separator")+fileName;
File fileCMD = new File(filePath+".cmd");
//fileCMD.createNewFile();
File filePRO =new File(filePath+".pro");
//filePRO.createNewFile();
}
else {
//write the code to print the message Usage: java Inventory Incorrect number of parameters for a while and exit the program.
}
}
This is what I've understood. Basically you have to write a program to create two files, one called fileName.cmd and the other fileName.pro. You have to construct the path of the files using the arguments (input parameters of the main method) and system's file separator. If the arguments don't have two elements you have to print the 'invalid' message. That's it.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
You have to use command line to pass the arguments and launch the program , something like the following code in cmd or terminal:
java inventory thePath theFileName
That's how it get initialized.

Related

Why do we use a String array in the main function of Java? [duplicate]

I'm just beginning to write programs in Java. What does the following Java code mean?
public static void main(String[] args)
What is String[] args?
When would you use these args?
Source code and/or examples are preferred over abstract explanations.
In Java args contains the supplied command-line arguments as an array of String objects.
In other words, if you run your program in your terminal as :
C:/ java MyProgram one two
then args will contain ["one", "two"].
If you wanted to output the contents of args, you can just loop through them like this...
public class ArgumentExample {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
The program will print in the terminal:
C:/ java MyProgram one two
one
two
C:/
Those are for command-line arguments in Java.
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
The reason for this is to configure your application to run a particular way or provide it with some piece of information it needs.
If you are new to Java, I highly recommend reading through the official Oracle's Java™ Tutorials.
args contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:
$ java MyProg -f file.txt
Then args will be an array containing the strings "-f" and "file.txt".
The following answer is based my understanding & some test.
What is String[] args ?
Ans:
String[] -> As we know this is a simple String array.
args -> is the name of an array it can be anything (e.g. a, ar, argument, param, parameter) no issues with compiler & executed & I tested as well.
E.g:
public static void main(String[] argument)
public static void main(String[] parameter)
When would you use these args?
Ans->
The main function is designed very intelligently by developers. Actual thinking is very deep. Which is basically developed under consideration of C & C++ based on Command line argument but nowadays nobody uses it more.
1- User can enter any type of data from the command line can be Number or String & necessary to accept it by the compiler which datatype we should have to use? see the thing 2
2- String is the datatype which supports all of the primitive datatypes like int, long, float, double, byte, shot, char in Java. You can easily parse it in any primitive datatype.
E.g: The following program is compiled & executed & I tested as well.
If input is -> 1 1
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] parameter)
{
System.out.println(parameter[0] + parameter[1]); // Output is 11
//Comment out below code in case of String
System.out.println(Integer.parseInt(parameter[0]) + Integer.parseInt(parameter[1])); //Output is 2
System.out.println(Float.parseFloat(parameter[0]) + Float.parseFloat(parameter[1])); //Output is 2.0
System.out.println(Long.parseLong(parameter[0]) + Long.parseLong(parameter[1])); //Output is 2
System.out.println(Double.parseDouble(parameter[0]) + Double.parseDouble(parameter[1])); //Output is 2.0
}
}
Even tho OP is only talking about the String[] args, i want to give a complete example of the public static void main(String[] args).
Public : is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only.
String[] args : is the parameter to the main Method.
If you look into JDK source code (jdk-src\j2se\src\share\bin\java.c):
/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
...
{ /* Make sure the main method is public */
...
mods = (*env)->CallIntMethod(env, obj, mid);
if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
message = "Main method not public.";
messageDest = JNI_TRUE;
goto leave;
...
You can see that the starting method in java must be named main and must have the specific signature public static void main(String[] args)
The code also tells us that the public static void main(String[] args) is not fixed, if you change the code in (jdk-src\j2se\src\share\bin\java.c) to another signature, it will work but changing this will give you other possible problems because of the java specs
Offtopic: It's been 7 years since OP asked this question, my guess is that OP can answer his own question by now.
I would break up
public static void main(String args[])
in parts.
"public" means that main() can be called from anywhere.
"static" means that main() doesn't belong to a specific object
"void" means that main() returns no value
"main" is the name of a function. main() is special because it is the start of the program.
"String[]" means an array of String.
"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.
String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.
String [] args is also how you declare an array of Strings in Java.
In this method signature, the array args will be filled with values when the method is called (as the other examples here show). Since you're learning though, it's worth understanding that this args array is just like if you created one yourself in a method, as in this:
public void foo() {
String [] args = new String[2];
args[0] = "hello";
args[1] = "every";
System.out.println("Output: " + args[0] + args[1]);
// etc... the usage of 'args' here and in the main method is identical
}
Explanation in simple layman's language.
The main method expects us to provide some arguments when we direct our JVM to the class name. That means, suppose your file name is Try.java, now to execute this in command prompt you write "javac Try.java" to compile followed by "java Try" to execute. Now suppose instead of writing simply "java Try" you write "java Try 1". Here you have passed an argument "1". This will be taken by your main method even if you don't use it in your code.
If you want to check whether your main method has actually taken the argument "1" or not. Simply, inside your main method type the following:
for(int i = 0; i < args.length; i++) {
System.out.println("Argument is: "+args[i]);
}
When you finish your code, you will turn it into a file with the extension .java, which can be run by double clicking it, but also throughout a console (terminal on a mac, cmd.exe on windows) which lets the user do many things. One thing is they can see console messages (System.out.print or System.out.println) which they can't see if they double click. Another thing they can do is specify parameters, so normally you would use the line
java -jar MyCode.jar
after navigating to the folder of the program with
cd C:My/Code/Location
on windows or
cd My/Code/Location
on Mac (notice that mac is less clunky) to run code, but to specify parameters you would use
java -jar MyCode.jar parameter1 parameter2
These parameters stored in the args array, which you can use in your program is you want to allow the user to control special parameters such as what file to use or how much memory the program can have. If you want to know how to use an array, you could probably find a topic on this site or just google it. Note that any number of parameters can be used.
I think it's pretty well covered by the answers above that String args[] is simply an array of string arguments you can pass to your application when you run it. For completion, I might add that it's also valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:
public static void main (String... args)
In other words, the main method must accept either a String array (String args[]) or varargs (String... args) as a method argument. And there is no magic with the name args either. You might as well write arguments or even freddiefujiwara as shown in below e.gs.:
public static void main (String[] arguments)
public static void main (String[] freddiefujiwara)
When a java class is executed from the console, the main method is what is called. In order for this to happen, the definition of this main method must be
public static void main(String [])
The fact that this string array is called args is a standard convention, but not strictly required. You would populate this array at the command line when you invoke your program
java MyClass a b c
These are commonly used to define options of your program, for example files to write to or read from.
in
public static void main(String args[])
args is an array of console line argument whose data type is String.
in this array, you can store various string arguments by invoking them at the command line as shown below:
java myProgram Shaan Royal
then Shaan and Royal will be stored in the array as
arg[0]="Shaan";
arg[1]="Royal";
you can do this manually also inside the program, when you don't call them at the command line.
String[] args means an array of sequence of characters (Strings) that are passed to the "main" function. This happens when a program is executed.
Example when you execute a Java program via the command line:
java MyProgram This is just a test
Therefore, the array will store: ["This", "is", "just", "a", "test"]
In addition to all the previous comments.
public static void main(String[] args)
can be written as
public static void main(String...arg)
or
public static void main(String...strings)
The String[] args parameter is an array of Strings passed as parameters when you are running your application through command line in the OS.
So, imagine you have compiled and packaged a myApp.jar Java application. You can run your app by double clicking it in the OS, of course, but you could also run it using command line way, like (in Linux, for example):
user#computer:~$ java -jar myApp.jar
When you call your application passing some parameters, like:
user#computer:~$ java -jar myApp.jar update notify
The java -jar command will pass your Strings update and notify to your public static void main() method.
You can then do something like:
System.out.println(args[0]); //Which will print 'update'
System.out.println(args[1]); //Which will print 'notify'
The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
You can also have the syntax below as well.
public static void main(String... args)
here ellipsis i.e. three dots after the data type String specifies zero or multiple arguments (variable number of arguments).
try this:
System.getProperties().getProperty("sun.java.command",
System.getProperties().getProperty("sun.rt.javaCommand"));

Command line arguments show 0?

package commandLine;
public class commandLine {
public static void main(String[] args) {
System.out.println("There are " +args.length+ " Command-line Arguments");
System.out.println("They are: ");
for(int i=0;i<args.length;i++){
System.out.println("arg["+i+"]: "+args[i]);
}
}
}
I wanted to check the length of my command-line arguments and loop through them to display the array of command lines. However, it says my command line arguments are 0? How can this be?
Official Java tutorial about command-line arguments.
Command-Line Arguments
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".
Echoing Command-Line Arguments
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
Note that the application
displays each word — Drink, Hot, and Java — on a line by itself. This
is because the space character separates command-line arguments. To
have Drink, Hot, and Java interpreted as a single argument, the user
would join them by enclosing them within quotation marks.
java Echo "Drink Hot Java" Drink Hot Java
If you are using IDE (Eclipse or etc.) you have to specify command-line arguments via some kind of run configuration. For example for Eclipse:
In have the command line is essentially of the form
java [vm options] class/jar [arguments]
Only these final arguments are given to you in the array. This is unlike a standard C program where you receive the command name also.

How can I handle spaces in arguments?

My app launches and loads the file if I do: myApp /file:c:\nospaces.asd from cmd but if I do myApp /file:c:\with spaces.asd it won't work because the program receives two arguments: myApp /file:c:\with and spaces.asd.
I know that I can do myApp "/file:c:\with spaces.asd" and it'll work like that from cmd. However this isn't a good solution because if I double click the .asd file (custom extension) (and select launch with my app) then main won't be getting the arguments as one line but as two arguments.
How can I go about fixing this issue so that my main will receive only one argument when double clicking the file?
You could join the arguments together if the file is not found. Something like this:
public static void main(String[] args) {
String fileName = joinArgumentsToValidFileName(args);
}
public static String joinArgumentsToValidFileName(String[] args) {
if(args.length == 0) {
return "";
}
String fileName = args[0];
int index = 1;
while(!new File(fileName).exists() && index < args.length) {
fileName += " " + args[index];
index++;
}
return fileName;
}
This assumes that the first argument (or the arguments) must be the file name. Any additional agruments could be evaluated by remembering the offset index somehow (not included in the code above).
But note: This is a not standard behavior of passing arguments to an application and could lead to cunfusion. So if you find a way to pass a "" wrapped file name argument, don't do this!
Double clicking to launch java would be affected by whats registered in windows related to the same i.e windows registry for jar-file launch command.
These are some similar questions asked on SO you can take a look at:
Running JAR file on Windows
java can run jar from cmd but not by double clicking
They mention the useful part which is ensuring you have the wildcard behind the executable in the registry c:\...\javaw.exe" -jar "%1" %

How can I pass variables from the command prompt into my java program

Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!
While executing java program pass the parameters and all the parameters should be separated by space.
java programName parameter1 parameter2 parameter3 parameter4
This parameters would be available in your main method argument
public static void main(String[] args){
//This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
for(int i=0; i<args.length; i++){
System.out.println("Argument " + i + " is " + args[i]);
}
Follow the link:
Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
shared by #BackSlash.
It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:
Displaying Command-Line Arguments passed by user from command-line to a Java program
The following example displays each of its command-line arguments on a
line by itself:
public class DisplayCommandLineParameters {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd
command below.
C:\Users\username>cd c:\test
C:\test>
Assuming the file, say DisplayCommandLineParameters.java, is in the
current working directory, type the javac command below to compile it.
C:\test>javac DisplayCommandLineParameters.java
C:\test>
If everything went well, you should see no error messages.
To run the program: The following example shows how a user might run the class.
C:\test>java DisplayCommandLineParameters Hello Java World
Output:
Hello
Java
World
Note that the application displays each word — Hello, Java and World —
on a line by itself. This is because the space character separates
command-line arguments.
To have Hello, Java and World interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
C:\test>java DisplayCommandLineParameters "Hello Java World"
Output: Hello Java World

Packaging a jar with preconfigured command line arguments

I am wondering if there's a way to create a jar that includes some command line arguments in it, the arguments that are usually passed in the command line when one tries to start up the jar (these parameters are then passed on to the main function). Basically instead of starting my app with
java -jar myapp.jar "arg1" "arg2", I want to start my app with
java -jar myapp.jar
and have "arg1" and "arg2" passed to the main function.
The reason behind this is that I want to deploy this to different environments, and I want my jar to contain different parameters according to the environment it's being deployed at.
Maybe there's another way to achieve similar results ??
Cheers.
PS: Looking for a maven solution.
Edit: I'll add a complete example to make this a bit more clear:
Let's say I have 2 environments: "Production" and "Test". I want to run the jar in the same way no matter in what environment I deploy it. So I always want to run it with:
java -jar myapp.jar
But! In order for my 2 environments to run ok, I need the Production environment jar to start it's main method with an argument "prod" and I need the Test environment jar to start it's main method with an argument "test".
If I correctly understood your problem, in your main() you could define a simple logic to handle the case where you do not specify any input parameter; the logic could retrieve the desired values according to the correct platform/env.
As an example:
public class Test01
{
public static void main(String... aaa)
{
// Check input
if(aaa.length == 0) {
/* Insert logic to retrieve the value you want, depending on the platform/environment.
* A trivial example could be: */
aaa = new String[2];
aaa[0] = "First value";
aaa[1] = "Second value";
}
// Processing, e.g. print the 2 input values
System.out.println(aaa[0] + ", " + aaa[1]);
}
}
Fyi, I created a runnable jar using eclipse, and start the application by either
java -jar Test01.jar
or
java -jar Test01.jar arg1 arg2
Hope this helps!
One solution is to change main(String[] args) to get values from env var if they are not present in the passed arguments.
String user;
String password;
if(args.length < 2)
{
user = System.getenv("appUser");
password = System.getenv("appPassword");
} else {
user = args[0];
password = args[1];
}
You can also create another class with a main function that will call the real one.
public class CallerMyApp{
public void main(String[] args) {
String[] realArgs = {System.getenv("appUser"), System.getenv("appPassword")};
MyApp.main(realArgs);
}
}
Then to execute its something like
java -cp myapp.jar CallerMyApp

Categories

Resources