Aditya Patil
Aditya Patil

Reputation: 133

How do i copy a Json file from the Assets/Resources/ to the Internal storage of an Android device ( persistent data)? [Unity Android]

I want to copy a single json file from Unity's Assets/Resources/ directory to the internal persistent memory of Android device (INTERNAL STORAGE/Android/data/<packagename>/files/) only once at the start of the game. I looked up all over the internet, with solutions saying to use Streaming assets and UnityWebRequests or WWW class which is obsolete now. I tried everything for hours now. And did not find a exact solutions, but only got null references and directory not found.

I added my json file to the <UnityProject>/Assets/Resources/StreamingAssets/, but it doesn't seem to detect any streaming assets. I understand an apk is a zip file and so I can only read the contents of streaming assets, but my I can't find a solution to this.

Once I get my json from streaming asset, I can finally add it to Application.persistentDataPath.

UPDATE I had actually figured it out,

     public void LoadFromResources() {
 {mobilePath = "StreamingAssets/"; mobilePath = mobilePath + "stickerJson" + ".json";
 string newPath = mobilePath.Replace(".json", "");
 TextAsset ta = Resources.Load<TextAsset>(newPath);
 string json = ta.text; Debug.Log(json); System.IO.File.WriteAllText(Application.persistentDataPath + "/stickers.json", json);
 }
}

Upvotes: 1

Views: 1511

Answers (1)

Lotan
Lotan

Reputation: 4283

To copy a file you only need to have the information of the file and then create a new one in another place.

So if you got your json file into your Resources directory you can retreive like the documentation say:

//Load text from a JSON file (Assets/Resources/Text/jsonFile01.json)
var jsonTextFile = Resources.Load<TextAsset>("Text/jsonFile01");
//Then use JsonUtility.FromJson<T>() to deserialize jsonTextFile into an object

Then you only have to create your android file in your persistentDataPath as @Iggy says in the comments doing:

System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "file.txt"), jsonTextFile);

Note: Not really sure, but for other cases I think that StreamingAssets folder should be inside Assets, no inside Resources.

Upvotes: 2

Related Questions