본문 바로가기

Programming/유니티

파일) Unity Resource폴더와 저장소의 바이너리파일 읽기 (re : 2019.05.07)


public BinaryReader PlayFileToBinary (string _fname) 
{
	TextAsset _textAsset = Resources.Load (_fname) as TextAsset;
	Stream _s;
    
    //if file not exist read from device storage
	if (_textAsset == null) {
		_s = GetBinaryFileStream (_fname);
	} else {
		_s = new MemoryStream (_textAsset.bytes);
	}
	BinaryReader br = new BinaryReader (_s, Encoding.Default);
	return br;
}

//get file from device storage
public Stream GetBinaryFileStream (string _fname) 
{
	string a_filePath = DeviceFilePath (_fname + ".txt");
	FileStream a_fstrem = new FileStream (a_filePath, FileMode.Open, FileAccess.Read);
	byte[] a_fileByte = null;
	a_fileByte = new byte[a_fstrem.Length];
	a_fstrem.Read (a_fileByte, 0, (int)a_fstrem.Length);
	Stream a_sw = new MemoryStream (a_fileByte);
	return a_sw;
}

public string DeviceFilePath (string _fname = null) 
{
	string _path = "";
	if (Application.platform == RuntimePlatform.Android) {
		_path = Application.persistentDataPath;
		_path = _path.Substring (0, _path.LastIndexOf ('/'));
	} else if (Application.platform == RuntimePlatform.IPhonePlayer) {
		_path = Application.persistentDataPath;
		_path = _path.Substring (0, _path.LastIndexOf ('/'));
		_path = _path + "/Documents";
	} else {
		_path = Application.dataPath;
		_path = _path.Substring (0, _path.LastIndexOf ('/'));
	}
	if (_fname == null) {
		return _path;
	}
	return _path + "/" + _fname; // Path.Combine (_path, _fname);
}

----

----


BinaryReader _br = PlayFileToBinary(filename);
_bodyInfo.VerSion_1 = _br.ReadByte ();
_bodyInfo.TracCount = _br.ReadInt32 ();
_bodyInfo.BeatPerMs = _br.ReadSingle ();
_bodyInfo.Bpm = _br.ReadInt32 ();
_bodyInfo.TotalTime = _br.ReadUInt32 ();