putty command line arguments acting strangely with java - 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.

Related

Input file for JAR

I want to send the input of a jar from one file and save the output in another,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
String line;
while (!(line = sc.nextLine()).isBlank()) {
builder.add(line);
}
builder.stream().sorted().forEach(System.out::println);
sc.close();
}
when I execute the jar I try it like this
java -jar name.jar > output.txt < input.txt
but it generates the exception java.util.NoSuchElementException, I appreciate any help.
This is what I believe is the easiest way to accomplish what you are trying to do:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("output.txt"); // Used to write to output.txt
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
while (sc.hasNextLine()) { // Same thing as what you had, just 1 less line
// Not entirely sure what you're trying to do here;
//if no input is given at the EXACT time the program is run, this will be skipped
builder.add(sc.next());
}
builder.stream().sorted().forEach((s) -> { // Changed this to a lambda
System.out.println(s);
try {
fw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
});
fw.close();
sc.close();
}
The easiest way would be to pass your input.txt file as a parameter to your jar. You can then utilize Files.readAllLines to read your text file and do your sort and then send each line to std out
Then you can redirect std out to your output.txt file.
public static void main(String[] args) throws IOException {
if (args == null || args.length == 0) throw new RuntimeException("No file provided");
Path file = Paths.get(args[0]);
if (Files.notExists(file)) throw new IOException(args[0] + " cannot be found.");
Files.readAllLines(file).stream().sorted().forEach(System.out::println);
}
Then you can invoke it like this:
java -jar name.jar input.txt > output.txt
The code is okay, not perfect, but it works. Of course your class needs to have some more lines (like defining the import and class definition etc.), but you only posted the main method is and that's okay for me.
At runtime, you're piping < input.txt as your standard input which is great.
I think your problem could be:
Your input.txt contains nothing, then you'll get this exception
Or the input.txt is in a different directory at runtime, so you're actually not piping anything as an input. There's no error from the command line, but this way you get the exception too.
One of those could be the cause.

ArrayIndexOutOfBoundsException:0 occurs when trying to read in a file from the Linux command line in Java?

So I'm trying to accept a text file from the Linux command line into my Java program, but the compiler gives me that error mentioned in the title. It says the error occurs at the line that says "String fileName = args[0];". Does anyone happen to know why?
Here is my code:
public class Parsons_Decoder
{
// method: main
// purpose: receives key-phrase and sequence of integers and
// prints the secret message to the screen.
public static void main(String[] args) throws IOException
{
String fileName = args[0];
// reads incoming file (if it exists) and saves the key-phrase to
// String variable "keyPhrase"
File testFile = new File(fileName);
if(!testFile.exists())
{
System.out.println("\nThis file does not exist.\n");
System.exit(0);
}
Scanner inputFile = new Scanner(args[0]);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for(int i = 0; i < numArray.size(); i++)
{
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
//keyboard.close();
inputFile.close();
}
}
Update:
Your professor is asking you to read in a file with stdin, using a command like the following:
java Diaz_Decoder < secretText1.txt
Your main() method should then look something like the following:
public static void main(String[] args) throws IOException {
// create a scanner using stdin
Scanner sc = new Scanner(System.in);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while (inputFile.hasNextInt()) {
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for (int i = 0; i < numArray.size(); i++) {
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
}
Based on your description and the link you provided (which should be in the question, not a comment), your prof wants you to write a program that accepts the contents of a file via "standard in" (STDIN) when run as a POSIX style shell command line using redirection.
If this is indeed a requirement, you can't just read the file given as an argument, but need to change your program such that it reads from STDIN. The key concept here is that the "<" is not available to your program argument list. It will be consumed by the shell (Bash, Ksh, etc.) running the Java process, and a "pipe" setup between the file on the right side and the process on the left side. In this case, the process is your Java process running your program.
Try doing a search for "java STDIN" to get some ideas on how to write a Java program that can read its standard in.
By the way, if your program crashes with an ArrayIndexOutOfBoundError when run with redirection in this manner, it still has a bug in it. You need to test for and handle the case where you have 0 file arguments after the shell has finished processing the command line. If you want full marks, you need to handle the error and edge cases.

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

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.

Categories

Resources