I have a problem with Android and Unity 3D. I have a file read code. When I put my code on the computer, it works. However, my code does not work on Android (Mobile). How can I solve this problem? Thank you.
FileInfo theSourceFile = new FileInfo(filename);
if (System.IO.File.Exists(fname))
{
StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(string);
}
EDIT updated code
string filename = "file.txt";
FileInfo theSourceFile = new FileInfo(filename);
filename = Application.persistentDataPath + "/"+filename;
System.IO.File.WriteAllText(filename,"Test");
if (System.IO.File.Exists(filename))
{
StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(string);
}
You need to change your build settings for android Device.
Change Configuration >> write access to external (sd card).
if not, your app is pointing to internal path and you need root permission in your android device.
You must use Application.persistentDataPath on Android to be able to read anything.
Change that to string filename = Application.persistentDataPath + "/file.txt"; and your code should work fine.
Bear in mind that before the read function can work, you must write to the directory first. So file.txt must exist in Application.persistentDataPath first.
For example
string filename = Application.persistentDataPath + "/file.txt";
System.IO.File.WriteAllText(filename,"Test");
EDIT:
You new code is still not working because you had FileInfo theSourceFile = new FileInfo(filename); before filename = Application.persistentDataPath + "/"+filename;. This means that the file name is still not valid. Pay attention the order your script execute. After switching it, it worked on my Android. Below is the whole code.
string filename = "file.txt";
filename = Application.persistentDataPath + "/" + filename;
System.IO.FileInfo theSourceFile = new System.IO.FileInfo(filename);
System.IO.File.WriteAllText(filename, "Test");
if (System.IO.File.Exists(filename))
{
System.IO.StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(text);
}
Related
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.
I am using this code, but I am not able to access the expansion file content, i want to show gif image from expansion file, how can i do?
String packageName = getPackageName();
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + "/Android/obb/" + packageName);
try {
if (expPath.exists()) {
String strMainPath = expPath
+ File.separator
+ "main."
+ getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode + "."
+ packageName + ".obb";
File f = new File(strMainPath);
if (f.exists()) {
Log.e("Path ", "=====>Exists");
} else {
Log.e("Path ", "=====> Not Exists");
}
ZipResourceFile zip = new ZipResourceFile(strMainPath);
InputStream iStream = zip.getInputStream("stage1_popup.gif");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeStream(iStream, null, option);
Glide.with(SampleDownloaderActivity.this).load(bitmap).into(image);
}
} catch (Exception e) {
}
http://prntscr.com/kp25qz
The Play APK expansions files library is completely open source, and you can see the sourcecode for ZipResourceFile here.
It looks like stage1_popup.gif is not in your obb file. To investigate it, why not use adb pull to get the file off your device and see what it actually contains. Or download the source code and attach to your IDE so you can step into the getInputStream() call and see where it is going wrong.
As mentioned in this answer, ZipResourceFile isn't able to deal with too much little files and neither is ZipFile. So try to divide your files in more directories.
Also, it's quite possible that there isn't any file with the name, stage1_popup.gif.
Alternatively, you can get all Entries via zipResourceFile.getAllEntries() and findout if the file exists.
I am using tesseract ocr in my app. In order to use tesseract i need to use several language files that are located at a directory called - 'tessdata'.
This is my method code:
public String detectText(Bitmap bitmap) {
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";
tessBaseAPI.setDebug(true);
tessBaseAPI.init(DATA_PATH, "eng"); //Init the Tess with the trained data file, with english language
tessBaseAPI.setImage(bitmap);
String text = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
return text;
}
I've used many variations of:
String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";
and every time the app fails with "path not found" exception.
I need a good way to put this directory in the android phone and get the path of it regardless of which phone it is. Right now the 'tessdata' directory can be found at the app root directory.
How can i do that?
Don't include "/tessdata/" in your DATA_PATH variable--just leave that part off, but be sure that subfolder exists within the directory specified by DATA_PATH.
From sourcecode TessBaseAPI#init
public boolean init(String datapath, String language) {
...
if (!datapath.endsWith(File.separator))
datapath += File.separator;
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory())
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
That means
the tessdata-subdirectory must exist.
init gets the parent-folder of "tessdata"
You can create it like this:
File dataPath = Environment.getDataDirectory();
// or any other dir where you app has file write permissions
File tessSubDir = new File(dataPath,"tessdata");
tessSubDir.mkdirs(); // create if it does not exist
tessBaseAPI.init(dataPath.getAbsolutePath(), "eng");
i can read and write file with this method for storing game progres.
filePath = Application.dataPath + "/";
filenam= "SavedGame";
extension = ".txt";
Lettura ----------------
var FRead = new File.OpenText(filePath + fileNam + extension);
for (var i : int= 0; i<N; i++) {
FRead.ReadLine();
}
Scrittura--------------------
var FWrite: StreamWriter = new StreamWriter(filePath + filenam + extension);
FWrite.WriteLine("AAAA");
A run time in the Unity editor all work perfectly.
But in Android device Application.dataPath seems dont work.
I tryed Application.persistentDataPath that work fine but in (Read Only),but i need place the SavedGame.txt manually in the patch.
I tried a fantomatic "jar:file://" + Application.dataPath + "!/assets/"; but dont work.
Note when i build the project in apk packege semms dont appear my SavedGame.txt,that
in the editor is in UnityProject\Assets .
Come posso risalire al percorso giusto del mio SavedGame.txt, posizionato in ad esempio in UnityProject\Assets nei device?
How i cand do this in a correct way read and write SavedGame.txt in android device?
On android you might not have direct write access to the dataPath of the project.
Try using Application.persistentDataPath instead. This is where save files are intended to be stored.
Change:
filePath = Application.dataPath + "/";
to
filePath = Application.persistentDataPath + "\\";
What i want to do is very simple :
String dataDir = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).applicationInfo.dataDir;
Log.e(TAG , "dataDir = " + dataDir);
File tmpFile = new File(dataDir + "/raw/ocr.jpg");
But i got a file not found exception
i NEED an object file as after i do
photoUriString = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), tmpFile.getAbsolutePath(), null, null);
(because i want to share the picture on google+, see How to share image in google Plus through an android app?)
So please don't tell me about a reader, a bufferedReader, etc ...
Thanks
InputStream is = getResources().openRawResource(R.raw.ocr.jpg));
you have to get the InputStream through openRawResource, then you can manage it as you need