Я создал пользовательскую функцию, которая должна искать в файле указанный тег и возвращать его значение, например:
Вызов функции:
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
Проблема может быть что-то со строкой, потому что когда я ее печатаю, я не получаю никакого сообщения в консоли, но я действительно не знаю, что с ней может быть не так, если проблема в ней.
Вся помощь очень ценится!