따..딱히 공부하려고 포스팅하는 건 아니니까..!
유니티 안드로이드 파일 입출력시 주의사항 본문
public void WriteStringToFile(Dictionary<string, JSONNode> dict, string filename)
{
string path = PathForDocumentsFile(filename + ".json");
FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(file);
// serialize
JSONNode serialize = new JSONClass();
foreach (KeyValuePair<string, JSONNode> data in dict)
{
serialize.Add(data.Key, data.Value);
}
string str = null;
str = serialize.ToString();
streamWriter.WriteLine(str);
streamWriter.Close();
file.Close();
}
public JSONNode ReadStringFromFileOnStorage(string filename)
{
string path = PathForDocumentsFile(filename + ".json");
FileStream file = new FileStream(path, FileMode.Open);
StreamReader streamReader = new StreamReader(file);
if (streamReader != null)
{
string str = null;
str = streamReader.ReadToEnd();
JSONNode node = JSON.Parse(str);
streamReader.Close();
file.Close();
return node;
}
Debug.Log("Stream Reader Error");
return null;
}
public JSONNode ReadStringFromFile(string filename)
{
TextAsset data = (TextAsset)Resources.Load(filename, typeof(TextAsset));
if (data.text != null)
{
string str = data.text;
JSONNode node = JSON.Parse(str);
return node;
}
Debug.Log("Read Error");
return null;
}
/*
* Application.persistentDataPath : /mnt/sdcard/Android/data/번들이름/files
* Application.persistentDataPath : /data/data/번들이름/files/
* Substring(int1, int2) : int1에서부터 int2까지의 문자열
* LastIndexOf(string) : 마지막 string문자의 인덱스를 리턴
*/
public string PathForDocumentsFile(string filename)
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
string path = Application.dataPath.Substring(0, Application.dataPath.Length - 5);
path = path.Substring(0, path.LastIndexOf('/'));
return Path.Combine(Path.Combine(path, "Documents"), filename);
}
else if (Application.platform == RuntimePlatform.Android)
{
string path = Application.persistentDataPath;
path = path.Substring(0, path.LastIndexOf('/'));
return Path.Combine(path, filename);
}
else
{
string path = Application.dataPath;
path = path.Substring(0, path.LastIndexOf('/'));
return Path.Combine(path, filename);
}
}
빌드할 때 미리 생성된 파일은 Resources 함수로 읽고
새로 생성한 파일은 Stream으로 저장하고 Stream으로 읽어준다
위 소스는 그것에 대한 내용이다
간단해보이지만 모르면 오랫동안 헤매게 되는 내용이다
'모바일' 카테고리의 다른 글
페이스북 연동시 invaild key hash라는 에러가 나올때 (1) | 2016.02.21 |
---|---|
모바일 애플리케이션 Data Path 정리 (0) | 2015.06.25 |