Here is my code:
public static void main(String[] args) {
String in = "";
InputStreamReader reader = new InputStreamReader(System.in);
int ch;
StringBuilder sb = new StringBuilder();
System.out.println("paste text below:");
try {
while ((ch = reader.read()) != -1 && ch != 0) {
sb.append((char)ch);
}
}catch (IOException e) {
System.err.println(e.toString());
}
}
in = sb.toString();
System.out.println(in);
}
I have debugged, and it runs through everything and prints each char on a newline, but it invaraible stalls after it has read the last character. I have typed simply asdfasdf
as well as copied the Declaration of Independence and pasted it. It runs all the way to then end and then stalls.
It's not even like it is an infinite loop because I have put a System.out.print("!@#$%") in every part of the code, and it just stops... no infinite loop in my code. I am quite certain that the InputStreamReader
-- reader
-- is stuck in an infinite loop of it's own because it is never returning -1. In fact it's never returning anything when it gets to the end (though it returns the correct ints/chars in the loop).
Does anyone know what's going on or has anyone had a similar problem? Is there a way to get around this (don't say BufferedReader because I need to read text with multiple newline characters, and BufferedReader searches for the first \n
, so I cannot use it)?
EDIT:
I have tried reading to a char buffer and then using a string builder... nothing.
ANSWER:
You have to provide a character that will break the loop (otherwise see @default locales's answer).
Here is what my code evolved into:
public static void main(String[] args) {
InputStreamReader reader = new InputStreamReader(System.in);
StringBuilder sb = new StringBuilder();
int ch;
System.out.println("Paste text below (enter or append to text \"ALT + 1\" to exit):");
try {
while ((ch = reader.read()) != (char)63 /*(char)63 could just be ☺*/) {
sb.append(ch);
}
reader.close();
}catch (IOException e) {
System.err.println(e.toString());
}
String in = sb.toString();
System.out.println(in);
}
Alt + 1
returns (on Windows at least) returns the smiley face icon, but you can do whatever key combo you want and all you have to do is find out what char that is in java and do while ((ch = reader.read()) != (char)charNumber
.