Input file to java through command line - java

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!!!

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
}

Java -Jar "my project" not executing in C.P (windows)

I am trying to run a java file in the command prompt. the project was made in NetBeans. so I tried running it with java -jar "D:\Java Projects\Algo1\dist\Algo1.jar" which is what NetBeans told me to run in the command prompt. however, I get the following:
my code is:
`
public static void main(String[] args) {
// TODO code application logic here
Scanner N = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Scanner K = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Scanner L = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println(K);
}
When you call System.out.println(K), java will print the argument (K) to the console. In this case the output tells you that you have an instance of the class java.util.Scanner and its properties.
When you want to read an input from the console, you should use the nextLine() method from the Scanner class, for example
String input = K.nextLine();
You can read more here: https://stackoverflow.com/a/11871792/7677308

use cat to send input file to java main class

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);
}
}
}
}

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