have ones app copy file from webpage - android

I have made an app that have to copy a file from a webpage, the following code doesn't do the job, it can't find the file
File ekstern = new File("http://192.168.13.40/cache.manifest");
copyFile(ekstern, intern);
and the copyFile method:
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
But the code says that the file doesn't exists
testing with ekstern.exists()

You can't use File object to get something from a webpage. You have to use an HttpClient

Related

FileInputStream error in SonarQube

I am getting SonarQube critical issue at below code
The problem is, sonarqube suggesting me to use try-with-resources which is only for above API LEVEL 19+ and i am targeting to LEVEL 16 as minimumSDK.
either way it is showing that close FileInputStream in finally block which i have already done in below code.
protected void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (source != null) {
destination.transferFrom(source, 0, source.size());
}
} finally {
if (source != null && destination != null) {
source.close();
destination.close();
}
}
}
Even android studio gives red-line error and suggests the same to use try-with-resources OR close stream in finally block.
UPDATE
SonarQube is giving a critical issue because there is a scenario when one of source or destination streams is not null. Also, you are not closing the FileInputStream objects and only closing their channels. In that case you would not close that FileChannel. See this line:
if (source != null && destination != null) {...}
In order to avoid this, you can do the following:
1: Split close of FileChannel as #fejd suggested.
2: Nested try-catch blocks, with each finally block closing their own streams.
One a general note, you can use 2 in more complex scenarios, but for the given one, 1 should suffice.
It's because you're only closing the two channels if both are null, and you are not closing the streams. Try extracting the check/close to separate blocks like:
protected void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileInputStream fis = null;
FileChannel source = null;
FileOutputStream fout = null;
FileChannel destination = null;
try {
fis = new FileInputStream(sourceFile);
source = fis.getChannel();
fout = new FileOutputStream(destFile);
destination = fout.getChannel();
if (source != null) {
destination.transferFrom(source, 0, source.size());
}
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("Failed to close source input stream.");
}
}
if (source != null) {
try {
source.close();
} catch (IOException e) {
System.out.println("Failed to close source channel.");
}
}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
System.out.println("Failed to close destination output stream.");
}
}
if (destination != null) {
try {
destination.close();
} catch (IOException e) {
System.out.println("Failed to close destination channel.");
}
}
}
}

How to save a text file present in asset folder of android app to the local directory of android phone as text or pdf file?

I have saved some text files in asset folder of android apk , whenever user opens the app which is having list of filenames ,if he clicks on a filename corresponding file opens from asset folder ,
Now I want to let user save that file in text or pdf format to his local directory so that he can transfer it or use it or modify it according to his choice
EDIT : I just want to know the api needed ,not the whole code
Use this function to copy something from assets to storage
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
Reference : Move file using Java

copy files from assets folder to sd card in android

my code works fine for copying a file from assets folder to sd card. but whenever i try to copy again, it just replaces the old file with the new one instead of renaming it. how do i fix this? thanks
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
}
Overwriting files in case they exist is a normal behavior, Use fileObject.exists() method to check, If the file exists pick another filename, You can use System.currentTimeMillis() method to gain a unique suffix and add it to the file name.
NaN answer is one of the ways to achieve your goal, just changing one line will do the job:
File outFile = new File(getExternalFilesDir(null), filename + System.currentTimeMillis());
Another way is to increase file size ad eternum, but if you are making a tools suit this won't fit your needs.

How can i restore my database to its original directory?

Here is the code to save/copy my data in to SDcard,when i click on Backup Button my database saved in sdcard in NOTEIT directory and now i want to restore this database when i click on restore button into my default directory so can anyone tell me how to achieve this?
public static void backupDatabase() throws IOException
{
try
{
File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");
File exportDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
file.createNewFile();
FileChannel inChannel = new FileInputStream(dbFile).getChannel(); //fails here
FileChannel outChannel = new FileOutputStream(file).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
I believe the restore is an exact opposite of your backup.
Like this:
public static void restoreDatabase() throws IOException
{
try
{
File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");
File importDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");
if (!importDir.exists())
{
throw new IOException("External 'NOTEIT' directory does not exist.");
return;
}
File file = new File(importDir, dbFile.getName());
if (!file.exists()) 
{
    throw new IOException("Does not exist external db file: NOTEIT/" + dbFile.getName());
    return;
}
FileChannel outChannel = new FileOutputStream(dbFile).getChannel();
FileChannel inChannel = new FileInputStream(file).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

Download all types of file from Dropbox

I am working on Dropbox. I see the documentation. This is my code to display list:
Entry entryCheck = mApi.metadata("/", 100, null, true, null);
Log.i("Item Name", entryCheck.fileName());
Log.i("Is Folder", String.valueOf(entryCheck.isDir));
I got all list from dropbox but my question is that
Here entryCheck.isDir always give me true value if it is file or directory so how i can know which is file or which one is directory?
How i downloaded that files.
I tried with this but it is not working:
private boolean downloadDropboxFile(String dbPath, File localFile,
DropboxAPI<?> api) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); // otherwise dropbox client will fail
// silently
}
DropboxInputStream fin = mApi.getFileStream("dropbox", dbPath);
br = new BufferedInputStream(fin);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
This will work
String inPath ="mnt/sdcard/"+filename;
File file=new File(inPath);
try {
mFos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
mApi.getFile("/"+filename, null, mFos, null);
This downloads the file and store it in the sdcard location inPath.
You have to do it in a new thread,not in main thread.Use AsyncTask.
http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
this link explains why..

Categories

Resources