Запись данных в кастомный конфиг

Baraban4ik

Разработчик
Пользователь
Сообщения
270
Решения
1
так я хотел записать данные в файл конфига но выходит ошибка

Код:
[20:51:30 ERROR]: Error occurred while enabling EcoLobby v1.0-SNAPSHOT (Is it up to date?)
java.lang.NullPointerException: null
        at com.sp3ctr0.ecolobby.commands.EcoLobbyCommand.<init>(EcoLobbyCommand.java:25) ~[?:?]
        at com.sp3ctr0.ecolobby.Ecolobby.register(Ecolobby.java:45) ~[?:?]
        at com.sp3ctr0.ecolobby.Ecolobby.onEnable(Ecolobby.java:34) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:316) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) ~[patched_1.12.2.jar:git-Paper-1618]
        at com.rylinaux.plugman.util.PluginUtil.load(PluginUtil.java:309) ~[?:?]
        at com.rylinaux.plugman.util.PluginUtil.load(PluginUtil.java:267) ~[?:?]
        at com.rylinaux.plugman.util.PluginUtil.reload(PluginUtil.java:393) ~[?:?]
        at com.rylinaux.plugman.command.ReloadCommand.execute(ReloadCommand.java:122) ~[?:?]
        at com.rylinaux.plugman.PlugManCommandHandler.onCommand(PlugManCommandHandler.java:95) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:152) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:685) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchServerCommand(CraftServer.java:648) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.aP(DedicatedServer.java:463) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:424) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:774) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:666) ~[patched_1.12.2.jar:git-Paper-1618]
        at java.lang.Thread.run(Thread.java:834) [?:?]
Команда:

Java:
package com.sp3ctr0.ecolobby.commands;

import com.sp3ctr0.ecolobby.Ecolobby;
import com.sp3ctr0.ecolobby.configurations.Configurations;
import com.sp3ctr0.ecolobby.utils.Chat;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

import java.util.List;

public class EcoLobbyCommand<c> implements CommandExecutor {

    private Configurations configurations;
    private Ecolobby plugin;

    public EcoLobbyCommand(Configurations configurations, Ecolobby pl) {
        this.configurations = configurations;
        this.plugin = pl;
    }

    FileConfiguration c = this.configurations.get("config.yml");

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (command.getName().equalsIgnoreCase("ecolobby")) {
            if (args.length >= 1 && args[0].equalsIgnoreCase("test")) {
                String x = "test";
                c.set("x", x);
                this.configurations.save(c, "config.yml");
                sender.sendMessage("Yes");
            }
        }
        return true;
    }

    private void reload(CommandSender sender)
    {
        if (!sender.hasPermission("ecolobby.reload"))
        {
            Chat.sendMessagePrefix(sender, this.configurations.get("messages.yml").getString("no-permissions"));
            return;
        }
        plugin.reload();
        Chat.sendMessagePrefix(sender, this.configurations.get("messages.yml").getString("plugin-reloaded"));
    }

    private void help(CommandSender sender)
    {
        if (!sender.hasPermission("ecolobby.help"))
        {
            Chat.sendMessagePrefix(sender, this.configurations.get("messages.yml").getString("no-permissions"));
            return;
        }
        List<String> help = this.configurations.get("messages.yml").getStringList("help");
        help.forEach((x) -> {
            Chat.sendMessage(sender, x);
        });
    }

}
Майн:

Java:
package com.sp3ctr0.ecolobby;

import com.sp3ctr0.ecolobby.commands.EcoLobbyCommand;
import com.sp3ctr0.ecolobby.configurations.Configurations;
import com.sp3ctr0.ecolobby.handler.SimpleEventHandler;

import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.Arrays;
import java.util.List;

public class Ecolobby extends JavaPlugin {

    public final List<String> ENABLE_MESSAGE = Arrays.asList
            (
                    "§7=-=-=-=-§a§lEco§f§lLobby§7-=-=-=-=",
                    "",
                    " Version: §a" + this.getDescription().getVersion(),
                    " Author: §aSp3ctr0",
                    "",
                    "§7=-=-=-=-§a§lEco§f§lLobby§7-=-=-=-="
            );

    private Configurations configurations = new Configurations(this, "config.yml", "messages.yml");
    public static String prefix;

