最基礎的 I/O 範例:從標準輸入讀取位元組,直接寫入標準輸出,直到 EOF (Ctrl+C 或 Ctrl+D)。
import java.io.*;
public class EchoStdin {
public static void main(String[] args) {
byte[] buffer = new byte[1024];
try {
while (true) {
int len = System.in.read(buffer); // 阻塞直到有資料
if (len == -1) break; // EOF
System.out.write(buffer, 0, len);
}
} catch (IOException e) {
System.err.println("I/O 錯誤:" + e.getMessage());
System.exit(1);
}
}
}
System.in 是 InputStream (位元組流),System.out 是 PrintStream (繼承 OutputStream)。read(byte[]) 回傳實際讀取位元組數,-1 表示串流結束。write(byte[], offset, len) 寫入指定範圍。
import java.io.*;
public class EchoStdinChar {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"))) {
char[] buf = new char[1024];
int len;
while ((len = br.read(buf)) != -1) {
bw.write(buf, 0, len);
bw.flush(); // 即時顯示
}
}
}
}
使用 InputStreamReader/OutputStreamWriter 指定編碼,避免中文亂碼;try-with-resources 確保關閉。