Java 读取行空白
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);
}
}
我正在读取带有空格行(不仅仅是空格)的文件,并比较某些索引处的字符以查看是否需要该行,但是当我读取一行空格时,我得到的字符串索引超出范围。
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);
}
}
I am reading in a file with lines of whitespace(not only whitespace) and comparing chars at certain indexes to see if I need the line however when I read in a line of whitespace I get a string index out of range.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如,如果该行的长度为 0 并且您试图确定位置 10 处的字符,您将得到一个异常。只需在处理之前检查该行是否不全是空格。
If the line is length 0 and you are trying to determine the character at location 10 for example you are going to get an exception. Just put in a check to see if the line is not all whitespace before processing it.
空行不会为 null,而是空字符串 ''。如果您尝试读取索引 0 处的字符,它将中断。
您还可以尝试使用 Java Scanner 类。它对于读取文件确实很有用。
An empty line will not be null, but and empty string ''. It will break if you try and read the character at index 0.
You can also try and use the Java Scanner class. It is really useful for reading in files.
您在这里所做的是使用
strLine.charAt(25)
检查章程直到第 25 个字符,而您的String strLine
可能没有那么多字符。如果index
参数不小于该字符串的长度,则charAt(int index)
方法将抛出IndexOutOfBoundsException
。您可以通过调用
strLine.length()
找到strLine
的长度,然后检查0
中的charAt()
> 到strLine.length() - 1
并且您不会看到该异常。What you are doing here is the checking the charter till 25th character using
strLine.charAt(25)
whereas yourString strLine
may not have those many characters. ThecharAt(int index)
method will throwIndexOutOfBoundsException
- if theindex
argument is not less than the length of this string.You can find the length of
strLine
by callingstrLine.length()
and then check thecharAt()
from0
tostrLine.length() - 1
and you will not see that exception.