我正在将大约79列的文件导入Java,并尝试将这些行读取到数组中。然后,我提取char
进行后处理。但是,当我使用索引大于41的.charAt()
或.substring()
时,会引发错误。
我还使用.length()
检查行的长度,它显示79索引明显在范围内。
此处的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser myFileChooser = new JFileChooser();
if (myFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
jTextField1.setText(myFileChooser.getSelectedFile().getPath());
}
FileReader file = null;
try {
file = new FileReader(myFileChooser.getSelectedFile().getPath());
} catch (FileNotFoundException ex) {
Logger.getLogger(GPS.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader myInput = new BufferedReader(file);
String[] textdata = new String[4000];
int i = 0;
do {
try {
textdata[i] = myInput.readLine();
} catch (IOException ex) {
Logger.getLogger(GPS.class.getName()).log(Level.SEVERE, null, ex);
}
if (textdata[i].length() > 0) {
System.out.println(textdata[i].length()-1);
headerLabel = String.valueOf(textdata[i].charAt(60));
switch (headerLabel) {
case "R":
fileType = String.valueOf(textdata[i].charAt(20));
if (!"N".equals(fileType)) {
jLabel28.setText("File incorrectly imported");
break;
}
version = textdata[i].substring(5, 9);
jLabel26.setText(version);
mode = String.valueOf(textdata[i].charAt(40));
}
i++;
} while (textdata[i - 1] != null);
}
错误发生在headerLabel = String.valueOf(textdata[i].charAt(60));
,抛出:Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 60
该如何解决问题?