I want to provide the series of inputs of my program from a text file so that I do not have to give input time and again, how can I do this using "javac"?
I used to do this in C/C++ Programs and it looked like as far as I remember gcc <sample.txt> filname.exe and it was called batch processing as told by my professor.
Is there any way to do the same with javac or by using some tweak in VS Code so that I do not have to give input from keyboard every time I run the program?
Thank You!
If you want to be able to run the same code, unchanged, for either getting user input via standard input or via a file, I suggest defining a "system" property as a flag to determine where user input comes from, depending on whether the property is defined or not.
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class Testings {
public static void main(String[] args) throws IOException {
String redirect = System.getProperty("REDIRECT");
Scanner scanner;
if (redirect != null) {
scanner = new Scanner(Paths.get("", args));
}
else {
scanner = new Scanner(System.in);
}
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
if (redirect != null) {
scanner.close();
}
}
}
If you want input from a file, rather than from standard input, use the following command to run the code.
java -DREDIRECT Testings path/to/file.txt
If you want input from the user, via the keyboard then remove -DREDIRECT
, i.e.
java Testings
Since you are not getting input from the file, no need to provide a path.
Note that if you are using an IDE, then it should provide the ability to define a "system" property as above. Also note that the property name can be anything. I simply (and arbitrarily) chose REDIRECT. Remember though, that it is case sensitive.
Alternatively, you can redirect System.in
.
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Testings {
private static void redirect(String[] args) throws IOException {
Path path = Paths.get("", args);
InputStream is = Files.newInputStream(path);
System.setIn(is);
}
public static void main(String[] args) throws IOException {
String redirect = System.getProperty("REDIRECT");
Scanner scanner;
if (redirect != null) {
redirect(args);
}
scanner = new Scanner(System.in);
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
Regarding the file that you use for input, the path to the file can be either relative or absolute. If it is relative, then it is relative to the current working directory which is the value returned by the following code:
System.getProperty("user.dir");
Alternatively, you could make the file a resource which would mean that the path is relative to the CLASSPATH.