How to solve no input in StreamTokenizer - java

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.

Related

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

How do I only send the output and not the input to InputStreamReader when executing a shell command using ProcessBuilder?

I am executing an executable with a command line argument using ProcessBuilder and I am trying to read the output using a BufferdReader. However, when I print out the input stream of the process, it seems I am first printing out the output, then the input as well.
For example, I am trying to execute "my_command -an-option /path/to/file", and when I print out the buffered reader, I am printing out the output followed by the contents of the my file at /path/to/file. I guess it makes sense that the input stream is reading in my inputp and the output,
public static void d(String file) throws Exception {
ProcessBuilder builder = new ProcessBuilder("my_command", "-an-option", file);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
process.waitFor();
String s = null;
while ((s = in.readLine()) != null) System.out.println(s);
in.close();
}
public static void main(String[] args) {
d("/path/to/file");
}
Does anyone know how to make it only print out the output? I want to save the output to a string or something and parse it, etc.

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...
}

Scanner unable to read text file

I have a bunch of .txt files I am trying to read but for many of them they will not read. The ones that will not read appear to start with a blank line before the text. For example the following throws a NoSuchElementException:
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(new File("documentSets/med_doc_set/bmu409.shtml.txt"));
System.out.println(input.next());
}
where the text file being read begins with a blank line and then some text. I've also tried using input.skip("[\\s]*") to skip any leading whitespace but it throws the same error. Is there some way to fix this?
EDIT:
The file hosted on google docs. If you download to view in a text editor you can see the empty line it starts with.
The Scanner type is weirdly inconsistent when it comes to handling input. It swallows I/O exceptions - consumers should test for these explicitly - so it is lax in informing readers of errors. But the type is strict when decoding character data - incorrectly encoded text or use of the wrong encoding will cause an IOException to be raised, which the type promptly swallows.
This code reads all lines in a text file with error checking:
public static List<String> readAllLines(File file, Charset encoding)
throws IOException {
List<String> lines = new ArrayList<>();
try (Scanner scanner = new Scanner(file, encoding.name())) {
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
if (scanner.ioException() != null) {
throw scanner.ioException();
}
}
return lines;
}
This code reads the lines and converts codepoints the decoder doesn't understand to question marks:
public static List<String> readAllLinesSloppy(File file, Charset encoding)
throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
Scanner scanner = new Scanner(reader)) {
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
if (scanner.ioException() != null) {
throw scanner.ioException();
}
}
return lines;
}
Both these methods require you to provide the encoding explicitly rather than relying on the default encoding which is frequently not Unicode (see also the standard constants.)
Code is Java 7 syntax and is untested.
It starts with a blank line, and you're only printing the first line in your code, change it to:
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(new File("documentSets/med_doc_set/bmu409.shtml.txt"));
while(input.hasNextLine()){
System.out.println(input.nextLine());
}
}
Scanner reads all the words or numbers up to the end of the line. At this point you need to call nextLine(). If you want to avoid getting an Exception you need to call one of the hasNextXxxx() methods to determine if that type can be read.

Reading in from System.in - Java [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am not sure how you are supposed to read in from system input from a Java file.
I want to be able to call java myProg < file
Where file is what I want to be read in as a string and given to myProg in the main method.
Any suggestions?
You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
import java.util.Scanner;
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
Well, you may read System.in itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
In Java, console input is accomplished by reading from System.in. To obtain a character based
stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream. Its most commonly used constructor
is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
This is taken from the book Java- The Complete Reference by Herbert Schildt
Use System.in, it is an InputStream which just serves this purpose
You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.
You can call java myProg arg1 arg2 ... :
public static void main (String args[]) {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
You probably looking for something like this.
FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
class myFileReaderThatStarts with arguments
{
class MissingArgumentException extends Exception{
MissingArgumentException(String s)
{
super(s);
}
}
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value
if(args.length>0)
{
// do something with args[0]
}
else
{
// default in a path
// or
throw new MissingArgumentException("You need to start this program with a path");
}
}

Categories