How to get line number in file from the character position using java

996 Views Asked by At

I have one JSON file and having some issue in it. When parsing the json file I will get the ParserException. From parser exception I have extracted the position where the is problem.

Now I want the line number of the that particular position in file.

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();
}
1

There are 1 best solutions below

0
On
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);
}