0

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());
}
1
  • why you do not use scanner.nextLine(); i mean in.nextLine(); Commented May 31, 2014 at 10:30

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0
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();
        }

Comments

0

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.

Comments

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.