2017-07-16 120 views
0

我試圖創建一個系統,在第一次登錄時爲每個玩家創建一個文件。在這個文件中,每個玩家都存儲了所有的數據。在Bukkit API中創建PlayerData文件

當玩家第一次加入時,插件應該在文件夾內爲他們創建一個文件,然後用GUI提示他們。

@EventHandler 
public void onPlayerJoinForFirstTime(PlayerJoinEvent e) { 
    File f = new File(Main.plugin.getDataFolder()+File.separator+"CrimsonCore",e.getPlayer().getUniqueId().toString()+".yml"); 
    FileConfiguration playerdata = YamlConfiguration.loadConfiguration(f); 
    if(!(f.exists())) { 
     try { 
      playerdata.createSection("info"); 
      playerdata.set("info.name",e.getPlayer().getName()); 

      playerdata.createSection("general"); 
      playerdata.set("general.element","none"); 

      playerdata.save(f); 
      f.createNewFile(); 
      System.out.println("Created data file for "+e.getPlayer().getName()); 
     }catch(IOException exception) { 
      exception.printStackTrace(); 
     } 
     Main.chooseElement.setItem(2,Main.createItem(new ItemStack(Material.BLAZE_POWDER), 
       ""+ChatColor.GOLD+"Choose Fire!", 
       new String[]{ChatColor.RED+"Infinite Strength II",""+ChatColor.GRAY+ChatColor.ITALIC+"Note: You can change this with /element."})); 
     Main.chooseElement.setItem(6,Main.createItem(new ItemStack(Material.ICE), 
       ""+ChatColor.AQUA+"Choose Ice!", 
       new String[]{ChatColor.DARK_AQUA+"Infinite Speed II",""+ChatColor.GRAY+ChatColor.ITALIC+"Note: You can change this with /element."})); 
     e.getPlayer().openInventory(Main.chooseElement); 
    } 
} 

順便說一下,Main.plugin只是指插件的一個實例。我在Main類(擴展JavaPlugin的類)中有一行,它只是「public static Main plugin;」

但是,這些事情都沒有發生。我在if語句之前首先嚐試了一個p.sendMessage(),然後在if語句中,它在加入時不發送。我知道該文件不存在,即使我之前已加入服務器,因爲我搜索了FTP並找不到它。那麼,爲什麼if語句不是真實且持續的?

注意:我不想將每個玩家的數據存儲在一個大的配置文件中,我只想知道爲什麼它不能正常工作。

+0

你應該使用一個數據庫,而不是yaml文件 – Kerooker

+0

你可能在第4行失敗。如果該文件不存在,你將無法加載Yaml。 – Kerooker

+0

刪除'f.createNewFile();',因爲您已經調用FileConfiguration#save。第二次電話會覆蓋第一個電話 – Squiddie

回答

0

問題在於文件實際存在。 Kerooker和Squiddie都是正確的。你正在嘗試使用一個你不知道存在的文件,你基本上將文件保存兩次。我會用它來繞過這個問題的方法是使用File.createNewFile方法在if語句,像這樣:

if(f.createNewFile()){ 
    //A new file was created 
    //Do what ever you would do to the new file. Like creating the FileConfiguration object here 
}else{ 
    //The file already exists 
    //Do what ever you would do with an already existing file 
} 

這您創建FileConfiguration對象之前阻止你有問題,與沒有被創建的文件確保在寫入任何內容之前已經創建了對象,因此不會覆蓋數據。