I have a html file in my asset directory and i have to load it as browser application using Intent.
Here is my code, but its not working:
startActivity (new Intent(Intent.ACTION_VIEW,
Uri.parse("file:///android_asset/Sample.htm")));
Could anyone help me?
Use loadUrl() method of WebView to load an html page
Sample Example
if faq.html is the html file present in assets folder then you can use
WebView html = (WebView) findViewById(R.id.webEulaView);
html.loadUrl("file:///android_asset/faq.html");
i had the same problem what i did was
copied the content of the assets to a database and then pulled it from the sdcard
here is the code to copy your assets to sdcard
the logic used is as follows the html pages are put in the zip file in assets folder
content is the name of the zip in assets folder
boolean succussFlag = false;
destination="";
destination=Environment.getExternalStorageDirectory()+"/";
File file = new File(destination);
if (!file.exists()){
file.mkdirs();
}
else
{
//file.delete();
//file.mkdir();
}
try
{
InputStream fileInput = context.getAssets().open("content.zip");
ZipInputStream inputStream = new ZipInputStream(fileInput);
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry())
{
String innerFileName = destination + entry.getName();
System.out.println("destination::::"+innerFileName);
// Log.v("inner file name 0",""+innerFileName);
File innerFile = new File(innerFileName);
if (innerFile.exists())
{
innerFile.delete();
}
// Check if it is a folder
if (entry.isDirectory())
{
// Its a folder, create that folder
innerFile.mkdirs();
}
else
{
// System.out.println(" ::::::::::::::INNER FILE COPYING :::: " + innerFile.toString());
FileOutputStream outputStream = new FileOutputStream(innerFileName);
final int BUFFER = 4096;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream,
BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1)
{
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
inputStream.closeEntry();
}
inputStream.close();
// System.out.println(" ::::::::::COPIED TO PRIVATE FOLDER :::: " );
succussFlag=true;
}
catch (IOException e)
{
// System.out.println("** EXCEPTION OCCURED WHILE COPYING***");
e.printStackTrace();
succussFlag=false;
}
return succussFlag;
after this you give following command
startActivity (new Intent(Intent.ACTION_VIEW,"file://"+ Environment.getExternalStorageDirectory()+"/content"+name_Html ;
);
Related
I'm writing app for android and I'm using caffe library. My problem is that on start I need to initialize caffe, which is done by passing two files (structures of network) to caffe.
Problem is that I don't know how to store extra files on device. I've added model file to assets, but I don't know how can I read it using file path. Can you tell me where to store these file that could be access using file path?
Thanks for any ideas.
This should do it. Just copy those files to data directory from asset folder. If you already have those files there just load them.
String toPath = "/data/data/" + getPackageName(); // Your application path
private static boolean copyAssetFolder(AssetManager assetManager,
String fromAssetPath, String toPath) {
try {
String[] files = assetManager.list(fromAssetPath);
new File(toPath).mkdirs();
boolean res = true;
for (String file : files)
if (file.contains("."))
res &= copyAsset(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
else
res &= copyAssetFolder(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
return res;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean copyAsset(AssetManager assetManager,
String fromAssetPath, String toPath) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(fromAssetPath);
new File(toPath).createNewFile();
out = new FileOutputStream(toPath);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
private static 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);
}
}
Put them into your project as assets, and then when the app starts, you can read them from the assets and copy them into the app's private storage area. You can find this directory using Context.getFilesDir().
From there, you'll be able to pass the files to Caffe.
Assets are packaged and access only using special methods, so i solved problem by access file and then copy it to new location which i passed to native method.
I am making an android webview application,there are a lot of files such as js/css/images must be downloaded from CDN to the app, because the network is not stable in our region and the size of the cached files is much bigger than the app itself, is there some way to build the apk file with the cache files stored automatically when the app runs at first few times.
Put your files and folders to assets. you'll find it in your project directory. When your application runs copy all assets contents to your SD card. then run your app :)
If you need any help about how to copy assets content to SD card let me know.
Copy Assets contents to SD card
Bellow code will copy all the contents of specified folder of your assets to your specified location of your SD card
CopyAssetContents.java
public class CopyAssetContents {
public static boolean copyAssetFolder(AssetManager assetManager,String fromAssetPath, String toPath) {
try {
String[] files = assetManager.list(fromAssetPath);
new File(toPath).mkdirs();
boolean res = true;
for (String file : files)
if (file.contains("."))
res &= copyAsset(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
else
res &= copyAssetFolder(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
return res;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean copyAsset(AssetManager assetManager,
String fromAssetPath, String toPath) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(fromAssetPath);
new File(toPath).createNewFile();
out = new FileOutputStream(toPath);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
private static 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);
}
}
}
For example you have all your contents in a folder named "CONTENTS" inside of your assets.and want to copy all of its content to root of your SD card.
call bellow method.
CopyAssetContents.copyAssetFolder(getAssets(), "CONTENTS", Environment.getExternalStorageDirectory().getAbsolutePath());
I have one requirement in my Android application. I need to download and save file in specific folder of SD card programmatically. I have developed source code, which is
String DownloadUrl = "http://myexample.com/android/";
String fileName = "myclock_db.db";
DownloadDatabase(DownloadUrl,fileName);
// and the method is
public void DownloadDatabase(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://myexample.com/android/");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
}
Now the issue is only empty file with filename myclock_db.db is saving in the path. but I need to download and save content of file in the specific folder. Tried several ways to get the file download, but I can't.
Your download URL is not a link to any file. It's a directory. Make sure its a file and exists. Also check your logcat window for error logs. One more suggestion, its always better to do a printStackTrace() in catch blocks instead of Logs. Its gives a more detailed view of the error.
Change this line:
URL url = new URL("http://myexample.com/android/");
to:
URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url
Next, in catch block, add this line:
e.printStackTrace();
Also in the directory path, it should be something like this:
File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
instead of
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
Next, make sure you have acquired permission for writing to external storage in Android manifest.
I'm trying to make an Android application that can open a docx file to read, edit and save it.
My idea is to extract all the xml file within the archive to a temp folder. In this folder we can edit the content of the docx in /word/document.xml. The problem is when I compress this temp folder to make a new docx file and replace the old file, inside the new docx archive the path is like /mnt/sdcard/temp/"all files xml go here" while the xml files should be in the first level.
Can anybody help me to go through this? here is the method to compress the temp directory
Note: dir2zip argument's value I use is /mnt/sdcard/temp/***.docx
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
//create a new File object based on the directory we
//have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
//loop through dirList, and zip the files
for(int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if(f.isDirectory())
{
//if the File object is a directory, call this
//function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
//loop again
continue;
}
//if we reached here, the File object f was not a directory
//create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
//create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
//place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
//now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
//close the Stream
fis.close();
}
}
catch(Exception e)
{
//handle exception
}
}
I have managed to fix it by myself. The problem is in this line:
File f = new File(zipDir, dirList[i]);
It should be
File f = new File(dirList[i]);
If the argument zipDir is included, the absolute path to the directory will be used in the archive!
I have now managed to get the original poster's code working on Mac and Windows by making the following two modifications:
1: add a ZipEntry for each directory: do not simply ignore it
2: remove the directory name from the ZipEntry name
Note: zipinfo is useful
This is a program that works for me:
import java.io.*;
import java.util.zip.*;
public class zipdoc
{
String savedDir = null;
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
if (savedDir == null)
savedDir = dir2zip;
// create a new File object based on the directory we
// have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if (f.isDirectory())
{
// if the File object is a directory, call this
// function again to add its content recursively
System.out.println("Adding dir: " + f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1) + "/");
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
String filePath = f.getPath();
zipDir(filePath, zos);
// loop again
continue;
}
else if (!f.getName().equals(".DS_Store"))
{
// if we reached here, the File object f was not a directory
// and it's not the MacOSX special .DS_Store
// create a FileInputStream on top of f
System.out.println("Adding file: " + f);
FileInputStream fis = new FileInputStream(f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1));
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
// now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
// close the Stream
fis.close();
}
}
}
catch(Exception e)
{
// handle exception
System.out.println(e);
}
}
public void zipit(String inDir, String outFile)
{
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(outFile)));
zos.setMethod(0);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(0);
zipDir(inDir, zos);
zos.finish();
zos.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main (String args[]) {
zipdoc z1 = new zipdoc();
// Check there are sufficient params if desired
// first param is directory to be 'zipped', second is resulting
// filename (??.docx)
// eg java zipdoc dir1 newDoc.docx
z1.zipit(args[0], args[1]);
System.out.println("Finished creating " + args[1]);
}
}
I am trying to create a folder and several subdirectory within it on the SD Card... I then want to transfer files that I have stored in /res/raw to that folder... I addition, I want this to only happen once, the first time the program is ever run. I realize that this is ridiculously open-ended, and that I am asking a lot... but any help would be greatly appreciated.
This will copy all files in the "clipart" subfolder of the .apk assets folder to the "clipart" subfolder of your app's folder on the SD card:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...
// in onCreate
File clipartdir = new File(basepath + "/clipart/");
if (!clipartdir.exists()) {
clipartdir.mkdirs();
copyClipart();
}
private void copyClipart() {
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(int i=0; i<files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + files[i]);
out = new FileOutputStream(basepath + "/clipart/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}
}
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);
}
}
I experienced a similar problem when using mkdirs(), however because running the command:
mkdir one/two
fails on Linux, then the method http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() subsequently fails too. I guess this means there is no way to use mkdirs on Android? My (probably rather hacky) work-around was to create each necessary directory separately:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
new File(extStorageDirectory + "/one/").mkdirs();
new File(extStorageDirectory + "/one/two/).mkdirs();