Reputation: 286
I'm writing a huffman tree and I need to know the frequencies of line breaks and spaces.
Using Scanner
or InputStreamReader
, is there anyway to store sentences with line breaks and spaces into a single String?
If I have the code below,
public class HuffmanTreeApp {
public static void main(String[] args) throws IOException {
HuffTree theTree = new HuffTree();
System.out.print("sentence: ");
String get;
get = getString();
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
and if my input is
"you are
good";
then I wanna store all the characters including line breaks and spaces into this one string variable get. So in this case, there will be one line break and one space.
Is this possible?
Upvotes: 2
Views: 910
Reputation: 9011
If you are reading from file, you can use
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
If you are taking input from a console
you can use any other delimiter
to end the reading.
Upvotes: 1
Reputation: 1819
Instead of using readLine (which reads characters until it finds a new line character, and then discard it), use read(char[], offset, len), which will capture new lines as well.
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
char [] buf = new char[0xff];
while(br.read(buf, 0, 0xff))
{
sb.append(new String(buf, "utf-8"));
}
String result = sb.toString();
Upvotes: 2