我有一个文本文件。每条线的长度略有不同。我想读取每行的第 44 个字符到行尾。对于某些行工作正常,但对于其他行则出现越界错误。
int lineNumber = 0;
ArrayList<String> SenState = new ArrayList<String>();
while((line=bufferedReader.readLine())!=null){
lineNumber++;
if (lineNumber >= 24) {
String temp = line.substring(44, 46);//error occurs here for int 46
SenState.add(temp);
}
}
下面是我正在读取的文本文件的一部分。我只需要获取每行的 Val
Start time End time ID Val
-------------------- -------------------- -- ---
25-Feb-2008 00:20:14 25-Feb-2008 00:22:57 24 1
25-Feb-2008 09:33:41 25-Feb-2008 09:33:42 24 1
25-Feb-2008 09:33:47 25-Feb-2008 17:21:12 24 1
25-Feb-2008 09:36:43 25-Feb-2008 09:37:04 5 1
25-Feb-2008 09:37:20 25-Feb-2008 09:37:23 6 1
最佳答案
i want to read for the 44th character of each line to the end of the line
那就调用 String.substring(int)
:
String temp = line.substring(44);
我强烈怀疑您当前代码的问题在于,当值 1 仅具有单个字符时,它期望获得 2 个字符。索引 46 超出范围。
(此外,我强烈建议您遵循 Java 命名约定 - SenState
应该是 senState
- 或者更好,可以清楚地表明含义。)
关于java - 从一行的特定部分读取到末尾(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22987868/