I'm trying to load from an existing file from the asset folder, rather than SD card as my code below does:
MapDataStore mapDataStore = new MapFile(
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "berlin.map"));
I am unsure how to do this in Android and am looking for help.
If I remember correctly, you can't access a .map file in the assets folder. You have to copy it from there to the SD card.
private void provideMapData() {
String sourceFile = res.getString(R.array.mapsource);
String destinationFile = res.getString(R.array.mapdestination);
String pathPrefix = activity.getExternalFilesDir(null) + "/";
File directory = new File(pathPrefix);
if (directory.exists() | directory.mkdirs()) {
AssetManager assetManager = activity.getAssets();
InputStream inputStream;
OutputStream outputStream;
File file = new File(pathPrefix + destinationFile);
if (!file.exists()) {
try {
inputStream = assetManager.open(sourceFile);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[8192];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException iOE) {
Log.e("Error: ", "provideMapData()");
}
}
}
}
Then I load the MapDataStore like this:
MapDataStore mapDataStore = new MapFile(new File(activity.getExternalFilesDir(null) + "/" + destinationFile));
According to this, you should put this into your manifest file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
It will save you from explicitly asking the user to grant WRITE_EXTERNAL_STORAGE permission.
Related
I am downloading zip file from server to internal storage. And after downloading I want to unzip that file in internal storage itself. My file is downloaded to internal storage and I can see that but while unzip I am not able to read it. Below is my unzipfile() method. Can anyone tell where I am going wrong?
public void unzipfile()
{
try {
Log.d("unzipiing","unzipping");
ContextWrapper cw = new ContextWrapper(context);
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name_, Context.MODE_PRIVATE);
File mypath=new File(directory,"dwnld");
FileOutputStream fout = new FileOutputStream(mypath);
File yourFile = new File(directory,"dwnld.zip");
Log.d("unzipiing","filepath -" + yourFile.getPath());
FileInputStream fin = new FileInputStream(yourFile.getPath());
ZipInputStream zin = new ZipInputStream(fin);
Log.d("unzipiing","zin size -" + zin.available());
// zin.available() give -1 in console log
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);
byte b[] = new byte[zin.available()];
int n;
Log.d("unzip","n - " + in.read(b,0,1024));
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
Log.d("unzip byte"," - " + n);
}
out.flush();
out.close();
in.close();
fin.close();
zin.close();
}
catch (Exception e){
}
}
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
use this method for unzip
public void unzip(String _zipFile, String _targetLocation) {
//create target location folder if not exist
dirChecker(_targetLocatioan);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
check the path
public void dirChecker(String filepath)
{
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
}
I'm trying to write some code to stream a file from a server directly into the Android external storage system.
private void streamPDFFileToStorage() {
try {
String downloadURL = pdfInfo.getFileServerURL();
URL url = new URL(downloadURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream pdfFileInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
File pdfFile = preparePDFFilePath();
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
byte[] buffer = new byte[8012];
int bytesRead;
while ((bytesRead = pdfFileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private File preparePDFFilePath() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
return file;
/*
String pdfFileDirectoryPath = ApplicationDefaults.sharedInstance().getFileStorageLocation() + pdfInfo.getCategoryID();
File pdfFileDirectory = new File(pdfFileDirectoryPath);
pdfFileDirectory.mkdirs();
return pdfFileDirectoryPath + "/ikevin" + ".pdf";
*/
}
It keeps getting an exception of "No such file or directory" at
"OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));"
How do I write the file? What's wrong with my code? (Also, I am not using Context.getExternalFilesDir() because I don't know how to get the Context from my controller logic code. Can anyone advise if this is the better solution?)
new File is returning you a file object and not the file. You might wana create a file before opening a stream to it. Try this
File pdfFile = preparePDFFilePath();
boolean isCreated = pdfFile.createNewFile();
if(isCreated){
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
}
This code works:
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/dir1");
dir.mkdirs();
I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}
Can anyone kind enough show me how to copy files from my app assets folder to /system folder? I know how to get root access and all. For example: I want to copy file from "/assets/lib/libs.so" and check if this file already exist, if it does replace it to new "/system/lib/libs.so".
try this:
try {
File from = new File( "/assets/lib/libs.so" );
File to = new File( "/system/lib/libs.so" );
if( from.exists() && to.exists() ) {
FileInputStream is = new FileInputStream( from );
FileOutputStream os = new FileOutputStream( to );
FileChannel src = is.getChannel();
FileChannel dst = os.getChannel();
dst.transferFrom( src, 0, src.size() );
src.close();
dst.close();
is.close();
os.close();
}
} catch( Exception e ) {
}
This will check if your file exists, delete it and then copy everthing that is in assets.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File exists = new File("/system/lib/libs.so");
if(exists.exists()){
exists.delete();
CopyAssets();
}else{
CopyAssets();
}
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream("/system/lib/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Edit:
Declare this permission in your manifest file for filesystems.
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
How Do I Copy songs or image to my SD Card. i.e download image and save to sd card in android.
Thanks , shiv
Try this code:
File src = new File(Your_current_file);
File dest = new File(destination_place);
public void copyFile(File src, File dest) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
Make sure to Give the permission for External Storage if you need:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Hope this will helps you.
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
Dont forget to add permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private final String PATH = "/data/data/com.whatever.whatever/"; //put the downloaded file here
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL("http://yoursite.com/" + imageURL); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
And don't forget to add the following permissions:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = //Input stream of the file downloaded;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}