    @Override
    public void onEnable() {
        ENABLE_MESSAGE.forEach(System.out::println);
        configurations.loadConfigurations();
        prefix = this.configurations.get("messages.yml").getString("prefix");

        this.register();
    }

    @Override
    public void onDisable() {
        System.out.println(ChatColor.RED + "EcoLobby plugin is disabled");
        configurations = null;
    }

    public void register() {
        // Commands:
        getServer().getPluginCommand("ecolobby").setExecutor(new EcoLobbyCommand(configurations, this));


        // Events:
        getServer().getPluginManager().registerEvents(new SimpleEventHandler(), this);


    }

    public void reload() {
        configurations.reloadConfigurations();
        prefix = this.configurations.get("messages.yml").getString("prefix");
    }
}
Конфигурация:

Код:
package com.sp3ctr0.ecolobby.configurations;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.google.common.collect.Lists;
import com.sp3ctr0.ecolobby.Ecolobby;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

public class Configurations
{
    private Map<String, Map.Entry<FileConfiguration, File>> configurations = new HashMap<> ();

    private List<String> configurationsNames;

    private final Plugin plugin;

    public Configurations(Plugin plugin, String... configurationsNames)
    {
        this.plugin = plugin;

        this.configurationsNames = Lists.newArrayList(configurationsNames);

        this.loadConfigurations();
    }


    private File generateDefaultFile(String name)
    {
        File file = new File(this.plugin.getDataFolder(), name);

        if (!file.exists())
        {
            this.plugin.saveResource(name, false);
        }

        return file;
    }

    public void loadConfigurations()
    {
        for (String configurationName : this.configurationsNames)
        {
            if (this.configurations.containsKey(configurationName))
            {
                continue;
            }

            File configurationFile = this.generateDefaultFile(configurationName);

            FileConfiguration configuration = YamlConfiguration.loadConfiguration(configurationFile);

            this.configurations.put(configurationName, new AbstractMap.SimpleEntry<> (configuration, configurationFile));
        }
    }

    public void reloadConfigurations()
    {
        this.configurations.clear();

        this.loadConfigurations();
    }

    private Optional<Map.Entry<FileConfiguration, File>> getEntry(String configurationName)
    {
        return Optional.ofNullable(this.configurations.get(configurationName));
    }

    public FileConfiguration get(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getKey)
                .orElse(null);
    }

    private File getFile(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getValue)
                .orElse(null);
    }


    public FileConfiguration save(FileConfiguration fileConfiguration, String s) {
        try {
            fileConfiguration.save(new File(plugin.getDataFolder(), s));
        } catch (IOException var3) {
            var3.printStackTrace();
        }
        return fileConfiguration;
    }
}
 
Решение
Java:
EcoLobbyCommand<c>
FileConfiguration c = this.configurations.get("config.yml");
???
Все поля класса объявляются до объявления конструктора класса.

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

По поводу ошибки - ты не можешь назначить значение переменной еще до того, как само значение проинициализировалось. Иначе говоря:
Java:
private Configurations configurations;

private FileConfiguration c;

public Command(Configurations configurations) {
    this.configurations = configurations;
    c = configurations.get("config.yml");
}
Тебе...
Java:
EcoLobbyCommand<c>
FileConfiguration c = this.configurations.get("config.yml");
???
Все поля класса объявляются до объявления конструктора класса.

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

По поводу ошибки - ты не можешь назначить значение переменной еще до того, как само значение проинициализировалось. Иначе говоря:
Java:
private Configurations configurations;

private FileConfiguration c;

public Command(Configurations configurations) {
    this.configurations = configurations;
    c = configurations.get("config.yml");
}
Тебе гораздо проще будет задавать подобные вопросы в моём дискорде - и не плодить на форуме кучу тем с вопросами подобного уровня.
 
Последнее редактирование:
Java:
EcoLobbyCommand<c>
FileConfiguration c = this.configurations.get("config.yml");
???
Все поля класса объявляются до объявления конструктора класса.

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

По поводу ошибки - ты не можешь назначить значение переменной еще до того, как само значение проинициализировалось. Иначе говоря:
Java:
private Configurations configurations;

private FileConfiguration c;

public Command(Configurations configurations) {
    this.configurations = configurations;
    c = configurations.get("config.yml");
}
Тебе гораздо проще будет задавать подобные вопросы в моём дискорде - и не плодить на форуме кучу тем с вопросами подобного уровня.
Уже решил но учту
 
Назад
Сверху Снизу