2

This is how i read my textfile in android.

#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
        WWW reader = new WWW(full_path);
        while (!reader.isDone){}

        json = reader.text;

        // PK Debug 2017.12.11
        Debug.Log(json);
 #endif

and this is how i read my textfile from pc.

#if UNITY_STANDALONE
        string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
        StreamReader reader = new StreamReader(full_path);
        json = reader.ReadToEnd().Trim();
        reader.Close();
#endif

Now my problem is that i don't know how to write the file on mobile cause i do it like this on the standalone

#if UNITY_STANDALONE
        StreamWriter writer = new StreamWriter(path, false);
        writer.WriteLine(json);
        writer.Close();
 #endif

Help anyone

UPDATED QUESTION

This This is the json file that it is in my streamingasset folder that i need to get

Community
  • 1
  • 1
NoobProgrammer
  • 488
  • 1
  • 8
  • 21
  • Not in a position to actually *verify*, but your standalone code should work on android. The way you are doing it on mobile is equivalent to reading a file from the Web and you can't write to the Web. – Draco18s no longer trusts SE Dec 14 '17 at 02:35
  • So there's no actual way of doing it on the WWW class? @Draco18s – NoobProgrammer Dec 14 '17 at 02:44
  • `StreamWriter writer = new StreamWriter(path, false); writer.WriteLine(json); writer.Close();` when i tried to use this on mobile my catch(Exception e) says `System.IO.DirectoryNotFoundException: Could not find a part of the path "/jar:file:/data/app/com.steet383.rh.google-1/base.apk!/assets/notice.json".` – NoobProgrammer Dec 14 '17 at 03:06
  • My mistake. I am away from a dev environment and can't check things. WWW is unlikely to allow you to write, but I dip not know what your alternatives are. – Draco18s no longer trusts SE Dec 14 '17 at 06:29
  • hmmm i've got nothing :( . I've been trying this for hours and i've seen a lot that they are using persistent data instead but the problem is i need to pass the url from aws server and getting it back . that's what my problem is. – NoobProgrammer Dec 14 '17 at 06:39

2 Answers2

5

Now my problem is that i don't know how to write the file on mobile cause I do it like this on the standalone

You can't save to this location. Application.streamingAssetsPath is read-only. It doesn't matter if it works on the Editor or not. It is read only and cannot be used to load data.

enter image description here

Reading data from the StreamingAssets:

IEnumerator loadStreamingAsset(string fileName)
{
    string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);

    string result;

    if (filePath.Contains("://") || filePath.Contains(":///"))
    {
        WWW www = new WWW(filePath);
        yield return www;
        result = www.text;
    }
    else
    {
        result = System.IO.File.ReadAllText(filePath);
    }

    Debug.Log("Loaded file: " + result);
}

Usage:

Let's load your "datacenter.json" file from your screenshot:

void Start()
{
    StartCoroutine(loadStreamingAsset("datacenter.json"));
}


Saving Data:

The path to save a data that works on all platform is Application.persistentDataPath. Make sure to create a folder inside that path before saving data to it. The StreamReader in your question can be used to read or write to this path.

Saving to the Application.persistentDataPath path:

Use File.WriteAllBytes

Reading from the Application.persistentDataPath path

Use File.ReadAllBytes.

