37

I am trying to pass a String to my BufferedReader. How can I pass "test" as String to the reader rather than the input from System.in ?

String test = "test";
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

2 Answers 2

54

You can modify your code as below

String test = "test";
Reader inputString = new StringReader(test);
BufferedReader reader = new BufferedReader(inputString);
Sign up to request clarification or add additional context in comments.

Comments

11

No point in buffering a string. Just

String aString = ...;
Reader inFromUser = new StringReader(aString);

7 Comments

but how to send it to the server in this way. Can u please adapter your answer to my code to understand your solution?
String message = "#2016011400#"; Socket clientSocket = new Socket("localhost", 39537); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); outToServer.writeBytes(message + '\n'); clientSocket.close();. I have tried the following but it does not work for me.
there is a point in buffering a String if it's huge and you want to read it line-by-line
@JonathanLandrum If you have a String, it's already fully in memory by definition. If you just mean that BufferedReader has the lines() method, and StringReader doesn't, fair enough, but it's fixed in Java 11 (docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/…).
A point might be: unit testing a method which expects a BufferedReader, and providing it as a String is the easiest.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.