passing input file in java through command line - java

FileInputStream fstream = new FileInputStream("textfile.txt");
This is above code to get the input file , i want a input file to give from command line
i.e.
pseudo command line code
java filename giveinputfile("textfile.txt")
What change i modify in my java code and command line(windows) to make this work

You use the String[] args in your main method,
public static void main(String[] args) {
String fileName = "textfile.txt";
if (args.length > 0) {
fileName = args[0];
}
System.out.println("fileName: " + fileName);
}
Then you run your program with
java myProgram MY_FILE
or
java myProgram
With the code above the first command would use "MY_FILE" and the second would use the default "textfile.txt".

Related

Reading data from file given by user [duplicate]

This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 10 months ago.
I have my program saved in JAR format. I need to read data from two different files given by user using this line: java -jar app.jar file1.txt file2.txt. How can I read it? I wrote this:
Scanner scan = new Scanner(System.in);
String inputFileName1 = scan.next().trim();
String inputFileName2 = scan.next().trim();
File input1 = new File(inputFileName1);
Scanner file1 = new Scanner(input1);
File input2 = new File(inputFileName2);
Scanner file2 = new Scanner(input2);
It works when I manually write: file1.txt file2.txt, but not with the command line. What's wrong?
When you use command line to send the arguments, you can use args to access those arguments. For example, if you run java yourfile arg0 arg1 on the command line, then you can access arg0 and arg1 by using args[0] respectively args[1] in your code.
So, if you use
public static void main(String[] args) {
File input1 = new File(args[0]);
Scanner file1 = new Scanner(input1);
File input2 = new File(inputFileName2);
Scanner file2 = new Scanner(args[1]);
...
}
then your code should work fine.
You can get the arguments from the command line through the args from your main method.
Giving the args out would look something like this:
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
You could make something like File input1 = new File(args[0]); to get the first argument.

Unable to find file during runtime execution at command prompt

