I was able to upload an expandable file and download it
on my app from google play. Following the o[fficial tutorial][1]
It saved the obb file to /Android/Obb/main.2.myappname.obb
I assumed this obb file would be extracted on assets or raw folder or
something similiar. The obb file was renamed after I zipped about 20 .mp3
files. They are named like so: 1.mp3, 2.mp3 etc.
Is it possible to extract the obb file if not how will I be able to
access the invididual mp3 files, the way I am able to access them from
assets or raw folder. Let's say I want to access 1.mp3 which is present
on the .zip archive that was renamed to main.2.myappname.obb
Thank you.
I'm surprised that no one has chimed in here. You can use the StorageManager to mountObb(), unmountObb(), getMountedObbPath(), and isObbMounted(). After mounting an Obb and calling getMOuntedObbPath, you can use the path returned to do normal reads from it. It acts as a virtual drive. You just cannot write back to it.
Here's the link to the documentation: https://developer.android.com/reference/android/os/storage/StorageManager.html
You can read from the OBB directly via an InputStream using the APK Expansion Zip Library. Documentation:
https://developer.android.com/google/play/expansion-files?hl=ko#ZipLib
Sample code:
try {
String obbFilePath = mContext.getObbDir() + "/" + "main.{package_name}.{version_code}.obb";
ZipResourceFile expansionFile = new ZipResourceFile(obbFilePath);
InputStream inputStream = mExpansionFile.getInputStream("1.mp3");
} catch (Exception e) {
Log.d(TAG, "Exception loading obb: " + e);
}
In place of the last line, since you are streaming a MP3, using MediaPlayer is a better idea.
Related
so i know there are alot of questions about creating a text file in android but i cant find any answers to my specific questions.
So the device I'm using is not an phone or a tablet, its a controller with android on it so the file directory is getting me confused. i want to create a new file either on the sd card or the device itself (it doesn't really matter as long as i can see it). firstly, the device doesn't have google docs or sheets or anything like that, will i need to install one of these apps on it for it to be able to read .txt files? or does android have some sort of internal software to do that?
Secondly, i've found alot of code on how to create a new file but most of it seems to gloss over how to get file directory, is there a specific way i can get the file directory?
This is what im using so far and im not getting any errors but its also not creating any files (or at-least none that i can see).
public void WriteToText(){
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
1, I think all devices have Html viewer which can view the text files. If you click a text file in a file manager app, it should prompt you with a list of apps that can view the text file.
2, Your code is correct, but it creates a file in the app's private file directory, which is not visible to all other apps, including file manager apps. This is because of Android security policy to prevent any app to steal information from other apps.
If you want to write a file which is visible to other apps like file manager, there are 2 ways.
in old api level (<29?) you can get the get external storage with
Environment.getExternalStorageDirectory()
you will need to request permission for it.
save the file in your app's private directory like what you have done, then create a chooser to share it out with correct mime type (txt/plain?), it will prompt you to select app that can view this mime type like what file manager does.
I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.
I am trying to output numeric values one at a time from an Android application I'm writing, but I'm having a lot of trouble figuring out what's going on. Tried looking for answers, but only confused further. This strikes me as something that should be relatively straightforward, so I feel pretty dumb for being so confused by it.
String directory = Environment.getExternalStorageDirectory().getAbsolutePath();
When I log the directory I get a path "/storage/emulated/0" Where is that? Is that different from what I would get if I wasn't debugging?
Then I have:
String fileName = directory + "/Android/data/com.sample.app/files/test.txt"
File myFile = new File(fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(myFile);
String text = "Test text\n";
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
I tried using the Windows Explorer to figure out where stuff is saving and/or is supposed to be saved but I don't see it. This is code based on the information in this link: http://developer.android.com/guide/topics/data/data-storage.html, but I really don't understand where the "/storage/emulated/0" comes from and how I either access that location or get rid of it.
EDIT: Right now I just want to save all the numbers so I can check what is coming out. The numbers are recorded from the audio input.
EDIT: Using the ASTRO File app on my phone revealed the files
Didn't need the "/Android/data/com.sample.app/files/" part, don't know how to use that.
Path wrong?
/storage/emulated/0 is a path at your filesystem which represents the external storage. At earlier versions of Android we often had /mnt/sdcard/ or something similiar, but many devices today don't have a sdcard but emulate an external storage anyway.
To view the files at your Android filesystem I'd recommend to use an App like Astro File Manager. Just take a look if your file has been written.
One possible mistake could be, that you you are missing a File.separator between your directory and the local path.
String fileName = directory + File.seperator + "Android/data/com.sample.app/file/test.txt"
Directory created?
You should also make sure, that the directory exists by calling myDir.mkDirs();, where myDir is the complete path without the filename.
To create the directory you can use the following code
directory = directory + "/Android/data/com.sample.app/file/test.txt"
new File(directory).mkDirs();
Uses-Permission in Manifest?
Last error source could be, that you might miss the external storage permission, you need a
You also need to make sure, that you require the permission for writing to the external storage. Take a look for <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in your Android Manifest file.
I've followed the instructions in
this thread, using the code in there I've been able to add a file to a zip file without uncompressing and recompresing it, but i have a problem, let me show you my code:
private void saveFileIntoProjectArchive(Path pathOfFile) {
this.projectArchiveFile.setWritable(true, false);
Path zipFilePath = Paths.get(this.projectArchiveFile.getAbsolutePath()),
pathToSaveInsideZIP = null;
FileSystem fs;
try {
fs = FileSystems.newFileSystem(zipFilePath, null);
pathToSaveInsideZIP = fs.getPath(pathOfFile.toString().substring((int) this.transactionalProjectFolder.getAbsolutePath().length()));
System.out.println("Coping from:\n\t"+pathOfFile+"\nto\n\t"+pathToSaveInsideZIP);
Files.copy(pathOfFile, pathToSaveInsideZIP, REPLACE_EXISTING);
System.out.println("Done!!!");
fs.close();
} catch (java.nio.file.NoSuchFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
projectArchiveFile.setWritable(false, false);
}
what I'm trying to do is, i have many files for a same project, that project is an archive (ZIP, which in the code is referenced by a java.io.File called projectArchiveFile, an instance variable of my class) containing all of those files, when I want to work with certain file inside my archive, i uncompress only that file into a folder which has an structure identical to the one inside my archive (ZIP, projectArchiveFile), the reference to that folder is a java.io.File called transactionalProjectFolder, also an instance variable of my class. But is giving me this error:
coping from:
C:\Dir1\Dir2\Dir3\Begin of Archive stucure\Another folder replica of the archive structure\An Excel File.xlsm
to
\Begin of Archive stucure\Another folder replica of the archive structure\An Excel File.xlsm
java.nio.file.NoSuchFileException: Begin of Archive stucure\Another folder replica of the archive structure\ at com.sun.nio.zipfs.ZipFileSystem.checkParents(ZipFileSystem.java:846)
at com.sun.nio.zipfs.ZipFileSystem.newOutputStream(ZipFileSystem.java:515)
at com.sun.nio.zipfs.ZipPath.newOutputStream(ZipPath.java:783)
at com.sun.nio.zipfs.ZipFileSystemProvider.newOutputStream(ZipFileSystemProvider.java:276)
at java.nio.file.Files.newOutputStream(Files.java:170)
at java.nio.file.Files.copy(Files.java:2826)
at java.nio.file.CopyMoveHelper.copyToForeignTarget(CopyMoveHelper.java:126)
at java.nio.file.Files.copy(Files.java:1222)
the rest of the stack trace are my classes.
I've been able to write in the root of the archive(zip), but whenever i try to write inside of a folder which is inside of the archive (zip) it fails, as you can notice in the stack trace, it says that java.nio.file.NoSuchFileException: Begin of Archive stucure\Another folder replica of the archive structure\ and it stops right before the name if the file which I'm trying to copy, I'M ENTIRELY SURE that the path inside the zip exist and it is appropriately spelled it just do not want to write (I've trying with Files.copy and Files.move) the file inside the archive, I've been stuck in this for a month, I don't know what else to do, any suggestion will be appreciated!!!
thanks in advance! :)...
Even tho you are sure the path exists, I would for troubleshooting add below row and see what directory structure it creates.
The error indicate the directories are missing inside the zip. Could be you are using some weird folder names not supported by zip etc..
System.out.println("Coping from:\n\t"+pathOfFile+"\nto\n\t"+pathToSaveInsideZIP);
Files.createDirectories(pathToSaveInsideZIP); // add this row
Files.copy(pathOfFile, pathToSaveInsideZIP, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Done!!!");
I'll recommend you to try out the TrueZip it's easy to use, it exposes any archive into a virtual file system, then you can append, delete or edit any file inside the archive easily.
I am trying to learn how to use the Simple XML Framework as detailed in this thread : Best practices for parsing XML.
I am using the following code :
public class SimpleXMLParserActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
Serializer serializer = new Persister();
Example example = new Example("Example message", 123);
File result = new File("example.xml");
try {
Log.d("Start", "Starting Serializer");
serializer.write(example, result);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Self", "Error");
e.printStackTrace();
}
}
}
I am having a problem understanding the line
File result = new File("example.xml");
1) Does this line create a new file in my app called example.xml ? If so where is this file located.
2) Or does this line look for an existing file called example.xml and then add to it ? If so where should the example.xml file be placed in my app bundle so that it can be found. I do notice at the moment I am getting an error message :
java.io.FileNotFoundException: /example.xml (Read-only file system)
Thank you.
File result = new File("example.xml")
This line will just store the filename "example.xml" in a new File object. There is no check if that file actually exists and it does not try to create it either.
A file without specifying an absolute path (starting with / like new File("/sdcard/example.xml")) is considered to be in the current working directory which I guess is / for Android apps (-> /example.xml (Read-only file system))
I guess serializer.write(example, result); tries to create the actual file for your but fails since you can't write to '/'.
You have to specify a path for that file. There are several places you can store files, e.g.
Context#getFilesDir() will give you a place in your app's home directory (/data/data/your.package/files/) where only you can read / write - without extra permission.
Environment#getExternalStorageDirectory() will give you the general primary storage thing (might be /sdcard/ - but that's very different for devices). To write here you'll need the WRITE_EXTERNAL_STORAGE permission.
there are more places available in Environment that are more specialized. E.g. for media files, downloads, caching, etc.
there is also Context#getExternalFilesDir() for app private (big) files you want to store on the external storage (something like /sdcard/Android/data/your.package/)
to fix your code you could do
File result = new File(Environment.getExternalStorageDirectory(), "example.xml");
Edit: either use the provided mechanisms to get an existing directory (preferred but you are limited to the folders you are supposed to use):
// via File - /data/data/your.package/app_assets/example.xml
File outputFile = new File(getDir("assets", Context.MODE_PRIVATE), "example.xml");
serializer.write(outputFile, result);
// via FileOutputStream - /data/data/your.package/files/example.xml
FileOutputStream outputStream = openFileOutput("example.xml", Context.MODE_PRIVATE);
serializer.write(outputStream, result);
or you may need to create the directories yourself (hackish way to get your app dir but it should work):
File outputFile = new File(new File(getFilesDir().getParentFile(), "assets"), "example.xml");
outputFile.mkdirs();
serializer.write(outputFile, result);
Try to avoid specifying full paths like "/data/data/com.simpletest.test/assets/example.xml" since they might be different on other devices / Android versions. Even the / is not guaranteed to be /. It's safer to use File.separatorChar instead if you have to.
2 solutions to do it cleanly :
use openFileOutput to write a private file in the application private directory (which could be located in the internal memory or the external storage if the app was moved there). See here for a snippet
or use the File constructor to create the File anywhere your app has write access. This is if you want to store the file on the SDCard for example. Instantiating a file doesn't create it on the file system, unless you start writiung to it (with FileOutputStream for example)
I'd recommend approach 1, it's better for users because these files get erased when your app is uninstalled. If the file is large, then using the External Storage is probably better.
What I read on the Android pages, I see it creates a file with that name:
File constructor
I think it writes it to the /data/data/packagname directory
edit: the 'packagename' was not shown in the tekst above. I put it between brackets. :s
Try saving to /sdcard/example.xml.