22#include " NBTCompound.h"
33#include " File/ByteBuffer.h"
44#include " File/GzipByteReader.h"
5+ #include " File/MemoryByteReader.h"
56#include " File/WriteBuffer.h"
67#include " File/GzipByteWriter.h"
78#include " File/FileByteWriter.h"
1314using namespace std ;
1415
1516namespace NBT {
16- NBTCompound* NBTReader::LoadFromFile (const char * filePath) {
17+ NBTCompound* NBTReader::LoadFromFile (const char * filePath, NBTFileType* outType ) {
1718 ifstream ifs (filePath, ios::binary | ios::ate);
1819 if (!ifs)
1920 throw Exception::FileException (strerror (errno), filePath, errno);
@@ -25,13 +26,33 @@ namespace NBT {
2526 ifs.read ((char *)bytes, length);
2627 ifs.close ();
2728
28- return LoadFromData (bytes, length);
29+ return LoadFromData (bytes, length, outType );
2930 }
3031
31- NBTCompound* NBTReader::LoadFromData (Byte* data, uint length) {
32+ NBTCompound* NBTReader::LoadFromData (Byte* data, uint length, NBTFileType* outType) {
33+ if (length > 1 && data[0 ] == NbtCompound) {
34+ // Maybe the file is uncompressed - try to load it without gzip compression
35+ std::cout << " Try to load the nbt file without compression." << std::endl;
36+
37+ File::MemoryByteReader reader (data, length);
38+ File::ByteBuffer buffer (&reader);
39+
40+ try {
41+ NBTCompound* compound = LoadFromUncompressedStream (&buffer);
42+ if (outType != NULL )
43+ *outType = NbtUncompressed;
44+ return compound;
45+ } catch (const Exception::Exception& ex) {
46+ std::cout << " Loading without compression failed: " << ex.GetMessage ().c_str () << std::endl;
47+ }
48+ }
49+
3250 File::GzipByteReader reader (data, length);
3351 File::ByteBuffer buffer (&reader);
3452
53+ if (outType != NULL )
54+ *outType = NbtGzipCompressed;
55+
3556 return LoadFromUncompressedStream (&buffer);
3657 }
3758
@@ -68,4 +89,21 @@ namespace NBT {
6889 delete gzipWriter;
6990 }
7091
92+ void NBTReader::SaveToFileUncompressed (const char * filePath, NBTCompound* compound) {
93+ File::FileByteWriter* fileWriter = new File::FileByteWriter (std::string (filePath));
94+
95+ try {
96+ File::WriteBuffer buffer (fileWriter);
97+ buffer.WriteByte (NbtCompound);
98+ buffer.WriteString (" " );
99+
100+ compound->Write (&buffer);
101+ } catch (const Exception::Exception& ex) {
102+ delete fileWriter;
103+ throw ex;
104+ }
105+
106+ delete fileWriter;
107+ }
108+
71109}
0 commit comments