"สวัสดี Amigo! วันนี้เราจะสำรวจบางสิ่งที่น่าสนใจมาก: วิธีแทนที่System.in input stream "

System.in  เป็น ตัวแปร InputStream แบบคงที่ที่เรียบง่าย แต่คุณไม่สามารถกำหนดค่าใหม่ให้กับมันได้ แต่คุณสามารถใช้เมธอด System.setIn()

ขั้นแรก เราต้องสร้างบัฟเฟอร์ จากนั้นจึงใส่ค่าบางอย่างลงไป จากนั้นเราจะรวมไว้ในคลาสที่รู้วิธีอ่านข้อมูลจากบัฟเฟอร์โดยใช้โปรโตคอล InputStream

นี่คือลักษณะ:

รหัส
public static void main(String[] args) throws IOException
{
 //Put data into a string
 StringBuilder sb = new StringBuilder();
 sb.append("Lena").append('\n');
 sb.append("Olya").append('\n');
 sb.append("Anya").append('\n');
 String data = sb.toString();

 //Wrap the string in a ByteArrayInputStream
 InputStream is = new ByteArrayInputStream(data.getBytes());

 //Replace in
 System.setIn(is);

 //Call an ordinary method that doesn't know about our changes
 readAndPrintLine();
}

public static void readAndPrintLine() throws IOException
{
 InputStreamReader isr = new InputStreamReader(System.in);
 BufferedReader reader = new BufferedReader(isr);

 while (true)
 {
  String line = reader.readLine();
  if (line == null) break;
  System.out.println(line);
 }
 reader.close();
 isr.close();
}

"Bilaabo! นี่เป็นตัวอย่างที่น่าสนใจที่สุดที่ฉันเคยเห็น ฉันไม่รู้ว่าคุณทำได้ ขอบคุณ"

"ยินดีด้วยนะ อามีโก้"