use cat to send input file to java main class - java

If i want to input file say myfile.txt using cat command
say "cat myfile.txt > java myMain"
What should I write in myMain function ? Is myfile.txt stored directly in args[0] or is there a way to reference it ?

You wouldn't do it quite like that - that's currently redirecting to a file. You either want to pipe it to java, or redirect in the other way:
java Foo < myTextFile
or
cat myTextFile | java Foo
Next, you should use System.in, as you're basically using the contents of that file as standard input instead of the console:
import java.io.*;
public class CopyInput {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in, Charset.defaultCharset()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Read: " + line);
}
}
}
}

Related

how to feed multipe files to command line in java without using shell

I am quite new to java, so it might be a stupid question. But I need it to be solved for my data structure class project...
So I am trying to feed my program with 2 different input files. I know we can use Scanner and InputStreamReader to achieve this with 1 file, I don't know how I should do it with 2 files.
In some answers to similar questions with mine, someone mentioned shell which I think can probably solve this problem. However, I don't know anything about shell, so I am wondering if this problem can be solved without writing a shell file, and what the syntax would be for inputting multiple files in command line.
What I execute in command line(with 1 input file):
java UserInterfaceOrNot < input.txt > output.txt
I will post more code if needed.
Code:
public class UserInterfaceOrNot
{
public static EventManager em;
public static Scanner scn = new Scanner(new InputStreamReader(System.in));
public static void main (String [] args)
{
UserInterfaceOrNot ui = new UserInterfaceOrNot();
while (scn.hasNext()){ui.runData();}
scn = new Scanner(new InputStreamReader(System.in));
while (scn.hasNext() && !scn.next().equals("x")){ui.runCommand();}
}
java UserInterfaceOrNot input1.txt input2.txt output.txt
When you call your program as this, you're actually passing 3 arguments to your java public static void main (String [] args) method.
You can find these argument in order in that String array (String [] args).
To read the arguments:
String myFirstFile = args[0]; // this will be "input1.txt"
String mySecondFile = args[1]; // this will be "input2.txt"
String myOutputFile = args[2]; // this will be "output.txt"
You can read each file (input1 and input2) like this by creating another method
public String readFileAsString(String inputFile) throw IOException {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
Then in your main method you can call it like this:
public static void main(String[] args) throws Exception {
UserInterfaceOrNot ui = new UserInterfaceOrNot();
String inputFile1 = args[0];
String inputFile2 = args[1];
String input1AsString = ui.readFileAsString(inputFile1);
String input2AsString = ui.readFileAsString(inputFile2);
//continue with your logic
}

Input file to java through command line

public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("Input.txt"));
}
I have to give input file through command line
java -cp Projectfile.java < Input.txt
what change should I do in my program to fetch this file in BufferedReader?
You pass it as command line argument
java -cp Projectfile.java Input.txt
and access passed argument in args[]
BufferedReader br = new BufferedReader(new FileReader(args[0]));
Try this way. You may optionally include 'else' part. If you dont want else part then move the bufferreader statement in 'then' part. Run it as ->
java -cp . Projectfile Input.txt
Code ->
public static void main(String[] args) throws IOException, {
String file;
if ( args.length > 0 ) {
file = args[0];
}
//Optionally you can define the file name if not supplied in java command.
else {
file = "Input.txt"
}
BufferedReader br = new BufferedReader(new FileReader(file));
}
try the code below:
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
}
During the execution of your program, you pass the file as argument but then you never use it. By using args[0], you will be using the argument that you passed on:
java -cp Projectfile.java < Input.txt
First of all after initialising the BufferedReader class with "br" as its object, you need to write the following line
String str=br.readLine();
System.out.println(str);
Next you have to create a file Input.txt and place it in the same folder as that of your java file.
Next in the command prompt, write
javac Projectfile.java
Press Enter
java -cp . Projectfile < Input.txt
In this way it'll be done. Happy Coding Journey!!!

File not opening in Java

Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?
give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}
You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.
Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!

Handling Java command line arguments in the format “cat file.txt | java YourMainClass”

I've never used java from the terminal before, and I certainly have never coded for it. My question is simple: How do I intake a file when the calling format is
cat  file.txt  |  java  YourMainClass
I have the rest of the code up and running swimmingly, I just need to take the given file name into my main method.
Since the cat command displays the contents of the file, you need to use the System.in buffer to capture the data coming in from that command. You can use a BufferedReader pointing to System.in to loop through the data and process it.
Look at this Example
public class ReadInput {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String x = null;
while( (x = input.readLine()) != null ) {
System.out.println(x);
}
}
}
As you are looking to read from System.in as the output from cat, you could do:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
// use line...
}

How to solve no input in StreamTokenizer

I have the following lines of code :
public static void main(String[] args) {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
StreamTokenizer t = new StreamTokenizer(inputStreamReader);
while (t.nextToken() != StreamTolenizer.TT_EOF) {
// process here
}
}
So, when I run, I call : java example.java < input.txt
However, I can't handle the situation "no input file" when I call : java example.
It seems to run forever.
If you don't redirect anything to stdin (System.in) such as "input.txt" in your example command line then your program will expect you to type data into the console window.
Perhaps you should refactor your program to expect a command line argument (e.g. by checking that "args.length >= 1") and interpret it as the name of the file to read. If no file name is given then you can print an error message. Additionally, you could interpret the special pseudo-filename "-" (a single hypen) to mean stdin so you can still redirect data.
For example:
public static void main(String[] args) {
if (args.length < 1) throw new IllegalArgumentException("no filename given");
InputStream in = ("-".equals(args[0])) ? System.in : new FileInputStream(args[0]);
InputStreamReader inputStreamReader = new InputStreamReader(in);
StreamTokenizer t = new StreamTokenizer(inputStreamReader);
while(t.nextToken() != StreamTolenizer.TT_EOF) {
// ...
However, don't forget to close the FileInputStream, e.g. in a finally block.

Categories