Reputation: 13
I am trying to read from scanner with spaces, i want to read even the spaces. for example "john smith" to be read "john smith".
my code is as follow: when it gets to the space after john it just hangs and doesn't read any more. any help would be appreciated.
Scanner in = new Scanner(new InputStreamReader(sock.getInputStream()));
String userName = "";
while (in.hasNext()) {
userName.concat(in.next());
}
Upvotes: 0
Views: 441
Reputation: 3190
When we use Scanner.next() to read token there is what we call a delimiter, the default delimiter used in by Scanner is \p{javaWhitespace}+ , you can get it by calling Scanner.delimiter(), which is any char that validate the Character.isWhitespace(char). you can use a customized delimiter for your Scanner using Scanner.useDelimiter().
If you want to take one line as a string so you can use nextLine()
, if you already know what is the type of the next token in the input stream, scanner gives you a list of method next*()
take convert the token to the specified type. see Scanner's doc here for more info.
Upvotes: 0
Reputation: 726509
Scanner.next()
returns the next token, delimited by whitespace. If you would like to read the entire line, along with the spaces, use nextLine()
instead:
String userName = in.nextLine();
Upvotes: 1
Reputation: 37034
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
or
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
Upvotes: 0