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);
}
}我正在读取一个包含多行空白(不仅仅是空白)的文件,并比较某些索引处的字符,以确定是否需要该行。然而,当我读取一行空白时,我得到的字符串索引超出了范围。
发布于 2012-02-10 12:42:40
例如,如果行的长度为0,并且您正在尝试确定位置10处的字符,那么您将得到一个异常。在处理该行之前,只需检查该行是否全部为空格。
if (line != null && line.trim().length() > 0)
{
//process this line
}发布于 2012-02-10 13:27:33
空行不是null,而是空字符串'‘。如果您尝试读取索引0处的字符,它将会崩溃。
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类。它对于在文件中读取数据非常有用。
发布于 2012-02-10 13:44:13
您在这里所做的是使用strLine.charAt(25)检查到第25个字符,而您的String strLine可能没有那么多字符。如果charAt(int index)参数不小于此字符串的长度,则index方法将抛出IndexOutOfBoundsException。
您可以通过调用strLine.length()找到strLine的长度,然后检查从0到strLine.length() - 1的charAt(),您将看不到该异常。
https://stackoverflow.com/questions/9222762
复制相似问题