Skip to content

Instantly share code, notes, and snippets.

@kosta
Created March 26, 2014 06:47
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kosta/9777932 to your computer and use it in GitHub Desktop.
Save kosta/9777932 to your computer and use it in GitHub Desktop.
Copy stdin to stdout in Java
import java.io.IOException;
/**
* Class that copies stdin to stdout, as compained about as not being cleanly
* writable in Java on Hacker News.
* In real code, you would just write IOUtils.copy(System.in, System.out),
* which does basically the same thing.
* This does not catch any exceptions as a) this is just an "exercise" and
* b) all we could do with them is pretty-print them. So let the runtime
* print them for you.
*
* Usage: javac inout.java && echo -e "foo\nbar" | java InOut
*/
class InOut {
public static void main(String[] args) throws IOException {
byte[] buffer = new byte[8192];
while(true) {
int bytesRead = System.in.read(buffer);
if (bytesRead == -1) {
return;
}
System.out.write(buffer, 0, bytesRead);
}
}
}
@co-dh
Copy link

co-dh commented Mar 26, 2014

in bash:
echo

@joewalnes
Copy link

In French:

Copiez entrée à la sortie

@tcard
Copy link

tcard commented Mar 26, 2014

In Go:

io.Copy(os.Stdout, os.Stdin)

Libraryless:

b := make([]byte, 1024)
for n, err := os.Stdin.Read(b); err == nil; n, err = os.Stdin.Read(b) {
    os.Stdout.Write(b[:n])
}

@nurettin
Copy link

In Turkish:

Girdiyi çıktıya aktar.

@BepBop
Copy link

BepBop commented Feb 21, 2022

uhh I dont understand why this isnt a valid solution 

import java.util.Scanner; 

public class Main
{

  public static void main (String[]args) 
  {
    while(true)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println(sc.nextLine());
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment