"नमस्कार, अमीगो! आज हम कुछ बहुत ही दिलचस्प चीज़ों के बारे में जानेंगे: System.in इनपुट स्ट्रीम को कैसे बदलें ।"

System.in  एक साधारण स्थैतिक InputStream चर है, लेकिन आप इसे केवल एक नया मान नहीं दे सकते। लेकिन आप System.setIn() विधि का उपयोग कर सकते हैं।

सबसे पहले, हमें एक बफ़र बनाने की ज़रूरत है, और फिर उसमें कुछ मान डालें। फिर हम इसे एक ऐसे वर्ग में लपेटेंगे जो जानता है कि इनपुटस्ट्रीम प्रोटोकॉल का उपयोग करके बफर से डेटा कैसे पढ़ना है।

यह कैसा दिखता है:

कोड
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();
}

"बिलाबो! यह सबसे दिलचस्प उदाहरण है जो मैंने देखा है। मुझे नहीं पता था कि आप ऐसा कर सकते हैं। धन्यवाद।"

"आपका स्वागत है, अमीगो।"