Пользовательская функция, которая ищет теги в файле, всегда возвращает значение null

Я создал пользовательскую функцию, которая должна искать в файле указанный тег и возвращать его значение, например:

Вызов функции:

getSingleLineValue("tagname");

В файле найдена строка:

<tagname>=tagvalue

Возвращаемая строка:

tagvalue

Вот код функции:

public String getSingleLineValue(String tag) {
    // The value
    String value;
    // If the list of passed tags contains the wanted tag
    if(passedTags.contains(tag)) {
        // Close the readers
        close();
        // RESET EVERYTHING
        try {
            // Re-create the FileReader
            fileReader = new FileReader(file);
            // Re-create the BufferedReader
            bufferedReader = new BufferedReader(fileReader);
            // Reset the passed tags array
            passedTags.clear();
            // Recall the function
            value = getSingleLineValue(tag);
            // Return the value
            return value;
        } catch(IOException e) {
            // Handle the exception
            e.printStackTrace();
        }
    } else {
        try {
            // The current line
            String line;
            // While the file has lines left
            while ((line = bufferedReader.readLine()) != null) {
                // If the current line contains a pair of tag marks ( < and > )
                if (line.contains("<") && line.contains(">")) {
                    // If the line contains the tag
                    if(line.contains(tag)) {
                        // Store the parts of the tag in an array (tag and value)
                        String[] tagParts = line.split("=");
                        // Get the value
                        value = tagParts[1];
                        // Return the value
                        return value;
                    } else {
                        // Get the passed tag
                        String passedTag = line.substring(1, line.indexOf(">") - 1);
                        // Add the tag to the passed tags array
                        passedTags.add(passedTag);
                    }
                }
            }
        } catch(IOException e) {
            // Handle the exception
            e.printStackTrace();
        }
    }
    // If the tag wasn't found, return null
    return null;
}

Объект с именем file представляет собой простой объект File с путем к файлу, который я хочу прочитать. Он объявлен в том же классе.

Объекты под названием fileReader и bufferedReader — это то, на что это похоже. FileReader и BufferedReader, объявленные следующим образом (также в том же классе):

private FileReader fileReader;
private BufferedReader bufferedReader;

И в конструкторе класса:

fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);

Проблема в том, что эта функция всегда возвращает null, поэтому, когда я ее вызываю, вышеприведенная демонстрация того, как я хочу, чтобы она работала, вместо этого будет выглядеть примерно так:

Вызов функции:

getSingleLineValue("tagname");

В файле найдена строка:

Неизвестно (может быть проблема в этом?)

Возвращаемая строка:

null

Проблема может быть что-то со строкой, потому что когда я ее печатаю, я не получаю никакого сообщения в консоли, но я действительно не знаю, что с ней может быть не так, если проблема в ней.

Вся помощь очень ценится!


person Daniel Kvist    schedule 03.12.2014    source источник


Ответы (1)


Я узнал, в чем была проблема. Дело было не в функции, которая на самом деле работала нормально, а в кодировке файла.

Я создал простую компьютерную версию и добавил в нее функцию, и распечатал все прочитанные строки, и обнаружил, что в программе файл читается иначе, чем в Sublime Text (текстовый редактор на компьютере). Строка, которая выглядела так:

ABCDEFG

в текстовом редакторе программа читала так:

A B C D E F G

Таким образом, он добавил пробел между каждым символом. Думаю проблема с кодировкой файла, так что сама функция прекрасно работает.

EDIT: я решил проблему с кодировкой файла с помощью FileInputStream и установил для него кодировку "UTF-16LE", которая была правильной кодировкой для моего файла, поэтому приведенный выше код вместо этого выглядел так:

public String getSingleLineValue(String tag) {
    // The value
    String value;
    // If the list of passed tags contains the wanted tag
    if(passedTags.contains(tag)) {
        // Close the readers
        close();
        // RESET EVERYTHING
        try {
            // Re-create the FileInputStream
            fileInput = new FileInputStream(file);  // <----- Changed
            // Re-create the InputStreamReader
            inputReader = new InputStreamReader(fileInput, "UTF-16LE");  // <----- Changed
            // Re-create the BufferedReader
            bufferedReader = new BufferedReader(inputReader);  // <----- Changed
            // Reset the passed tags array
            passedTags.clear();
            // Recall the function
            value = getSingleLineValue(tag);
            // Return the value
            return value;
        } catch(IOException e) {
            // Handle the exception
            e.printStackTrace();
        }
    } else {
        try {
            // The current line
            String line;
            // While the file has lines left
            while ((line = bufferedReader.readLine()) != null) {
                // If the current line contains a pair of tag marks ( < and > )
                if (line.contains("<") && line.contains(">")) {
                    // If the line contains the tag
                    if(line.contains(tag)) {
                        // Store the parts of the tag in an array (tag and value)
                        String[] tagParts = line.split("=");
                        // Get the value
                        value = tagParts[1];
                        // Return the value
                        return value;
                    } else {
                        // Get the passed tag
                        String passedTag = line.substring(1, line.indexOf(">") - 1);
                        // Add the tag to the passed tags array
                        passedTags.add(passedTag);
                    }
                }
            }
        } catch(IOException e) {
            // Handle the exception
            e.printStackTrace();
        }
    }
    // If the tag wasn't found, return null
    return null;
}
person Daniel Kvist    schedule 03.12.2014