Версия Minecraft
1.7+
Здравствуйте. Добрый день. Помогите, пожалуйста.
Да, я знаю, что в классе TileEntity можно менять NBT-данные, но мне нужно это сделать в другом классе, например, в функции инициализации модификации. Я думаю, это действие делается через NBTTagCompound, можно ли его создать просто так? В самом классе замечено несколько функций, возможно, записи и чтения. Подскажите, пожалуйста, как просто так, на пустом месте, читать NBT? Можно ли его создать просто так строкой new NBTTagCompound?
С уважением, Вамиг Алиев.
 
Решение
Приветствую.
Если я правильно понял, то тебе нужно типа этого:
Java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;

public abstract class FileNBT {

    final File directory;
    final String name;

    public FileNBT(File directory, String name) {
        this.directory = directory;
        this.name = name;
    }

    public void loadData() {
        try {
            File file = new File(directory, name + ".nbt");
            if (file != null && file.exists()) {
                //System.out.println(file.toString());
                FileInputStream fileinputstream = new...

timaxa007

Модератор
5,831
409
672
Приветствую.
Если я правильно понял, то тебе нужно типа этого:
Java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;

public abstract class FileNBT {

    final File directory;
    final String name;

    public FileNBT(File directory, String name) {
        this.directory = directory;
        this.name = name;
    }

    public void loadData() {
        try {
            File file = new File(directory, name + ".nbt");
            if (file != null && file.exists()) {
                //System.out.println(file.toString());
                FileInputStream fileinputstream = new FileInputStream(file);
                NBTTagCompound nbttagcompound = CompressedStreamTools.readCompressed(fileinputstream);
                fileinputstream.close();
                readFromNBT(nbttagcompound);
            }
        } catch (Exception e) {e.printStackTrace();}
    }

    public void saveData() {
        try {
            File file = new File(directory, name + ".nbt");
            if (file.getParentFile() != null) file.getParentFile().mkdirs();
            if (file != null) {
                //System.out.println(file.toString());
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                writeToNBT(nbttagcompound);

                FileOutputStream fileoutputstream = new FileOutputStream(file);
                CompressedStreamTools.writeCompressed(nbttagcompound, fileoutputstream);
                fileoutputstream.close();
            }
        } catch (Exception e) {e.printStackTrace();}
    }

    public abstract void readFromNBT(NBTTagCompound nbt);

    public abstract void writeToNBT(NBTTagCompound nbt);

}
Java:
public class Clan extends FileNBT {

    public static final String TAG = "clan";
    public Clan() {
        super(getDir(), TAG);
    }
//В главном классе
    @Mod.EventHandler
    public void serverStarting(FMLServerStartingEvent event) {
        loadData();
    }

    @Mod.EventHandler
    public void serverStopping(FMLServerStoppingEvent event) {
        saveData();
    }
//Не в главном классе

    public static File getDir() {
        return new File(MinecraftServer.getServer().worldServers[0].getSaveHandler().getWorldDirectory(), "clan");
    }

    @Override
    public void readFromNBT(NBTTagCompound nbt) {
        if (nbt.hasKey("Groups", NBT.TAG_LIST)) {
            groups.clear();
            NBTTagList nbttaglist = nbt.getTagList("Groups", NBT.TAG_COMPOUND);
            for (int i = 0; i < nbttaglist.tagCount(); ++i) {
                NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
                ClanGroup clan_group = new ClanGroup(nbttagcompound1.getString("ClanName"));
                if (nbttagcompound1.hasKey("ClanDesk", NBT.TAG_STRING))
                    clan_group.setClanDescription(nbttagcompound1.getString("ClanDesk"));
                if (nbttagcompound1.hasKey("Access", NBT.TAG_BYTE)) {
                    for (Access access : Access.values()) {
                        if (access.ordinal() == nbttagcompound1.getByte("Access")) {
                            clan_group.setAccess(access);
                            break;
                        }
                    }
                }
                if (nbttagcompound1.hasKey("Commander", NBT.TAG_COMPOUND)) {
                    GameProfile game_prodile = NBTUtil.func_152459_a(nbttagcompound1.getCompoundTag("Commander"));
                    clan_group.setCommander(game_prodile);
                }
                if (nbttagcompound1.hasKey("DeputyCommander", NBT.TAG_COMPOUND)) {
                    GameProfile game_prodile = NBTUtil.func_152459_a(nbttagcompound1.getCompoundTag("DeputyCommander"));
                    clan_group.setDeputyCommander(game_prodile);
                }
                if (nbttagcompound1.hasKey("Members", NBT.TAG_LIST)) {
                    NBTTagList nbttaglist2 = nbttagcompound1.getTagList("Members", NBT.TAG_COMPOUND);
                    for (int i2 = 0; i2 < nbttaglist2.tagCount(); ++i2) {
                        NBTTagCompound nbttagcompound2 = nbttaglist2.getCompoundTagAt(i);
                        GameProfile game_prodile = NBTUtil.func_152459_a(nbttagcompound2);
                        clan_group.getMembers().add(game_prodile);
                    }
                }
                if (nbttagcompound1.hasKey("Symbol", NBT.TAG_COMPOUND))
                    clan_group.setSymbol(ItemStack.loadItemStackFromNBT(nbttagcompound1.getCompoundTag("Symbol")));
                clan_group.setPoints(nbttagcompound1.getInteger("Points"));
                groups.add(clan_group);
                //System.out.println(clan_group.getClanName());
            }
        }
    }

    @Override
    public void writeToNBT(NBTTagCompound nbt) {
        NBTTagList nbttaglist = new NBTTagList();
        if (groups != null && !groups.isEmpty())
            for (ClanGroup clan_group : groups) {
                NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                if (StringUtils.isNullOrEmpty(clan_group.getClanName())) continue;
                nbttagcompound1.setString("ClanName", clan_group.getClanName());
                if (!StringUtils.isNullOrEmpty(clan_group.getClanDescription()))
                    nbttagcompound1.setString("ClanDesk", clan_group.getClanDescription());
                nbttagcompound1.setByte("Access", (byte)clan_group.getAccess().ordinal());

                if (clan_group.getCommander() != null) {
                    NBTTagCompound nbttagcompound3 = new NBTTagCompound();
                    NBTUtil.func_152460_a(nbttagcompound3, clan_group.getCommander());
                    nbttagcompound1.setTag("Commander", nbttagcompound3);
                }
                if (clan_group.getDeputyCommander() != null) {
                    NBTTagCompound nbttagcompound4 = new NBTTagCompound();
                    NBTUtil.func_152460_a(nbttagcompound4, clan_group.getDeputyCommander());
                    nbttagcompound1.setTag("DeputyCommander", nbttagcompound4);
                }
                if (clan_group.getMembers() != null && !clan_group.getMembers().isEmpty()) {
                    NBTTagList nbttaglist2 = new NBTTagList();
                    for (GameProfile game_profile : clan_group.getMembers()) {
                        if (game_profile == null) continue;
                        NBTTagCompound nbttagcompound2 = new NBTTagCompound();
                        NBTUtil.func_152460_a(nbttagcompound2, game_profile);
                        nbttaglist2.appendTag(nbttagcompound2);
                    }
                    nbttagcompound1.setTag("Members", nbttaglist2);
                }
                if (clan_group.getSymbol() != null) {
                    NBTTagCompound nbttagcompound5 = new NBTTagCompound();
                    clan_group.getSymbol().writeToNBT(nbttagcompound5);
                    nbttagcompound1.setTag("Symbol", nbttagcompound5);
                }
                nbttagcompound1.setInteger("Points", clan_group.getPoints());
                nbttaglist.appendTag(nbttagcompound1);
            }
        nbt.setTag("Groups", nbttaglist);
    }

}
 

timaxa007

Модератор
5,831
409
672
Пожалуйста. Во вставке кода не записываються табы, они переделываются в пробелы. В eclipse если настроено на табуляци во форматировании кода, то выделяй весь код "Ctrl + A", затем "Ctrl + I".
Ctrl + A
Ctrl + I
Ctrl + Shift + O
Ctrl + S
 
Да, это мне сейчас AlexSocol и показал через TiemWiever, написав здесь сообщение, так что извиняюсь за это сообщение. Мы просто думали, что этот код может быть из Minecraft'а, и я обратил внимание на пробелы, а Alex на это и указал. Еще раз спасибо за помощь в нашей разработке!
 

timaxa007

Модератор
5,831
409
672
что этот код может быть из Minecraft'а
Этот код написал я, но чтения и записи я брал связанное с SaveDataWorld.
net.minecraft.world.storage.MapStorage методы loadData и saveData.
так что извиняюсь за это сообщение
Для меня ни чего страшного.
Еще раз спасибо за помощь
Пожалуйста.
 
2,505
81
397
Приветствую.
Если я правильно понял, то тебе нужно типа этого:
А кто будет закрывать стрим в случае эксепшена? Используй конструкцию try-with-resources, чтобы не думать об этом.
 
Сверху