0

I want to redirect stdin like this

java foo < test.txt

and read test.txt byte by byte in a function. I just want to do this:

FileInputStream f = new FileInputStream(System.in)

This should be incredibly simple but I've been pounding my head because I cannot figure out a way to grab test.txt without using args[x].

Edit: The issue is that I'm doing this:

FileInputStream readByte = new FileInputStream(file);
char c = (char)readByte.read();

It does not give the same thing as

char c = System.in.read(); 
Aire
  • 127
  • 2
  • 11
  • 3
    Well, it's not a `FileInputStream` if it's coming from `System.in`, because `System.in` isn't a `File`. – Andy Turner Jun 29 '17 at 19:13
  • 2
    System.in is already an InputStream. You can read bytes from it directly. – JB Nizet Jun 29 '17 at 19:13
  • Possible duplicate of [Reading in from System.in - Java](https://stackoverflow.com/questions/5488072/reading-in-from-system-in-java) – Michael Jun 29 '17 at 19:15
  • I know but for some reason System.in.read() does not give me the same bytes as FileInputStream.readByte() – Aire Jun 29 '17 at 19:16
  • Did you read the documentation? One reads a byte, the other reads a char. – shmosel Jun 29 '17 at 19:17
  • Sorry I was casting the byte as a char... – Aire Jun 29 '17 at 19:18
  • @shmosel Where does it say anything about chars? In the docs `System.in` is declared as just an `InputStream`, and `InputStream.read()` is documented as reading a byte, just like `FileInputStream.read()`... – Siguza Jun 29 '17 at 19:30
  • @Siguza My bad, I was looking at `InputStreamReader`. – shmosel Jun 29 '17 at 19:31

1 Answers1

0

Not sure if this is exactly what you were looking for but check out this question:

Reading in from System.in - Java

They use the following method:

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());
}
Michael
  • 3,093
  • 7
  • 39
  • 83
  • No, sorry if I was not specific enough, but the issue is that I'm doing this: FileInputStream readByte = new FileInputStream(file); char c = readByte.read(); It does not give the same thing as char c = System.in.read(); – Aire Jun 29 '17 at 19:18
  • duplicate and repost of https://stackoverflow.com/questions/5488072/reading-in-from-system-in-java – Akash Jun 29 '17 at 19:28
  • @Akash I know, I already flagged the question. I also fully references their answer in mine. I only posted for OP's sake – Michael Jun 29 '17 at 19:49