0

So I have a Java-file e.g. example.java. I've then compiled it using javac (I then made a .class file in my directory, example.class).

I now want to run it using standard input with a .txt file in the ubuntu terminal. I remember it being fairly easily done with Python, but I'm not quite sure what to do with Java.

I want something along the lines of

dir$ java example indata.txt

That would pass my file indata.txt as standard input into my program.

Nyfiken Gul
  • 593
  • 3
  • 16
  • 2
    How did you do it with python? Have you tried doing the same thing here? – JimNicholson Nov 03 '16 at 11:40
  • That's what I don't really remember, hehe. I recall it being sometthing along the lines of what I did in my code block in my question, but that didn't work in Java – Nyfiken Gul Nov 03 '16 at 11:41
  • 1
    You do know that the command java take a first parameter as the class with the main function then argument for the previous one. So `indata.txt` would be a String in arg[1]. – AxelH Nov 03 '16 at 11:47
  • Hmm, okay.. What I want it to do is read my .txt-file row-wise, and outputting something after it's read the whole file. Do you have any idea how I would accomplish that? – Nyfiken Gul Nov 03 '16 at 11:49
  • 1
    By implementing your need in java ? your `example.java` contains a `public static void main(String[] args){...}` function. `args`will contains the same argument that those pass to the java command `args[0] = example` `args[1] = indate.txt`. For more information, you should ask Google. Using a OutputStream is not complicated but this is not the place... – AxelH Nov 03 '16 at 11:51
  • 1
    Here is a bit of a start for you http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java or this http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file – AxelH Nov 03 '16 at 11:53
  • Hmm, okay.. Not really what I'm looking for though, in Python I could read a text file just as if I read the contents of the text file as standard input - I need it to be able to do exactly that since I'm going to pass my program into an online review tool that just takes the .java file and feeds it with standard input and then checks if the outputs are correct. – Nyfiken Gul Nov 03 '16 at 11:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127275/discussion-between-axelh-and-nyfiken-gul). – AxelH Nov 03 '16 at 12:26

1 Answers1

0

I managed to solve my problem - the way I did it was as follows (in the terminal, standing in the same directory as my .java, .class and .txt files;

java example < indata.txt
Nyfiken Gul
  • 593
  • 3
  • 16