gpt4 book ai didi

java - 子字符串的 StringOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 05:35:26 27 4
gpt4 key购买 nike

我当前正在尝试在包含以下行的文本文件 (sample.text) 上运行以下命令:

personPersistenceType=SQLite3
personDbConnectionString=person.sqlite3

但是我收到了 StringOutOfBoundsException(结果 -1)。我知道这意味着它找不到 = 符号,但我不确定为什么。我试图将= 符号之前的所有内容都设为字符串键,将= 符号之后的所有内容设为字符串值。

import java.util.Scanner;

public class TextReader {

private Scanner input = new Scanner("sample.txt");

public void loadFile(){
while(input.hasNextLine()){
String line = input.nextLine(); //acquires line
String key = line.substring(0, line.indexOf('=')); //key
String value = line.substring(line.indexOf('=') + 1); //value
config.setProperty(key, value);
}
}
}

最佳答案

问题:

new Scanner("sample.txt");

您在构造函数中传递的是字符串而不是文件位置,因此会出现StringOutOfBoundsException

解决方案:

您需要通过在 Scanner 的构造函数中传递 File 类来添加扫描仪内的文件位置

Scanner input = new Scanner(new File("sample.txt"));

顺便说一句,您的实现用于解析字符串。

关于java - 子字符串的 StringOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25007532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com