I was asked to run a program using command line arguments. The command line argument could either be a file or stdin.
eg:
Your program must accept input from two sources: a filename passed in
command line arguments and STDIN. For example './program input.txt' and './program < input.txt' should work.
Let me be frank, I am not sure whether I am being asked to pass the location of the file or feed the input to the program using STDIN. I am assuming, for now, it's asking me to input the location of the file. How can I do it using arg[0]? Can I use System.in, will that violate the requirement that is being asked from me?
Instead of running the application directly you can pass the arguments from run configuration. For example, in eclipse you can do the following:
right click on the project > run as > run configuration
In the new windows: java application > "your app"
you can find a tab "arguments"
here you can set the arguments for the app in the "program arguments".
I am not sure whether I am being asked to pass the location of the file or feed the input to the program using STDIN
Both. As stated, "your program must accept input from two sources". So, your program must support both, either taking a file argument or reading from standard in.
For the first variant, the file argument, the file's name will be available in arg[0].
So, if the arg-array contains at least one entry, go with the file argument.
If there is no file argument (arg.length == 0), then read from STDIN.
In code, it could look a bit like this:
public static void main(String[] arg) {
if (arg.length == 0) {
// work with System.in
} else {
File file = new File(arg[0]);
// work with file
}
}
Related
I'm working on a program that is supposed to take two files as command line arguments, open the files, and read data from the files to make a data structure.
So far, I have been able to make the structure using File() to open the files and Scanner to read the data. The problem is that I have been providing a specific path to the call for File like this
File f1 = new File("F:/MinSpan/resources/cities.txt");
Scanner sc1 = new Scanner(f1);
I don't think this is going to work for the person who tries to run this program, because I have provided the path for where my specific txt files are located - they're on my flash drive (F) and in some folders. Is there a way I can program this to pass some kind of args[] value in for File() based on the cmd arguement the user has provided?
I have already tried just doing new File(args[2]) , and it can't find the file because there is no path.
The reason for that is because, if you are passing in only two paths, args[2] wont return anything, because args[] starts at 0. So you'd want to use:
new File(args[0]);
new File(args[1]);
Does that make sense?
If you're going for something like java -jar program.jar FILE, then have the program check for the String in args[] at index 0.
Then, construct your file. Check if the file exists (in java.io, it's File.exists()) and return an error message to the user if it's wrong.
I am running OSX 10.11 with IntelliJ 14.1.15.
I have a programme which takes a txt file as an argument. I can run it from the terminal through java SearchCmd test.txt and then it allows me to enter a search term and searches that list.
How do I do this from within IntelliJ, so that I can click the run button and it reads the file and I am able to enter a search term in the IntelliJ console.
The main class 'SearchCmd' contains the main method, as such:
public class SearchCmd {
public static void main (String[] args) throws IOException {
String name;
// Check that a filename has been given as argument
if (args.length != 1) {
System.out.println ("Usage: java SearchCmd <datafile>");
System.exit (1);
}
// Read the file and create the linked list
HTMLlist l = Searcher.readHtmlList (args[0]);
}
However, when I try and run this it says: "Usage: java SearchCmd ".
In order to pass the test.txt file to IntelliJ, I entered the file path in the 'Run/Debug Configurations'.
Sadly I can't attach the picture. :-(
Any help on fixing this and helping me run it from IntelliJ will be greatly appreciated.
Go to Run -> Edit Configurations, Select Application, then give the main class name and program arguments. Then Run.
I just figured it out.
So instead of pasting in an absolute path, you need to paste a relative path from the root directory of your IntelliJ project. And most importantly you have to ommit the initial forward slash.
So my absolute path to the file might be this:
Computer/project/TestInput/itcwww-small.txt
But the path that I need to put into Programme Arguments is:
TestInput/itcwww-small.txt
I hope that this will help someone else.
I had the same issue and was very confused with the previous answers of this question, so here is my explanation to anyone that is lost like I was.
With the project open.
Run > Edit Configurations....
Add the whole directory that the file is in it on the Program
Arguments field with the file format at the end.
Steps to follow-
1. Run->Edit Configurations.
2. Select Application.
3. Provide main class name and command line arguments and apply.
4. Run
Adding the input file name's relative path in the "Program Arguments" will allow the "main" method reading the argument in as a "String"
However, in order to actually let the System to understand using data from the file as standard input, it seems we have to specifically read the file and set the input stream as the system input :
try {
FileInputStream inputStream = new FileInputStream(new File(args[0]));
System.setIn(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You need to go in the menu Run -> Edit configurations.
Select your configuration and add the parameters in the field Program arguments
The field Program arguments is what appears after the class name from command line. For example:
java MyMainClass ProgramArgument1 ProgramArgument2 ProgramArgument3
in your example
java SearchCmd test.txt
the program argument is test.txt
Note: Use an absolute path or check that the working directory is the directory containing your file
java someJavaProgram fsa.fsa <test.txt
That, apparently, is a legitimate command to take with two files as arguments for a Java program in the terminal - one to read in, and then the other (and I think the idea is that it prints the output to the terminal directly). someJavaProgram, fsa.fsa and test.txt are all files in the same directory (being someProject/src, and someJavaProgram in the default package).
However, the response I am given in the terminal just says:
FSA file not found - please scan in the appropriate file.
Testing file not found, please scan in the new relevant file.
My question is two-fold:
What is this command and what is it for?
Does it need refining or modifying or is it the program that needs improvement?
I should note that I wrote the code in Eclipse, where I simply hardcoded filepaths into the program. I'm not sure if that affects anything but it's related.
EDIT: The filepaths and related code are as follows:
private static final String FILE_PATH = "src/test.txt";
private static final String FSA_PATH = "src/fsa1.fsa";
...
public static void main(String[] args) throws FileNotFoundException {
interpretAutomaton();
testAutomaton();
}
...
interpretAutomaton() {
...
Scanner fsaScanner = new Scanner(new BufferedReader(new FileReader(FSA_PATH)));
...
testAutomaton() {
...
Scanner fileScanner = new Scanner(new BufferedReader(new FileReader(FILE_PATH)));
*Both are surrounded by try/catch blocks - which clearly work!
Thanks to anyone who can help clarify on the matter!
Based on the comments so far, to answer your actual questions:
1) The command has four elements:
java - execute the java program
someJavaProgram - the name of the Java class to execute
fsa.fsa - the first argument to the java program, accessible via argv[]
<test.txt - standard input redirection, the contents of the file will be available on the program's standard input, ie. System.in
The net effect is to run your Java program with one argument and one file's contents on the standard input.
2) Both the command line and the program look like they need to change:
change the command line to:
java someJavaProgram fsa.fsa test.txt
That is, remove the <. You will also need to check the paths to the files are correct. This command line assume you are in the same directory as the files when you execute it.
Change your code to use the filenames on the command line rather than the hard-coded names.
I have been reading this book Algorithms 4th Edition. Its code examples take an input from the command line
String[] a = StdIn.readAllStrings();
and sorts them. The source code for StdIn.java is given in http://introcs.cs.princeton.edu/java/stdlib/StdIn.java . Source for heap sort is in http://algs4.cs.princeton.edu/24pq/Heap.java but really isn't relevent.
The main function looks like this:
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Heap.sort(a);
show(a);
}
There is no explicit reference to the args. Yet when i pass in a text file as an argument in the command line it works as advertised:
% more tiny.txt
S O R T E X A M P L E
% java Heap < tiny.txt
A E E L M O P R S T X
Can someone enlighten me how the program reads in the input when no reference has been given. Many thanks in advanced!
Edit: changed the link for stdin java. My bad.
You've got this rather wrong:
"The source code for StdIn.java is given in http://introcs.cs.princeton.edu/java/stdlib/In.java."
Actually the source code for StdIn.java is http://introcs.cs.princeton.edu/java/stdlib/StdIn.java. You were looking at the wrong class!
"Yet when i pass in a text file as an argument in the command line it works as advertised".
Actually, you are NOT passing a text file as an argument. Really!
When you do this:
% java Heap < tiny.txt
the shell is opening the file, and passing the open file descriptor to Java. Java wraps this file descriptor as an java.io.InputStream object, and makes it available for the application via the the java.lang.System.in variable. That is what StdIn.readAllStrings() is actually reading from.
In fact, your Heap program has no command line arguments. If you print args.length in the main method, you will see that it is zero.
When in command line, passing a file as < whatever to the application means that the contents of the whatever file will be the input for the application. This means that the contents of tiny.txt (in your specific case) will become the t̶e̶d̶i̶o̶u̶s̶ user input of the application.
Looking at the default constructor for the In class you provided, I assume StdIn is just an instance which is default initialized. By this constructor, it reads from stdin. By redirecting stdin to be from a file (<), you are feeding the contents of the file to this reader which is simply reading the lines.
To be clear, the text file is not given to your program in the args array. That would be java Heap sort.txt. Instead the standard input stream is redirected to be from a file.
I know that you must add command line arguments into the "Run Configurations" in Eclipse to get your command line arguments to be passed every time by default. This worked fine on my PC.
The purpose of this question is to create a simple program that can be submitted to an online programming challenge site (like codeeval). The system provides a file path to the command line args[0] and then you manipulate the file and its data.
On the PC I had my Class folder > Default Package > (file.txt and TestCode.java)
The project was set up with a run configuration with simply file.txt in the program arguments section.
On the MAC this doesn't seem to be working. I get a fileNotFoundExcepion. I'm new to MAC so I'm thinking this might be a problem with file extensions not being what I think they are. I saved a file as "file.txt" but if I save it as "file" MAC doesn't show the file extensions and I'm not sure if MAC supports .txt by default.
If it doesn't support .txt, what file type is a "text document"? I tried saving the text document as "file" leaving off any extension, and then adding file.rtf or file.txt or even file to the Program arguments and none of that works. It all gives me a fileNotFoundException.
EDIT
The intent is to be able to develop solutions to the CodeEval (or similar) website and submit them. I have previously solved many problems on CodeEval and turned them in with the code below from a PC. This, however, doesn't work on MAC. The answer involving the use of the URL does not work when run from the solution checking platform (presumably because the program is not actually saved onto the system).
EDIT 2
My entire program:
public class TestCode {
public static void main (String[] args)throws IOException{
File filename = new File(args[0]);
Scanner file = new Scanner(filename); // returns the fileNotFoundException
while( file.hasNextLine()){
String line = file.nextLine();
System.out.println(line);
}
}
}
Under "Run Configurations" in the Arguments tab > Program Arguments I have tried putting file, file.txt, file.rtf all three with a "text document" in the same directory as the above program. I have tried naming that file file, file.txt and file.rtf And i tried every combination of these names.
Did you try to use the absolute file name as command line parameter? This should be something like /Users/name/path/to/your/file. If the file is part of your project, you can also use a variable such as ${project_loc}/file (try the button Variables… below the Program Arguments field.
Replace your code with this
URL resource = TestCode.class.getResource(args[0]);
Scanner file = new Scanner(new File(resource.getFile()).getAbsoluteFile());