Unable to find file during runtime execution at command prompt - java

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.

Related

How to execute a console command in a Java application?

I am developing a Java application which will execute a console command. What the command actually does is, it will make changes to a file, then will save a copy of it with a different name to a different folder (both of the file and the output folder is specified by the user). And it requires some binary program to do this, which is a local resource of my application.
So my code is something like:
...
public void actionPerformed(ActionEvent e) {
File selectedFile = jFileChooser1.getSelectedFile();
File pathAssigned = jFileChooser2.getSelectedFile();
String file = selectedFile.getAbsolutePath();
String output = pathAssigned.getAbsolutePath();
String name = selectedFile.getName();
// What's next???
}
And the usage/syntax of the command is something like:
"command -options /package/binary.bin "+file+" "+output+"\\"+name+"-changed"
So my question would now be; What will be my next code? Should I use a Runtime? If so, then how?
And about including a local resource path to a command, does my syntax is correct?
I am still a newbie here as well as in Java programming so please be kind to your answers/comments. Thanks!
PS. The command is a platform independent by the way.
I hope the code below can help you. First you have a shell script that takes parameters.
#!/bin/bash
echo "hola"
echo "First arg: $1"
echo "Second arg: $2"
You save it in e.g. /home/dac/proj/javatest2016/src/main/java/myshellScript.sh and then you can pass the parameters from your Java code.
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
try {
ProcessBuilder pb = new ProcessBuilder("/home/dac/proj/javatest2016/src/main/java/myshellScript.sh", "myArg1", "myArg2");
pb.directory(new File("/home/dac/proj/javatest2016/src/main/java"));
Process p = pb.start();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Test
### hola
First arg: myArg1
Second arg: myArg2

how to pass a variable through a constructor in java

I want to pass a variable to String filename variable below as a parameter. Can anyone help?? I checked the internet but could not find a good tutorial or example.
Thank you in advance...
import java.io.IOException;
public class JavaReadTextFile
{
public static String main(String[] args)
{
// This instantiates from another class
ReadFile rf = new ReadFile();
// The text file location of your choice.
// Here I want to pass a variable as a parameter to the variable filename
String filename = "";
try
{
String[] lines = rf.readLines(filename);
for (String line : lines)
{
//System.out.println(line);
return line;
}
}
catch(IOException e)
{
// Print out the exception that occurred
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
I'm assuming you mean "as an argument to my program", so that you can run:
java -jar myProgram.java theStringIWantToPass
If so, that's what main(String[] args) is for. All arguments will be put in there.. So, try using the following:
if (args.length > 0){
filename = args[0];
}
You didn't post a constructor, but you can get the (command line) parameter of your main function:
public static String main(String[] args) {
if (args!=null && args.length > 0) {
String filename = args[0];
}
}
Change your code to
String filename = args[0];
Now you can pass the file name as a program argument.
If you are open to use swing , then you can explore JOptionPane mesageBox , which can take input.
Otherwise the conventional way of reading the arguments while running the program from args array.

passing input file in java through command line

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".

Java Reading String to Float as Input from File through Command Line

I have to read Strings from a file which the first String is N then convert it as a Integer for a cycle for to go from 0 to N, reading each time another String from file and then convert each line read as a floatas following:
FILE Name: test.txt with the following content:
4
1.21
1.31
1.21
1.32
Java Code
public class lpa2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated constructor stub
String line;int n;
while((line = nextLine())!=null){
n = Integer.parseInt(line);
float v[] = new float[n];
for(int i = 0;i<n;i++){
String temp = readln();
v[i] = Float.parseFloat(temp);
}
for(float f:v)
System.out.println(f);
}
}
public static String readln() throws IOException{
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
return bi.readLine();
}
}
When i use command line like this:
javac -nowarn lpa2.java
then
java lpa2 < test.txt
to use file as input i get the following error
java.lang.NumberFormatException: For input string: "{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf370"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at lpa2.main(lpa2.java:15)
While if i try to do it using eclipse it works perfectly ....
How can i fix this? i used readln() that i created instead Scanner because i needed a faster input reader and even if i try using Scanner i get the same error ... Is there any way to fix this?
Thanks ...
Your file "test.txt" is saved as a rtf file -- I am guessing you saved it from Word or similar word processors? If you open the file in a text editor (e.g., notepad) you'll find that it doesn't contain what you expect.

Read filename from command line argument

I have in my code a hardcoded name for a text file I am reading.
String fileName = "test.txt";
However I now have to use a command argument like so:
text.java arg1 arg2 arg3 (can be any amount) < test.txt
Can anyone help me please?
I have it getting the arguments no problem just not sure on the file. Thank you
I have tried:
String x = null;
try {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
while( (x = f.readLine()) != null )
{
System.out.println(x);
}
}
catch (IOException e) {e.printStackTrace();}
System.out.println(x);
}
However my application now hangs on readLine, any ideas for me to try please?
That is because the file is not passed as an argument, but piped as standard input.
If that is the intended use (to pipe the content of the file), then you just have to read it from System.in (in means standard input):
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String firstLine = in.readLine();
// etc.
}
If you just wanted to pass the file name, then you have to remove or escape that <, because it means "pipe" in shell.
Pass the file as filename to your program and then open this file and read from it.

Categories

Resources