Corey
Corey

Reputation: 781

How to take a file as argument?

I realize that was not a very descriptive question, but I wasn't sure how else to state it..

I wrote an interpreter, Tiny_Int.java, for a made up language called "tiny". All I need to know is how to run the interpreter with a specified tiny file like so:

java Tiny_Int <Sample.tiny

It may be helpful to know I am using this to read the tiny file

FileReader fileReader = new FileReader(file); //file being the Sample.tiny
BufferedReader bufferedReader = new BufferedReader(fileReader);

Upvotes: 2

Views: 897

Answers (4)

jatanp
jatanp

Reputation: 4102

You are redirecting the file to the Java command, therefore you should read the content from standard input stream (System.in) using,

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Use br.readLine() to read each line until it returns null.

Upvotes: 3

vbcr
vbcr

Reputation: 101

using command line arguments passed to your main method (String args[]).

more info: http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

args[0] is your variable 'file'.

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 373082

You seem to be mixing up two concepts. If you want to use shell redirection like this:

java Tiny_Int < Sample.tiny

Then the shell will push the contents of your file into System.in, and you don't need to explicitly load the file. You just need to read it from System.in.

If, on the other hand, you want your program to take in an explicit argument saying which file you want to use, like this:

java Tiny_Int Sample.tiny

Then you'd want to look at the String[] argument to main to get the file to open.

Amazing how much difference a < can make!

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 994251

If you're expecting input from stdin, use System.in:

FileReader fileReader = new FileReader(System.in);

Note that if you read from stdin like this, then on Unix you can use a shebang line to make your Sample.tiny script executable:

#!/usr/bin/java Tiny_Int

print "hello"

When you run your script with ./Sample.tiny, then the JVM will be run with the rest of your script on stdin.

Upvotes: 2

Related Questions