I am making an app which stores its SQLite Database backup on GDrive. I succeeded in signing in and uploading the file in the drive but failed to restore it. Following is the code.
I use SQLiteDatabase to store the fileID so that when it is required while updating and restoring, it can be used. I am looking for a method which will make use of FileID to restore.
Error occurs at file.getDownloadUrl() and file.getContent().
class DriveClassHelper
{
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private static Drive mDriveService;
private String FileID = null;
private static String filePath = "/data/data/com.example.gdrivebackup/databases/Data.db";
DriveClassHelper(Drive mDriveService)
{
DriveClassHelper.mDriveService = mDriveService;
}
// ---------------------------------- TO BackUp on Drive -------------------------------------------
public Task<String> createFile()
{
return Tasks.call(mExecutor, () ->
{
File fileMetaData = new File();
fileMetaData.setName("Backup");
java.io.File file = new java.io.File(filePath);
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("application/x-sqlite-3");
FileContent mediaContent = new FileContent(mimeType, file);
File myFile = null;
FileID = getFileIDFromDatabase();
try {
if (FileID != null) {
Log.i("CALLED : ", FileID);
//mDriveService.files().delete().execute();
myFile = mDriveService.files().update(FileID, fileMetaData, mediaContent).execute();
} else {
myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
MainActivity.demoSQLite.insertData(myFile.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
if (myFile == null) {
throw new IOException("Null Result when requesting file creation");
}
Log.i("ID:", myFile.getId());
return myFile.getId();
}
);
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO get File ID -------------------------------------------
private static String getFileIDFromDatabase()
{
String FileIDFromMethod = null;
Cursor result = MainActivity.demoSQLite.getData();
if (result.getCount() == 0) {
Log.i("CURSOR :", "NO ENTRY");
return null;
} else {
while (result.moveToNext()) {
FileIDFromMethod = result.getString(0);
}
return FileIDFromMethod;
}
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO Restore -------------------------------------------
public static class Restore extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
String fileId = null;
try
{
fileId = getFileIDFromDatabase();
if (fileId != null)
{
File file = mDriveService.files().get(fileId).execute();
downloadFile(file);
}
else
{
return null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return fileId;
}
private void downloadFile(File file)
{
InputStream mInput = null;
FileOutputStream mOutput = null;
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) //Error occurs at file.getDownloadUrl()
{
try
{
HttpResponse resp = mDriveService.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
mInput = resp.getContent();
String outFileName = "file://" + Environment.getDataDirectory().getPath() + filePath;
// Log.e("com.example.myapp", "getDatabasePath="+ getDatabasePath(""));
//Log.e("com.example.myapp", "outFileName="+outFileName);
// String outFileName = "../databases/" + "Quickpay.db";
mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
}
catch (IOException e)
{
// An error occurred.
e.printStackTrace();
// return null;
}
finally
{
try
{
//Close the streams
if (mOutput != null)
{
mOutput.close();
}
if (mInput != null)
{
mInput.close();
}
}
catch (IOException e)
{
Log.e("com.example.myapp", "failed to close databases");
}
}
}
else
{
// The file doesn't have any content stored on Drive.
// return null;
Log.e("com.example.myapp", "No content on Drive");
}
}
}
}
The Gradle file is like
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation('com.google.api-client:google-api-client-android:1.26.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation 'com.google.http-client:google-http-client-gson:1.26.0'
As far as i know Download URL is only avalibale in Google drive api v2 and not in V3.
Short lived download URL for the file. This field is only populated for files with content stored in Google Drive; it is not populated for Google Docs or shortcut files.
It was not very stable in my opinion as not all file types would return a download url.
Using Google Drive v3 you should download the file using a stream.
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
This should work with the restore. Let me know if it doesnt and i will have a look its been a while since i have tried restore.
Related
I am uploading my App on play store but get me bellow error:
Zip Path Traversal Your app contains an unsafe unzipping pattern that
may lead to a Path Traversal vulnerability. Please see this Google
Help Center article to learn how to fix the issue.
org.apache.cordova.Zip.unzipSync
I edited my source code like this LINK, but get me error.
Here is my source code changed:
public class Zip extends CordovaPlugin {
private static final String LOG_TAG = "Zip";
// Can't use DataInputStream because it has the wrong endian-ness.
private static int readInt(InputStream is) throws IOException {
int a = is.read();
int b = is.read();
int c = is.read();
int d = is.read();
return a | b << 8 | c << 16 | d << 24;
}
#Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("unzip".equals(action)) {
unzip(args, callbackContext);
return true;
}
return false;
}
private void unzip(final CordovaArgs args, final CallbackContext callbackContext) {
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
unzipSync(args, callbackContext);
}
});
}
private void unzipSync(CordovaArgs args, CallbackContext callbackContext) {
InputStream inputStream = null;
try {
String zipFileName = args.getString(0);
String outputDirectory = args.getString(1);
// Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
// Accept a path or a URI for the source zip.
Uri zipUri = getUriForArg(zipFileName);
Uri outputUri = getUriForArg(outputDirectory);
CordovaResourceApi resourceApi = webView.getResourceApi();
File tempFile = resourceApi.mapUriToFile(zipUri);
if (tempFile == null || !tempFile.exists()) {
String errorMessage = "Zip file does not exist";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
File outputDir = resourceApi.mapUriToFile(outputUri);
outputDirectory = outputDir.getAbsolutePath();
outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
String errorMessage = "Could not create output directory";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
ProgressEvent progress = new ProgressEvent();
progress.setTotal(zipFile.length);
inputStream = new BufferedInputStream(zipFile.inputStream);
inputStream.mark(10);
int magic = readInt(inputStream);
if (magic != 875721283) { // CRX identifier
inputStream.reset();
} else {
// CRX files contain a header. This header consists of:
// * 4 bytes of magic number
// * 4 bytes of CRX format version,
// * 4 bytes of public key length
// * 4 bytes of signature length
// * the public key
// * the signature
// and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.
readInt(inputStream); // version == 2.
int pubkeyLength = readInt(inputStream);
int signatureLength = readInt(inputStream);
inputStream.skip(pubkeyLength + signatureLength);
progress.setLoaded(16 + pubkeyLength + signatureLength);
}
// The inputstream is now pointing at the start of the actual zip file content.
ZipInputStream zis = new ZipInputStream(inputStream);
inputStream = zis;
ZipEntry ze;
byte[] buffer = new byte[32 * 1024];
boolean anyEntries = false;
while ((ze = zis.getNextEntry()) != null) {
try {
anyEntries = true;
String compressedName = ze.getName();
if (ze.isDirectory()) {
try {
File dir = new File(outputDirectory + compressedName);
File f = new File(dir, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(dir.toString())){
dir.mkdirs();
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
} else {
File file = new File(outputDirectory + compressedName);
File f = new File(file, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(file.toString())) {
file.getParentFile().mkdirs();
if (file.exists() || file.createNewFile()) {
try {
Log.w("Zip", "extracting: " + file.getPath());
FileOutputStream fout = new FileOutputStream(file);
int count;
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
progress.addLoaded(ze.getCompressedSize());
updateProgress(callbackContext, progress);
zis.closeEntry();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
// final progress = 100%
progress.setLoaded(progress.getTotal());
updateProgress(callbackContext, progress);
if (anyEntries)
callbackContext.success();
else
callbackContext.error("Bad zip file");
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) throws JSONException {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
private Uri getUriForArg(String arg) {
CordovaResourceApi resourceApi = webView.getResourceApi();
Uri tmpTarget = Uri.parse(arg);
return resourceApi.remapUri(
tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
}
private static class ProgressEvent {
private long loaded;
private long total;
public long getLoaded() {
return loaded;
}
public void setLoaded(long loaded) {
this.loaded = loaded;
}
public void addLoaded(long add) {
this.loaded += add;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public JSONObject toJSONObject() throws JSONException {
return new JSONObject(
"{loaded:" + loaded +
",total:" + total + "}");
}
}
}
I need to download all the documents from an alfresco site that contains 400GB of documents.
The code below is ok for create a small zip file (about 1GB) otherwise it takes too much memory.
I would not like to keep ZipOutputStream in memory, i would like to use memory only for every document copied to the Zip file or use a temporary file that is overwritten for each document.
What is the best practice for this kind of problem?
This piece of code is called from my main:
FolderImpl sitoFolder = (FolderImpl) cmisObject;
List<Tree<FileableCmisObject>> sitoFolderDescendants = sitoFolder.getDescendants(-1);
byte[] zipFile = createZipFILE(sitoFolderDescendants);
String rootPath = cartella_download_file;
File dir = new File(rootPath + File.separator);
if (!dir.exists()) {
dir.mkdirs();
}
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String stringDate = sdf.format(date);
String nameZipFile = sitoFolder.getName().replaceAll("\\s","");
File serverFile = new File(dir.getAbsolutePath() + File.separator + stringDate+"_"+nameZipFile+".zip");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(serverFile));
IOUtils.write(zipFile, bufferedOutputStream);
bufferedOutputStream.close();
//Returns the zip file
private byte[] createZipFILE(List<Tree<FileableCmisObject>> list) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteTransform byteTransform = new ByteTransform();
try {
ReportDocument reportDocument = new ReportDocument();
ZipOutputStream zos = new ZipOutputStream(baos);
for (Tree<FileableCmisObject> aList : list) {
traverseTree(aList, zos, reportDocument);
}
zos.close();
return baos.toByteArray();
} catch (IOException exc) {
reportLog.error(exc.getMessage());
} finally {
baos.close();
}
return new byte[0];
}
private void traverseTree(Tree<FileableCmisObject> tree, ZipOutputStream zos, ReportDocument reportDocument) {
for (int i=0; i<tree.getChildren().size(); i++) {
Tree<FileableCmisObject> child = tree.getChildren().get(i);
if (CmisUtil.isDocument(child.getItem())) {
Document document = (Document) child.getItem();
try {
addToZipFile(document, zos);
} catch (IOException ioExc) {
appLog.error(ioExc.getMessage());
}
} else if(CmisUtil.isFolder(child.getItem())) {
Folder folder = (Folder) child.getItem();
if (folder.getChildren().getTotalNumItems() == 0) {
try {
addToZipFolder(folder, zos);
} catch (IOException ioExc) {
appLog.error(ioExc.getMessage());
}
}
}
traverseTree(child, zos, reportDocument);
}
}
//Service method to add documents to the zip file
private void addToZipFile(Document document, ZipOutputStream zos) throws IOException {
InputStream inputStream = document.getContentStream().getStream();
String path = document.getPaths().get(0).replace(sito_export_path, "");
ZipEntry zipEntry = new ZipEntry(path);
zos.putNextEntry(zipEntry);
IOUtils.copy(inputStream, zos, 1024);
inputStream.close();
zos.closeEntry();
}
//Service method to add empty folder to the zip file
private void addToZipFolder(Folder folder, ZipOutputStream zos) throws IOException {
String path = folder.getPaths().get(0).replace(sito_export_path, "");
ZipEntry zipEntry = new ZipEntry(path.concat("/"));
zos.putNextEntry(zipEntry);
}
I solved it. I first created a directory on the server and then created the zip file on this directory directly.
The error was to save all the files first on: ByteArrayOutputStream and then on the zip file.
File serverFile = new File(dir.getAbsolutePath() + File.separator + stringDate+"_"+nameZipFile+".zip");
FileOutputStream fileOutputStream = new FileOutputStream(serverFile);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fileOutputStream);
for (Tree<FileableCmisObject> aList : sitoFolderDescendants) {
traverseTree(aList, zos, reportDocument);
}
zos.close();
In the finally block I close the FileOutputStream.
Than I changed the services method using: ZipArchiveOutputStream and ZipArchiveEntry.
private void addToZipFolder(Folder folder, ZipArchiveOutputStream zos) throws IOException {
String path = folder.getPaths().get(0).replace(sito_export_path, "");
ZipArchiveEntry zipEntry = new ZipArchiveEntry(path.concat("/"));
appLog.info("aggiungo cartella vuota "+folder.getName()+" al file zip");
zos.putArchiveEntry(zipEntry);
zos.closeArchiveEntry();
}
private void addToZipFile(Document document, ZipArchiveOutputStream zos) throws IOException {
InputStream inputStream = document.getContentStream().getStream();
String path = document.getPaths().get(0).replace(sito_export_path, "");
ZipArchiveEntry entry = new ZipArchiveEntry(path);
entry.setSize(document.getContentStreamLength());
zos.putArchiveEntry(entry);
byte buffer[] = new byte[1024];
while (true) {
int nRead = inputStream.read(buffer, 0, buffer.length);
if (nRead <= 0) {
break;
}
zos.write(buffer, 0, nRead);
}
inputStream.close();
zos.closeArchiveEntry();
}
Actually i have create downlod as zip functionality for alfresco 3.4.d version and used following code.i have not checked it for GB's file because i don't have that much data.it may be help to you.
This is Java Backed WebScript.
/*
* this class create a zip file base on given(parameter) node
* */
public class ZipContents extends AbstractWebScript {
private static Log logger = LogFactory.getLog(ZipContents.class);
private static final int BUFFER_SIZE = 1024;
private static final String MIMETYPE_ZIP = "application/zip";
private static final String TEMP_FILE_PREFIX = "alf";
private static final String ZIP_EXTENSION = ".zip";
private ContentService contentService;
private NodeService nodeService;
private NamespaceService namespaceService;
private DictionaryService dictionaryService;
private StoreRef storeRef;
private String encoding;
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public void setNamespaceService(NamespaceService namespaceService) {
this.namespaceService = namespaceService;
}
public void setDictionaryService(DictionaryService dictionaryService) {
this.dictionaryService = dictionaryService;
}
public void setStoreUrl(String url) {
this.storeRef = new StoreRef(url);
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
String nodes = req.getParameter("nodes");
if (nodes == null || nodes.length() == 0) {
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "nodes");
}
List<String> nodeIds = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(nodes, ",");
if (tokenizer.hasMoreTokens()) {
while (tokenizer.hasMoreTokens()) {
nodeIds.add(tokenizer.nextToken());
}
}
String filename = req.getParameter("filename");
if (filename == null || filename.length() == 0) {
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "filename");
}
String noaccentStr = req.getParameter("noaccent");
if (noaccentStr == null || noaccentStr.length() == 0) {
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "noaccent");
}
try {
res.setContentType(MIMETYPE_ZIP);
res.setHeader("Content-Transfer-Encoding", "binary");
res.addHeader("Content-Disposition", "attachment;filename=\"" + unAccent(filename) + ZIP_EXTENSION + "\"");
res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
res.setHeader("Pragma", "public");
res.setHeader("Expires", "0");
createZipFile(nodeIds, res.getOutputStream(), new Boolean(noaccentStr));
} catch (RuntimeException e) {
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
}
}
public void createZipFile(List<String> nodeIds, OutputStream os, boolean noaccent) throws IOException {
File zip = null;
try {
if (nodeIds != null && !nodeIds.isEmpty()) {
zip = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, ZIP_EXTENSION);
FileOutputStream stream = new FileOutputStream(zip);
CheckedOutputStream checksum = new CheckedOutputStream(stream, new Adler32());
BufferedOutputStream buff = new BufferedOutputStream(checksum);
ZipArchiveOutputStream out = new ZipArchiveOutputStream(buff);
out.setEncoding(encoding);
out.setMethod(ZipArchiveOutputStream.DEFLATED);
out.setLevel(Deflater.BEST_COMPRESSION);
if (logger.isDebugEnabled()) {
logger.debug("Using encoding '" + encoding + "' for zip file.");
}
try {
for (String nodeId : nodeIds) {
NodeRef node = new NodeRef(storeRef, nodeId);
addToZip(node, out, noaccent, "");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
} finally {
out.close();
buff.close();
checksum.close();
stream.close();
if (nodeIds.size() > 0) {
InputStream in = new FileInputStream(zip);
try {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
} finally {
IOUtils.closeQuietly(in);
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
} finally {
// try and delete the temporary file
if (zip != null) {
zip.delete();
}
}
}
public void addToZip(NodeRef node, ZipArchiveOutputStream out, boolean noaccent, String path) throws IOException {
QName nodeQnameType = this.nodeService.getType(node);
// Special case : links
if (this.dictionaryService.isSubClass(nodeQnameType, ApplicationModel.TYPE_FILELINK)) {
NodeRef linkDestinationNode = (NodeRef) nodeService.getProperty(node, ContentModel.PROP_LINK_DESTINATION);
if (linkDestinationNode == null) {
return;
}
// Duplicate entry: check if link is not in the same space of the
// link destination
if (nodeService.getPrimaryParent(node).getParentRef().equals(nodeService.getPrimaryParent(linkDestinationNode).getParentRef())) {
return;
}
nodeQnameType = this.nodeService.getType(linkDestinationNode);
node = linkDestinationNode;
}
String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
nodeName = noaccent ? unAccent(nodeName) : nodeName;
if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_CONTENT)) {
ContentReader reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
if (reader != null) {
InputStream is = reader.getContentInputStream();
String filename = path.isEmpty() ? nodeName : path + '/' + nodeName;
ZipArchiveEntry entry = new ZipArchiveEntry(filename);
entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime());
entry.setSize(reader.getSize());
out.putArchiveEntry(entry);
byte buffer[] = new byte[BUFFER_SIZE];
while (true) {
int nRead = is.read(buffer, 0, buffer.length);
if (nRead <= 0) {
break;
}
out.write(buffer, 0, nRead);
}
is.close();
out.closeArchiveEntry();
} else {
logger.warn("Could not read : " + nodeName + "content");
}
} else if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_FOLDER)
&& !this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_SYSTEM_FOLDER)) {
List<ChildAssociationRef> children = nodeService.getChildAssocs(node);
if (children.isEmpty()) {
String folderPath = path.isEmpty() ? nodeName + '/' : path + '/' + nodeName + '/';
ZipArchiveEntry entry = new ZipArchiveEntry(folderPath);
entry.setSize(0);
entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime());
out.putArchiveEntry(entry);
out.closeArchiveEntry();
} else {
for (ChildAssociationRef childAssoc : children) {
NodeRef childNodeRef = childAssoc.getChildRef();
addToZip(childNodeRef, out, noaccent, path.isEmpty() ? nodeName : path + '/' + nodeName);
}
}
} else {
logger.info("Unmanaged type: " + nodeQnameType.getPrefixedQName(this.namespaceService) + ", filename: " + nodeName);
}
}
/**
* ZipEntry() does not convert filenames from Unicode to platform (waiting
* Java 7) http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499
*
* #param s
* #return
*/
public static String unAccent(String s) {
String temp = Normalizer.normalize(s, Normalizer.NFD, 0);
return temp.replaceAll("[^\\p{ASCII}]", "");
}
}
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}
I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}
I'm working with Android and I'm trying to use a database I already have. I'd like to put it on the SD card. I have the database file in my project's assets folder. How can I make it on the SD card or external storage of whatever device the app is installed on?
//Step1 : Checked accessiblity on sd card
public boolean doesSDCardAccessible(){
try {
return(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
//Step2 : create directory on SD Card
//APP_DIR : your PackageName
public void createAndInitAppDir(){
try {
if(doesSDCardAccessible()){
AppDir = new File(Environment.getExternalStorageDirectory(),APP_DIR+"/");
if(!AppDir.exists()){
AppDir.mkdirs();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Step 3 : Create Database on sdcard
//APP_DIR : your PackageName
//DATABASE_VERSION : give Database Vesrion
//DATABASE_NAME : your Databsename Name
public void initDB()
{
try {
//Using SQLiteHelper Class Created Database
sqliteHelper = new SQLiteHelper(Application.this,AppDir.getAbsolutePath()+"/"+DATABASE_NAME,
null, DATABASE_VERSION);
//OR use following
//Creating db here. or db will be created at runtime whenever writable db is opened.
db = SQLiteDatabase.openOrCreateDatabase(AppDir.getAbsolutePath()+"/"+DATABASE_NAME, null);*/
db= sqliteHelper.getWritableDatabase();
db.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
In reference to this answer, you can find the directory of the SD card in Android 4.0+ by trying both of the following (only one should work per device):
new File("/mnt/external_sd/");
or
new File("/mnt/extSdCard/");
On Android <4.0, you can use
Environment.getExternalStorageDirectory();
You can create your SQLite database there. Additionally, if you can't find it, you can iterate over all directories in /mnt/ (note: the sdcard will always be accessible via /mnt/).
Go throuh this link
OR try following
InputStream myInput;
try {
AssetManager assetManager = getAssets();
myInput = assetManager.open("mydatabase.db");
File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory
.getPath() + "/DatabaseSample.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The database is like any other flat file. Just copy it to your SD card.
public boolean backup()
{
File sdcard = Environment.getExternalStorageDirectory();
File data = new File("/data/data/com.mydomain.myappname/databases/");
if (sdcard.canWrite())
{
File input = new File(data, DB_NAME);
File output = new File(sdcard, "android/data/com.mydomain.myappname/databases/");
if(!output.exists())
{
if(output.mkdirs())
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
output.createNewFile();
result = true;
}
else
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
result = true;
}
if(input.exists() && result)
{
FileInputStream source;
FileOutputStream destination;
try
{
source = new FileInputStream(input);
try
{
destination = new FileOutputStream(output);
byte[] buffer = new byte[1024];
int length;
while((length = source.read(buffer)) > 0)
{
destination.write(buffer, 0, length);
}
source.close();
destination.flush();
destination.close();
result = true;
}
catch(Exception e)
{
result = false;
destination = null;
}
}
catch(Exception e)
{
result = false;
source = null;
}
}
else
{
result = false;
}
}
else
{
result = false;
}
}
catch(Exception e)
{
result = false;
}
return result;
}