我正在通过文件进行非常基本的循环。该文件包含许多条目,但是,它似乎在第三个循环之后中断,该循环肯定包含超过25个字符。简单的循环如下:处理字符串超出范围例外
public static void organiseFile() throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<>();
String directory = "C:\\Users\\hussainm\\Desktop\\Files\\ex1";
Scanner fileIn = new Scanner(new File(directory + "_temp.txt"));
PrintWriter out = new PrintWriter(directory + "_ordered.txt");
while (fileIn.hasNextLine() == true) {
if (!fileIn.nextLine().isEmpty()) {
lines.add(fileIn.nextLine());
String test = fileIn.nextLine().substring(12, 25);
System.out.println(test);
}
}
我不知道是什么问题,但它不断抛出:
异常线程“main” java.lang.StringIndexOutOfBoundsException: 字符串索引超出的范围:在25 java.lang.String.substring(未知 源)在 fedOrganiser.fedOrganiser.organiseFile(fedOrganiser.java:41)在 fedOrganiser.fedOrganiser.main(fedOrganiser.java:31)
不知道它的问题是什么。
文件如下:
https://www.dropbox.com/s/69h1f8u387zikbp/ex1_temp.txt?dl=0
请编辑您的问题并添加您尝试阅读的文件的内容。 –
检查您的C:\\ Users \\ hussainm \\ Desktop \\ Files \\ ex1_temp.txt文件。检查每一行是否长达25个字符? –
每次检查文件是否有下一行时,您还要调用nextLine()3次。 nextLine()返回**下一行**,每次调用它时。 –