See this post for a complete example of how to save data in Unity.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Ow sorry my bad. My eyes are getting blurry now I'm sorry. So by that sir can i still call my s3 server by doing that? cause in my standalone platform im calling my datacenter like this `https://********.amazonaws.com/pc_version/ph/check/serverList.json` and it will download the serverlist.json – NoobProgrammer Dec 14 '17 at 08:06
  • 1
    You do understand that by simply replacing your `full_path` value with `Application.persistentDataPath`, the read and write code in your question with `StreamWriter` will work? This is what programmer is trying to tell you. Remove the `UNITY_ANDROID` and `UNITY_STANDALONE`. You don't need those. Simply use `StreamWriter` with the path provided in this answer and your problem will be solved. `StreamWriter` works on Android too. – PassetCronUs Dec 14 '17 at 09:21
  • @PassetCronUs but the problem is the file is in my streamingassetpath? will it be affected? – NoobProgrammer Dec 15 '17 at 06:05
  • Something like that sir . On my StreamingAsset folder i have my json files – NoobProgrammer Dec 15 '17 at 06:11
  • [this is the json i need to get](https://imgur.com/a/2yV4G) @Programmer – NoobProgrammer Dec 15 '17 at 06:17
  • I tried changing the `Application.streamingAssetPath` with `Applicatoin.persistentDataPath` and it give's me this error on logcat @Programmer `java.net.MalformedURLException: Protocol not found: /pc_version/ph/check/serverList.json` – NoobProgrammer Dec 15 '17 at 06:23
  • Instead of disabling them sir can i just use an `#if` directives? – NoobProgrammer Dec 15 '17 at 06:37
  • Okay i'll comeback to here sir and let you know what happened – NoobProgrammer Dec 15 '17 at 06:41
  • sir last question before i go testing your code what's the difference of `while(www.isDone){}` and `yield return www` i know there's a difference between them – NoobProgrammer Dec 15 '17 at 06:53
  • I bet i couldn't yield return null in a void function . I'm using those WWW class in a `public void ` – NoobProgrammer Dec 15 '17 at 07:19
  • @Programmer it give me this error `java.net.MalformedURLException: Protocol not found: /pc_version/ph/check/serverList.json` – NoobProgrammer Dec 15 '17 at 07:40
  • 2
    BTW, this directory does appear to be Read Only on Android because it's packaged into a jar. However, it is writable on other platforms. The "Read Only" in the documentation refers to the variable, not the directory (as in you can't change the path). – House Nov 24 '19 at 23:09
0

This is the way I do it without the WWW class (works for Android an iOS), hope its useful

public void WriteDataToFile(string jsonString)
{

    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
    if (!File.Exists(filePath))
    {
        File.Create(filePath).Close();
        File.WriteAllText(filePath, jsonString);
    }
    else
    {
        File.WriteAllText(filePath, jsonString);
    }

}
Hristo
  • 1,805
  • 12
  • 21
  • will it work with WWW class sir because i have a json file that has my data center in it `dataCenter:{ https://********.amazonaws.com }` and im calling it like this on my standalone platform `serverListJsonURL = string.Format("{0}/pc_version/ph/check/serverList.json", DataCenter_BaseURL );` – NoobProgrammer Dec 14 '17 at 08:03
  • Yes it does work with a downloaded JSON string using the `WWW` class – Hristo Dec 14 '17 at 08:12
  • @NoobProgrammer just keep in mind its going to save the file where the application is installed on the device (for Android its in the root data folder, for Windows its in the AppData folder) – Hristo Dec 14 '17 at 08:14
  • hi sir . I'm a bit hard to convert it something like this `StreamWriter writer = new StreamWriter(path, false); writer.WriteLine(json); writer.Close();` could you help me out – NoobProgrammer Dec 14 '17 at 08:28
  • What exactly is the problem, I don't understand the question? – Hristo Dec 14 '17 at 08:38
  • The problem here sir is that i'm converting an .exe application in unity to apk now i successfully did that . The problem code above is that problem i need to convert the code from #IF UNITY_STANDALONE to #IF UNITY_ANDROID which is we know that streamreader doesn't perfectly work in android – NoobProgrammer Dec 14 '17 at 08:50
  • @NoobProgrammer Your initial question was not about a `StreamReader/Writer` but how to save file on an android. If you use my method, you could successfully save a file in Android (test it out with a hard-coded string to see if it works). – Hristo Dec 14 '17 at 09:22
  • To be honest sir i don't know how to implement my logic to your logic hmmm – NoobProgrammer Dec 14 '17 at 09:26
  • I want to do it like this i don't know if it is right. `public static bool SaveJson_mk2(string json, string path){ try{ #if UNITY_ANDROID if(!File.Exist(path)){ File.Create(path).Close(); File.WriteAllText(path, json); } }catch(){} }` now i dont know where to insert the WWW class – NoobProgrammer Dec 14 '17 at 09:30
  • @NoobProgrammer What happens when you execute the above code? – Hristo Dec 14 '17 at 09:42
  • i didn't try it yet because it is a big project and its taking time to build >. – NoobProgrammer Dec 14 '17 at 09:51