Good day to all experts here,
I am getting a FileNotFoundException when I run the following command at command prompt:
c:\TA\java -jar LoginCaptchaChrome.jar LoginCaptchaChrome https://2015.qa.int.www.mol.com/ C:\\TA\\TD\\Login\\Login.xlsx C:\\TA\\TR\\LoginCaptchaChrome_22082016_1838.xlsx
The error message is as below:
`Exception in thread "main" java.io.FileNotFoundException: C:\TA\TR\LoginCaptchaChrome_22082016_1838.xlsx" (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at LoginCaptchaChrome.main(LoginCaptchaChrome.java:58)
I am actually passing arguements from the command prompt, and the file
LoginCaptchaChrome_22082016_1838.xlsx` is not being passed to the code line :
FileOutputStream fos = new FileOutputStream("\"" + args[3] + "\"");
in the following code:
public class LoginCaptchaChrome {
public static void main(String[] args) throws IOException, InterruptedException{
String tc = args[0];
String address = args[1];
String test_data = args[2];
String test_result = args[3];`
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lam Chio Meng\\Desktop\\work\\chromedriver_win32\\chromedriver.exe");
FileOutputStream fos = new FileOutputStream("\"" + args[3] + "\"");
XSSFWorkbook workbook = new XSSFWorkbook();
Hope to have advice from experts here. Thank you in advance.
The problem comes from a misconception of how arguments are passed at a command line.
Take a shell for instance. Suppose this command at the prompt:
someCommand "arg with spaces"
What the arguments of the process actually are:
someCommand, and
arg with spaces. Yes, that's a single argument.
This means that the problem for you is this line:
new FileOutputStream("\"" + args[3] + "\"");
You don't need the leading and trailing quotes at all.
Moreover, since this is 2016, don't use FileOutputStream. Use JSR 203:
final Path path = Paths.get(args[3]);
final OutputStream out = Files.newOutputStream(path);
A simple way to see how the Java program actually sees arguments is a program like this:
public final class CmdLineArgs
{
public static void main(final String... args)
{
final int len = args.length;
System.out.println("---- Begin arguments ----");
IntStream.range(0, len)
.map(index -> String.format("Arg %d: %d", index + 1, args[index])
.forEach(System.out::println);
System.out.println("---- End arguments ----");
System.exit(0);
}
}
Try and run this command at the prompt with, say:
java MyClass foo bar
and:
java MyClass "foo bar"
and see the difference.

putty command line arguments acting strangely with java

I need my code to read in a file pathway and analyze the file at the end of it, and according to the assignment it has to exit if no valid pathway is given. when I type in something like "java ClassName pathway/file" though it just goes to accepting more input. If I then put in the exact same pathway it does what I want it to but it need to do it in the former format. should I not be using a Scanner?
(TextFileAnalyzer is another class I wrote that does the file analysis, obviously)
import java.util.Scanner;
public class Assignment8 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String path = null;
TextFileAnalyzer analysis = null;
if (args.length == 0 || java.lang.Character.isWhitespace(args[0].charAt(0)))
System.exit(1);
try {
path = stdin.next();
analysis = new TextFileAnalyzer(path);
} catch (Exception e) {
System.err.println(path + ": No such file or directory");
System.exit(2);
}
System.out.println(analysis);
stdin.close();
System.exit(0);
}
}
Arguments specified on the command line are not the same as information entered via standard input at the console. Reading from System.in will let you read input, and this is not related to command line parameters.
The problem with your current, non-working code is that while you are checking to see if the argument was specified, you aren't actually using args[0] as the pathname, you're just going on to read user input regardless.
Command line parameters are passed in via the String[] parameter to main. In your case it's the first parameter, so it would be in args[0]:
public static void main (String[] args) {
String pathname;
if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Or, more strict:
public static void main (String[] args) {
String pathname;
if (args.length > 1) {
System.err.println("Error: Too many command line parameters.");
System.exit(1);
} else if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Check out the official tutorial on command-line arguments for more information.
By the way, I noticed you have this in your if condition:
java.lang.Character.isWhitespace(args[0].charAt(0))
Leading and trailing whitespace is automatically trimmed off of unquoted command line parameters, so that will always be false unless the user explicitly uses quotes and does something like:
java ClassName " something"
And even in that case, you may want to just accept it and use args[0].trim() to be more lenient.

acccepting file names using command line in java

I'm trying to accept 3 filenames through a command line. This is the code I tried but not working.. ?? Pls help
public class MedicalStudentMatcher {
enum Arguments {
HospitalFile, ResidentFile, OutputFile
};
/**
* #param args
*/
public static void main(String[] args) {
//Retrieve file locations from command line arguments
String hospitalFile = "";
String residentFile = "";
String outFile = "";
if (args.length > 2){
hospitalFile = args[Arguments.HospitalFile.ordinal()];
residentFile = args[Arguments.ResidentFile.ordinal()];
outFile = args[Arguments.OutputFile.ordinal()];
} else {
System.out
.println("Please include names for the preference files and output file when running the application.\n "
+ "Usage: \n\tjava MedicalStudentMatcher hospital.csv student.csv out.txt\n");
return;
}
Do some debugging. Print the length of you command line arguments as well as each argument
something like:
System.out.println(args.length);
for(String arg: args)
{
System.out.println(arg);
}
This way you will see what you are passing to your program as arguments.

User input other than print prompt and scanner

I wrote a program that asks for user input like this:
System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();
...
System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);
I ask several times for input in this way but it can get to be a huge pain if you mistype because then you have to kill the program and rerun. Is there an easy way to just take input all at once when you run a program? As in just declaring it in the command line when having it run?
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
You can use file redirection.
program < file
sends the file to the standard input of the program. In your case,
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere < file
Or you can read from a file in your program. You can make this optional like
InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!
When you run the command as :
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
It runs the public static void main(String[] args) method of your primary class where you can get the userinputhere directly as:
public static void main(String[] args)
String userinputhere = args[0];
..... rest of your code
}
If there are multiple user Inputs, you can get them all as :
public static void main(String[] args)
String userinput1 = args[0];
String userinput2 = args[1];
String userinput3 = args[2];
//and so on..
..... rest of your code
}

Categories

Resources