Reading in from System.in - Java [duplicate] - java

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

Related

BufferedWriter doesnt write [duplicate]

I have to take name and address of user from user and put it into textfile. I write following code:
package selfTest.nameAndAddress;
import com.intellij.codeInsight.template.postfix.templates.SoutPostfixTemplate;
import java.io.*;
import java.util.Arrays;
/**
* Created by
*/
public class Test {
public static void main(String[] args) throws IOException {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
//creating addressbook text file
File fl=new File("E:/addressbook.txt");
fl.createNewFile();
FileReader fr=new FileReader(fl);
BufferedReader in=new BufferedReader(fr);
boolean eof=false;
int inChar=0;
String[] name=new String[2];
String[] address=new String[2];
int counter=0;
do{
FileWriter fw=new FileWriter(fl);
BufferedWriter out=new BufferedWriter(fw);
System.out.println("Enter "+(counter+1)+" students name "+" and address");
name[counter]=br.readLine();
address[counter]=br.readLine();
out.write(name[counter]);
System.out.println("Nmae: "+name[counter]+" ddress: "+address[counter]);
counter++;
}while(counter<2);
}
}
When I run the code, it takes input from user but the text file is empty. The address and name is not written into text file. How can I store the name and address into text file in the above code.
You create the BufferedWriter, but never flush or close it.
These operations are what actually write to the file
As #ManoDestra pointed out in the comments, Java supports the try-with-resources statement, which allows you to format your statements like:
try(BufferedWriter out = new BufferedWriter(new FileWriter(fl))) {
Since BufferedWriter implements the AutoCloseable interface, Java will automatically take care of cleanup of out when the try block exits
A simpler alternative to BufferedWriter is PrintStream:
PrintStream printer = new PrintStream(new File("filepath"));
System.setOut(printer);
And then you can print whatever you want to the file, e.g.
printer.println(name[counter]);
And then close it at the end:
printer.close();

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?
Here is how I have initialized the scanner in my main class:
public class Nimsys {
public static Scanner keyboardIn;
static {
keyboardIn = new Scanner(System.in);
} ...
In the main class Nimsys here is how I get input:
String inputString1 = keyboardIn.nextLine();
In another class here is how I use the scanner from Nimsys:
int inputInt1 = Nimsys.keyboardIn.nextInt();
But now in my main class Nimsys I am trying to scan in a whole file - so far I have used another scanner, as you can see in the code below. However, is it possible to have it all done by the original scanner?
try
{
inputStream = new Scanner(new FileInputStream("file.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File morestuff.txt was not found");
}
String[] reopenPlayers = new String[100];
int i = 0;
while(inputStream.hasNextLine()){
reopenPlayers[i]=inputStream.nextLine();
System.out.println(reopenPlayers[i]);
}
Thanks a lot!
Tom
If I understand your question (not that I think a global variable is a great solution), you could change (and perhaps rename)
keyboardIn = new Scanner(System.in);
to something like
try {
keyboardIn = new Scanner(new FileInputStream("file.txt"));
} catch (FileNotFoundException e) {
System.out.println("file \"file.txt\" not found");
e.printStackTrace();
}
and then remove the try-catch from
inputStream = new Scanner(new FileInputStream("file.txt"));
and modify it to something like
inputStream = Nimsys.keyboardIn;
(or replace inputStream with Nimsys.keyboardIn and not to be prescriptive but perhaps rename Nimsys.keyboardIn to Nimsys.in). Hopefully you're using an IDE that supports refactoring.
No you cannot do that, Scanner is just a wrapper class, which means the actual stream sources you are using are FileInputStream and system.in, obviously you cannot do this, and there is not much benefit if you can do this.
I would recommend against you trying to use the same scanner for multiple sources. From what I can tell from the code you've described, you wouldn't gain anything by it. In general, one Scanner should represent a single source of data.
However, if you're dead-set on the idea, you can write your own implementation of InputStream which combines the input from System.in and your FileInputStream. For ideas on how to do this, see this related question. Then construct the scanner with an instance of your two-source InputStream.
This brings up a host of other questions though- how exactly do you intend to properly combine the input from the two sources? The file contents will be available as soon as the file has been opened. The input from System.in will be available as the user types it. How should your combined Scanner choose what to output and when? These are questions you would have to answer if you choose to write your own InputStream to wrap the two sources.

System.out in DataOutputStream is not printing on the console

I am trying the following code using the DataOutputStream. The OutputStream passed to the DataOutputStream is not printing anything. Please see my below code and pllease tell me anything wrong in this code.
public class DataStreamsExample {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the First Number");
int i = dis.readInt();
System.out.println("Enter the Second Numebr");
int j= dis.readInt();
int total = i+j;
DataOutputStream dos = new DataOutputStream(System.out);
dos.writeInt(total);
}
}
Why are you using data output streams? Can't you use a Scanner for reading input?
Calling dos.flush() will print out your result though.
OutputStream is fundamentally a binary construct. If you want to write text data (e.g. from the console) you should use a Writer of some description. To convert an OutputStream into a Writer, use OutputStreamWriter. Then create a PrintWriter around the Writer, and you can read a line using PrintWriter.println().
You can replace follow line
DataOutputStream out = new DataOutputStream(out);
into this
PrintWriter out = new PrintWriter(new OutputStreamWriter(out));
The character encoding can then be explicitly specified in the constructor of OutputStreamWriter.

How do you read a text file and print it to the console window? Java

I would like to read an entire text file and store its entire contents into a single string. Then I would like to print the string to the console window. I tried this:
import java.util.Scanner;
import java.io.*;
public class WritingTextFiles{
public static void main (String [] args) throws IOException{
FileWriter fw= new FileWriter("testing.txt");
Scanner in= new Scanner (System.in);
String testwords=in.nextLine();
fw.write(testwords);
BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );
System.out.print(r);
fw.close();
}
}
The only thing that is printed to the console window is java.io.BufferedReader#18fb397.
Can anyone explain this to a newbie like me? I have very little experience but I am certainly willing to learn. I am open to any and all suggestions. Thanks in advance!
The reason that java.io.BufferedReader#18fb397 is printed to the console is because you give the reference of the buffered reader as an argument to print, and not the string you want to print.
BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );
System.out.print(r);
should be:
BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );
String s = "", line = null;
while ((line = r.readLine()) != null) {
s += line;
}
System.out.print(s);
Notice we actually read the lines of the file and store it in a temporary variable, then we append this variable to s. Then we print s, and not the BufferedReader.
On a final note, it is wise to close a file when your done, you do call fw.close(), but you should have called it directly after writing the testwords. This is to make sure that the FileWriter has actually written the string.
If it's a relatively small file, a one-line Java 7+ way to do this is:
System.out.println(new String(Files.readAllBytes(Paths.get("testing.txt"))));
If you just want to read it into a String, that's also simple:
String s = new String(Files.readAllBytes(Paths.get("testing.txt")));
See https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html for more details.
Cheers!

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