【发布时间】:2013-11-22 03:23:32
【问题描述】:
每个人。我最近刚刚开始为 Minecraft 编写 Bukkit 插件。我的前两个插件的开发版本已经在我的服务器上运行良好,它们根本没有给我带来太多麻烦。我目前正在研究第三个,但遇到了一些麻烦。
我正在尝试弄清楚如何准确地创建 YAML 文件并从中读取/写入数据。澄清一下,我指的不是config.yml 文件,因为我对此没有任何问题。我知道如何创建一个默认的config.yml 文件并从中读取数据,这一切都很好而且很花哨。但是,对于我的第三个插件,我需要使用单独的 YAML 文件。我四处寻找帮助,但我得到的 95% 的答案涉及有人告诉我一些关于 getConfig() 的事情,这不是我想要的,或者至少我有 95% 的把握这不是我想要的。米找。经过几周寻找明确答案后,我决定在这里发布我的问题。一如既往,提前感谢您的帮助!
我想我已经知道如何创建 YAML 文件了,但之后我就陷入了困境。我只是举一个我的情况的例子。
假设我有以下主要课程:
package ...
import ...
//Here is my main class
public class MyClass extends JavaPlugin {
//I instantiate my File and FileConfiguration here
//Should I do this? I need them for my other classes.
public FileConfiguration myFileConfig = null;
public File myFile;
//On Enable
@Override
public void onEnable() {
//Get/Create File
myFile = new File(getDataFolder(), "myfile.yml");
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//Load myfily.yml file configuration
FileConfiguration myFileConfig = YamlConfiguration.loadConfiguration(myFile);
//Register my command executor class
getCommand("test").setExecutor(new myCommandExecutor());
}
//On Disable
@Override
public void onDisable() {
//Irrelevant stuff here
}
}
现在假设我还有以下 CommandExecutor 类(星号标记重要事情发生的地方。我省略了所有嵌套的 if 函数以节省您的时间):
package ...
import ...
public class myCommandExecutor implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("test")) {
if (args.length > 0) {
****************//RIGHT HERE I WOULD ADD ALL THE COMMAND ARGUMENTS
****************//IMAGINE THE FOLLOWING USAGE FOR THE COMMAND
****************//USAGE: /test <add|del> <one|two|three> <name>
****************//IF THE USER EXECUTED THE FOLLOWING, THE CODE BELOW WOULD BE THE FINAL RESULT
****************//EXECUTED: /test add two hello
YamlClass.addToFile(args[1], args[2]);
} else {
sender.sendMessage("Not enough arguments!");
}
}
}
}
在上面的示例中,如果用户键入 /test add two hello,我希望将最后两个参数(两个和 hello)发送到另一个类中的方法(在此示例中,addToFile(String a, String b) 在类 YamlClass 中)其中 args[1] 和 args[2] 将用于将字符串放入这样的文件中:
test:
one:
two:
- hello
three:
如果用户随后运行/test add three goodbye,文件将如下所示:
test:
one:
two:
- hello
three:
- goodbye
如果用户随后执行/test add three test,它会将“测试”添加到该部分,而不会替换之前添加的“再见”。
谁能给我一些关于如何去做的帮助或提示?
谢谢!
[编辑] 我昨晚想通了。就文件和 YamlCinfiguration 而言,我实际上做的一切都是正确的,我的 CommandExecutor 有问题,但我修复了它。感谢您的回复!
【问题讨论】: