如何使用java从字符位置获取文件中的行号

如何使用java从字符位置获取文件中的行号,java,file,line,line-numbers,parsing-error,Java,File,Line,Line Numbers,Parsing Error,我有一个JSON文件,其中有一些问题。解析json文件时,我将获得ParserException。从解析器异常中,我提取了问题所在的位置 现在我想要文件中那个特定位置的行号 JSONObject json; try { if (!file.exists()) { throw new ExceptionDoesNotExist(file); } scanner = new Scanner(file, Charset.defaultCharset().toSt

我有一个JSON文件,其中有一些问题。解析json文件时,我将获得ParserException。从解析器异常中,我提取了问题所在的位置

现在我想要文件中那个特定位置的行号

JSONObject json;
try {
    if (!file.exists()) {
        throw new ExceptionDoesNotExist(file);
    }
    scanner = new Scanner(file, Charset.defaultCharset().toString());
    String data = scanner.useDelimiter("\\Z").next();
    json = (JSONObject) new JSONParser().parse(data);
    return json;
} catch (ParseException e) {
    this.log.logException(e);
    int position = e.getPosition();
    String reason = e.getUnexpectedObject().toString();
    return new JSONObject();
}
如果(!file.exists()){
抛出新的ExceptionDeesnotexist(文件);
}
scanner=新扫描仪(文件,Charset.defaultCharset().toString());
字符串数据=scanner.useDelimiter(“\\Z”).next();
试一试{
返回新的JSONParser().parse(数据);
}捕获(解析异常){
字符串lineAndColumn=lineAndColumn(数据,e,4);
...;
返回新的JSONObject();
}
公共静态字符串lineAndColumn(字符串文本、语法异常、int tabSize){
int position=e.getPosition();
int lineNo=1+(int)text.substring(0,位置).codePoints()
.filter(cp->cp=='\n')
.count();
int columnNo=1+text.substring(0,位置).lastIndexOf('\n')+1;//否\n也可以。
//标签
int-cI=0;
对于(int i=0;i
请共享您的代码,并共享例外JSONObject json try{if(!file.exists()){throw new ExceptionDoesNotExist(file);}scanner=new scanner(file,Charset.defaultCharset().toString());String data=scanner.useDelimiter(“\\Z”).next();json=(JSONObject)new JSONParser().parse(data);return json;}catch(ParseException e){this.log.logException(e);int position=e.getPosition();String reason=e.getUnexpectedObject().toString();return new JSONObject();}编辑您的帖子并将其添加到itAny解决方案中?如果您获得引发异常的字符串,逐行阅读文件,直到找到为止
if (!file.exists()) {
    throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
try {
    return new JSONParser().parse(data);
} catch (ParseException e) {
    String lineAndColumn = lineAndColumn(data, e, 4);
    ...;
    return new JSONObject();
}

public static String lineAndColumn(String text, ParseException e, int tabSize) {
    int position = e.getPosition();
    int lineNo = 1 + (int) text.substring(0, position).codePoints()
            .filter(cp -> cp == '\n')
            .count();
    int columnNo = 1 + text.substring(0, position).lastIndexOf('\n') + 1; // no \n okay too.

    // Tabs
    int cI = 0;
    for (int i = 0; i < columnNo - 1; ++i) {
        if (text.charAt(posion - (columnNo - 1) + i) == '\t') {
            cI += tabSize;
            cI %= tabSize;
        } else {
            ++cI;
        }
    }
    columnNo = cI + 1;

    return String.format("%d:%d"), lineNo, ColumnNo);
}