【问题标题】:reading String with spaces java读取带空格的字符串java
【发布时间】:2014-05-31 10:27:29
【问题描述】:

我正在尝试从带有空格的扫描仪中读取,我什至想读取空格。 例如,将“john smith”读作“john smith”。

我的代码如下: 当它在 john 之后到达空间时,它只是挂起并且不再读取。 任何帮助将不胜感激。

Scanner in = new Scanner(new InputStreamReader(sock.getInputStream()));

String userName = "";
while (in.hasNext()) {
    userName.concat(in.next());
}

【问题讨论】:

  • 为什么你不使用scanner.nextLine();我的意思是in.nextLine();

标签: java


【解决方案1】:

Scanner.next() 返回下一个标记,由空格分隔。如果您想阅读整行以及空格,请改用nextLine()

String userName = in.nextLine();

【讨论】:

    【解决方案2】:
    Scanner scan = new Scanner(file);  
    scan.useDelimiter("\\Z");  
    String content = scan.next();   
    

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

    【讨论】:

      【解决方案3】:

      当我们使用Scanner.next()读取token的时候,有我们所说的分隔符,Scanner使用的默认分隔符是\p{javaWhitespace}+,你可以通过调用Scanner.delimiter()得到它,它是任意的验证Character.isWhitespace(char) 的字符。您可以使用Scanner.useDelimiter() 为您的扫描仪使用自定义分隔符。

      如果您想将一行作为字符串以便您可以使用 nextLine() ,如果您已经知道输入流中下一个标记的类型是什么,scanner 会为您提供方法列表 next*() take convert指定类型的令牌。有关详细信息,请参阅 Scanner 的文档here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-29
        • 2011-02-20
        • 1970-01-01
        • 2021-03-09
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多