How can I create a BufferedReader from a String? - java

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));

You can modify your code as below
String test = "test";
Reader inputString = new StringReader(test);
BufferedReader reader = new BufferedReader(inputString);

No point in buffering a string. Just
String aString = ...;
Reader inFromUser = new StringReader(aString);

Related

Having trouble reading in content of url using InputStream

So I run the code below and it prints "!DOCTYPE html". How do I get the content of the url, like the html for instance?
public static void main(String[] args) throws IOException {
URL u = new URL("https://www.whitehouse.gov/");
InputStream ins = u.openStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader websiteText = new BufferedReader(isr);
System.out.println(websiteText.readLine());
}
According to java doc https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html: "When you run the program, you should see, scrolling by in your command window, the HTML commands and textual content from the HTML file located at ".... Why am I not getting that?
In your program, your did not put while loop.
URL u = new URL("https://www.whitehouse.gov/");
InputStream ins = u.openStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader websiteText = new BufferedReader(isr);
String inputLine;
while ((inputLine = websiteText.readLine()) != null){
System.out.println(inputLine);
}
websiteText.close();
You are only reading one line of the text.
Try this and you will see that you get two lines:
System.out.println(websiteText.readLine());
System.out.println(websiteText.readLine());
Try reading it in a loop to get all the text.
BufferedReader has a method called #lines() since Java 8. The return type of #lines() is Stream. To read an entire site you could do something like that:
String htmlText = websiteText.lines()
.reduce("", (text, nextLine) -> text + "\n" + nextLine)
.orElse(null);

Java input readers - chaining the input stream API

what the difference between both stream chaining methods ?
first :
BufferedReader br = new BufferedReader(
new InputStreamReader(someUrlConnection.getInputStream(), encoding));
second :
InputStream raw = someUrlConnection.getInputStream();
InputStream buffer = new BufferedInputStream(raw);
Reader reader = new InputStreamReader(buffer);

Substitute for Scanner when using Sockets

Is there a better substitute for Scanner class when using sockets? i am getting really tired of the .next() and .nextLine() that are really annoying to work with because they skip lines all the time.
Use InputStreamReader along with BufferedReader
Eg:
Socket s = new Socket("10.0.0.1",4444);
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
String str = new String();
while ((str = br.readLine())!=null){
System.out.println(str);
}

Convert InputStream to BufferedReader

I'm trying to read a text file line by line using InputStream from the assets directory in Android.
I want to convert the InputStream to a BufferedReader to be able to use the readLine().
I have the following code:
InputStream is;
is = myContext.getAssets().open ("file.txt");
BufferedReader br = new BufferedReader (is);
The third line drops the following error:
Multiple markers at this line
The constructor BufferedReader (InputStream) is undefinded.
What I'm trying to do in C++ would be something like:
StreamReader file;
file = File.OpenText ("file.txt");
line = file.ReadLine();
line = file.ReadLine();
...
What am I doing wrong or how should I do that? Thanks!
BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:
Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);
Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.
InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

Reading InputStream as UTF-8

I'm trying to read from a text/plain file over the internet, line-by-line. The code I have right now is:
URL url = new URL("http://kuehldesign.net/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
LinkedList<String> lines = new LinkedList();
String readLine;
while ((readLine = in.readLine()) != null) {
lines.add(readLine);
}
for (String line : lines) {
out.println("> " + line);
}
The file, test.txt, contains ¡Hélló!, which I am using in order to test the encoding.
When I review the OutputStream (out), I see it as > ¬°H√©ll√≥!. I don't believe this is a problem with the OutputStream since I can do out.println("é"); without problems.
Any ideas for reading form the InputStream as UTF-8? Thanks!
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
I ran into the same problem every time it finds a special character marks it as ��. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
If you use the constructor InputStreamReader(InputStream in, Charset cs), bad characters are silently replaced. To change this behaviour, use a CharsetDecoder :
public static Reader newReader(Inputstream is) {
new InputStreamReader(is,
StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
);
}
Then catch java.nio.charset.CharacterCodingException.

Categories