Java读线空白
我正在读取一个包含几行空格(不仅仅是空格)的文件,并比较某些索引处的字符,看看是否需要这一行。然而,当我读取一行空格时,我得到的字符串索引超出了范围 如果行的长度为0,并且您试图确定位置10处的字符,例如,您将得到一个异常。在处理它之前,只需检查一下这行是否都是空白Java读线空白,java,whitespace,readline,Java,Whitespace,Readline,我正在读取一个包含几行空格(不仅仅是空格)的文件,并比较某些索引处的字符,看看是否需要这一行。然而,当我读取一行空格时,我得到的字符串索引超出了范围 如果行的长度为0,并且您试图确定位置10处的字符,例如,您将得到一个异常。在处理它之前,只需检查一下这行是否都是空白 FileInputStream fstream = new FileInputStream("data.txt"); // Get the object of DataInputStream DataInputStream in
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);
}
}
空行将不为null,但为空字符串“”。如果尝试读取索引0处的字符,它将中断
if (line != null && line.trim().length() > 0)
{
//process this line
}
while((strLine=br.readLine())!=null)
{
//删除行内容前后的空格。
strLine=strLine.trim();
if(strLine.equals(“”)
继续;
//检查字符串在修剪时是否至少包含25个字符。
if(strLine.length()您在这里所做的是使用strLine.charAt(25)
检查charter到第25个字符,而您的字符串strLine
可能没有那么多字符。charAt(int index)
方法将抛出IndexOutOfBoundsException
——如果index
参数不小于此字符串的长度
您可以通过调用strLine.length()
找到strLine.length的长度,然后从0
到strLine.length()-1
检查charAt()
,您将不会看到异常情况。您可以提供一些代码来说明您的问题吗?需要查看一些代码来帮助您解决。。。
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);
}
}