我们正在使用Unity创建一个Android应用(游戏)。
为了处理Android,我们编写了一个Android库模块。
我们想手动将文本文件插入Android文件系统,而不是通过应用程序访问它,我们应该把文件放在哪里以及如何访问它?
我们试过了
File file = new File(context.getExternalFileDir(null), "fileToRead.txt");
System.out.println(file.toString());
而文件" fileToRead.txt"在sd_card / Android / data / com.ourapp.ourapp /
中没有成功。 (file.exists()返回false)。
编辑: 我们将这些添加到清单
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我也
答案 0 :(得分:3)
转到播放器设置,对于Android,将写入权限从“仅限内部”更改为外部(SDCard)< / strong>即可。然后,您可以使用Application.persistentDataPath
获取外部存储空间路径的位置。
string myPath = Application.persistentDataPath;
它将返回如下内容:
“/storage/sdcard0/Android/data/' + package-name + '/files'
;
然后,您可以对其进行操作以指向您的自定义文件目录,或者像这样使用它。
File file = new File(myPath, "fileToRead.txt");
System.out.println(file.toString());
编辑: 从 Unity网站中尝试这种简单的方法。它消除了对Java模块或代码的需求。
string getPath()
{
string path = "";
#if UNITY_ANDROID && !UNITY_EDITOR
try {
IntPtr obj_context = AndroidJNI.FindClass("android/content/ContextWrapper");
IntPtr method_getFilesDir = AndroidJNIHelper.GetMethodID(obj_context, "getFilesDir", "()Ljava/io/File;");
using (AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (AndroidJavaObject obj_Activity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) {
IntPtr file = AndroidJNI.CallObjectMethod(obj_Activity.GetRawObject(), method_getFilesDir, new jvalue[0]);
IntPtr obj_file = AndroidJNI.FindClass("java/io/File");
IntPtr method_getAbsolutePath = AndroidJNIHelper.GetMethodID(obj_file, "getAbsolutePath", "()Ljava/lang/String;");
path = AndroidJNI.CallStringMethod(file, method_getAbsolutePath, new jvalue[0]);
if(path != null) {
Debug.Log("Got internal path: " + path);
}
else {
Debug.Log("Using fallback path");
path = "/data/data/*** YOUR PACKAGE NAME ***/files";
}
}
}
}
catch(Exception e) {
Debug.Log(e.ToString());
}
#else
path = Application.persistentDataPath;
#endif
return path;
}
http://answers.unity3d.com/questions/283823/how-can-you-save-both-internally-and-externally.html
答案 1 :(得分:0)
File file = new File(context.getExternalFilesDir(null), "fileToRead.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(file.toString());
您还必须为清单添加权限:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
WRITE_EXTERNAL_STORAGE
已包含READ_EXTERNAL_STORAGE
。因此,如果您添加了写作权限,您也可以阅读。因此,您可以删除READ_EXTERNAL_STORAGE
权限。