I am trying to read a String with System.in using an InputStream o DataInputStream, maybe I can use BufferedInputStream, but I don't know how to use it, I was searching for bu I don't understand how does it works, I am trying to dos something like this.
import java.io.*;
public class Exer10 {
public static void main(String[] args) throws IOException {
InputStream is = System.in;
DataInputStream dis = new DataInputStream(is);
try {
while (true){
dis.readChar();
}
} catch (EOFException e){
}
}
}
The problem here is that I am in loop in the System.in because the method "readChar" is in loop, but if I put the "dis.readChar()" in another position, this only returns me one byte, can you hel me please?
The solution I found is that I can put it in a array of bytes, but this don't solve anything, because if i do this, the file have to be always of the same length, and this length can't be moved. Something like this:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Exer10 {
public static void main(String[] args) throws IOException {
InputStream is = System.in;
DataInputStream dis = new DataInputStream(is);
byte[] bytes = new byte[10];
dis.read(bytes);
}
}
readChar will only returns one byte if there is one. The way you could solve it is the following:
Then you can use the extracted data :)
sources:
javadoc: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/DataInputStream.html example: https://www.geeksforgeeks.org/datainputstream-read-method-in-java-with-examples/#:~:text=read(byte%5B%5D%20b)%20method,data%20is%20available%20to%20read.
Easier implementation would indeed be with a Scanner: