首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java readline空格

Java readline空格
EN

Stack Overflow用户
提问于 2012-02-10 12:38:30
回答 3查看 3.6K关注 0票数 0
代码语言:javascript
复制
FileInputStream fstream = new FileInputStream("data.txt");

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;
//Read File Line By Line

while ((strLine = br.readLine()) != null) 
  {
    //Test if it is a line we need
    if(strLine.charAt(0) != ' ' && strLine.charAt(5) == ' '
       && strLine.charAt(10) == ' ' && strLine.charAt(15) == ' '
       && strLine.charAt(20) == ' ' && strLine.charAt(25) == ' ' )
      {
        System.out.println (strLine);
      }
  }

我正在读取一个包含多行空白(不仅仅是空白)的文件,并比较某些索引处的字符,以确定是否需要该行。然而,当我读取一行空白时,我得到的字符串索引超出了范围。

EN

回答 3

Stack Overflow用户

发布于 2012-02-10 12:42:40

例如,如果行的长度为0,并且您正在尝试确定位置10处的字符,那么您将得到一个异常。在处理该行之前,只需检查该行是否全部为空格。

代码语言:javascript
复制
if (line != null && line.trim().length() > 0)
{
   //process this line
}
票数 2
EN

Stack Overflow用户

发布于 2012-02-10 13:27:33

空行不是null,而是空字符串'‘。如果您尝试读取索引0处的字符,它将会崩溃。

代码语言:javascript
复制
 while ((strLine = br.readLine()) != null) 
 {
    //remove whitespace infront and after contents of line.
    strLine = strLine.trim();

    if (strLine.equals(""))
      continue;

     //check that string has at least 25 characters when trimmed.
    if (strLine.length() <25)  
       continue;

    //Test if it is a line we need
    if(strLine.charAt(0) != ' ' && strLine.charAt(5) == ' ' && strLine.charAt(10) == ' ' && strLine.charAt(15) == ' ' && strLine.charAt(20) == ' ' && strLine.charAt(25) == ' ' )
    {
         System.out.println (strLine);
    }
 }

您还可以尝试使用Java Scanner类。它对于在文件中读取数据非常有用。

票数 0
EN

Stack Overflow用户

发布于 2012-02-10 13:44:13

您在这里所做的是使用strLine.charAt(25)检查到第25个字符,而您的String strLine可能没有那么多字符。如果charAt(int index)参数不小于此字符串的长度,则index方法将抛出IndexOutOfBoundsException

您可以通过调用strLine.length()找到strLine的长度,然后检查从0strLine.length() - 1charAt(),您将看不到该异常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9222762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档