Java字符串索引超出范围:-45
我试图通过GUI中的文件浏览器接受用户的文件,并逐行读取文件。基本上,我的兴趣是知道字符位置60和80之间到底写了什么,因为在此基础上,我得出了一些结论,需要做出一些决定,尤其是读取一个rinex.o文件。 但是我在线程AWT-EventQueue-0java.lang.StringIndexOutOfBoundsException中得到错误异常:字符串索引超出范围:-45 行中:String typeField=line.substring60,line.length;无法前进 提前谢谢你的帮助Java字符串索引超出范围:-45,java,exception,substring,Java,Exception,Substring,我试图通过GUI中的文件浏览器接受用户的文件,并逐行读取文件。基本上,我的兴趣是知道字符位置60和80之间到底写了什么,因为在此基础上,我得出了一些结论,需要做出一些决定,尤其是读取一个rinex.o文件。 但是我在线程AWT-EventQueue-0java.lang.StringIndexOutOfBoundsException中得到错误异常:字符串索引超出范围:-45 行中:String typeField=line.substring60,line.length;无法前进 提前谢谢你的帮
void parseRinexOFile(File inputfile) throws FileNotFoundException, IOException{
File obsFile= inputfile;
// if (obsFile.exists()) //Code to test if the file exists.
// System.out.println("Hello, I exist"+ obsFile.getPath());
// Create File Stream, Stream Reader and Bufferreader
streamObs = new FileInputStream(obsFile);
inStreamObs = new InputStreamReader(streamObs);
buffStreamObs = new BufferedReader(inStreamObs);
BufferedReader in = new BufferedReader(new FileReader(obsFile));
String line="";
while((line = in.readLine()) != null)
{
String typeField=line.substring(60,line.length());
typeField=typeField.trim();
if (typeField.equals("RINEX VERSION / TYPE")) {//Check if the observation file identifier is missing else find the version of the file
if (!line.substring(20, 21).equals("O")) {
// Error if observation file identifier was not found
System.err.println("Observation file identifier is missing in file "
+ obsFile.toString() + " header");
ver = 0;
} else if (line.substring(5, 7).equals("3.")){
ver = 3;
} else if (line.substring(5, 9).equals("2.12")){
ver = 212;
} else {
ver = 2;
System.out.println(" Current version:"+ver);
}
}
//System.out.println(line);
}
in.close();
}
发生异常是因为输入行少于60个字符。在调用substring之前,需要检查行长度。您的字符串长度小于60个字符,因此无法将60作为第一个参数传递给string.substring。正确的解决方案取决于您的要求,但有一种可能是line.substringMath.minline.length,60,line.length。由于line.length小于60,因此出现此异常,请在执行此操作之前测试字符串的长度:
String typeField="";
if(line.length()>60){
typeField=line.substring(60,line.length());
}
你已经超出了限制
//this line is throwing the exception...
String typeField=line.substring(60,line.length());
检查字符串是否包含以下内容以避免异常:
if (line.contains("RINEX VERSION / TYPE")) {//Check if the observation file identifier is missing else find the version of the file