Android move file to External Device with press of Button - android

I need to make a button so that it moves a specific file to the External Drive. I have set the manifest so it allows to write to External Storage but I can not find the code to write a specific file to write to the External Storage.

Make sure you have the following permissions if writing/reading external memory in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
called like this:
copyExt("/storage/emulated/0/obb/Orange.txt","");
//turn String path names into File descriptors
public void copyExt (String pathInternal, String pathExternal) {
File fInternal = new File (pathInternal);//pathInternal must exist
// File fExternal = new File (pathExternal);//pathExternal must exist
String filename=path.substring(pathInternal.lastIndexOf("/")+1);
File fExternal = new File(Environment.getExternalStorage().getAbsolutePath()+"/filename");
copyFile(fInternal,fExternal);
}
//make it static so we can re-use it, in a Utils class
public static void copyFile(File src, File dst) throws IOException
{
try
{
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
ALTERNATIVE
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}

Related

How to make a downloaded file visible in File Manager after written/downloaded into Android?

I have successfully downloaded the file from the server and saved it on Android storage, but the file is stored in a deep path, for example: /storage/emulated/0/Android/data/example.com.yourapp/files/Download/example_file.pdf
The code I'm currently using is like this:
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
assert filesDir != null;
downloadedFile = new File(filesDir,
"file_name" + ".pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(downloadedFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
Functions.scanFile(getContext(), downloadedFile, "application/pdf");
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
What I want, when the download process is successful and I open the file manager, the latest file that already downloaded can be seen in the latest file before.
I don't know yet, but I think I need to make use of MediaStore to make my files visible in File Manager by trying this code:
public static void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection.scanFile(ctxt, new String[] {f.getAbsolutePath()}, new String[] {mimeType}, null);
}
But it didn't work either. How do i achieve this?
So i just change File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
into File filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
And it's available in recent files in File manager

Read,Write,Delete Specific text from json file

I am currently developing an application that reads,writes,updates,deletes json file.i have 4 json files namely data.json(to store name,address,area,pin),image.json(to store image name),location.json(to store latitute,longitude) and final.json that merges the above json files.final.json will combine all data from 3 files to make a single record.In a activity I need to read the name,date,time of all records stored in final.json in different radio buttons. I am unable to read only the name,date,time from a record stored in temp.json as temp.json contains latitute,longitude,image name,name,address,pin,area,date,time.Please help me do the following.Also I need to delete only specific record from temp.json file.
This is the code I used to read the text from temp.json.How to read only name,date,time from the file.I am able to read all the parameters
My temp.json looks like
{Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22"]} {Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22" ]}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File file = new File(myDir, FILENAME);//making a new file in the folder
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
String x=text.toString();
String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
String[] y=z.split(",");
//rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString()+""+"");
// rb2.setText(y[11].toString()+","+y[15].toString()+","+y[16].toString());
//rb3.setText(y[19].toString()+","+y[23].toString()+","+y[24].toString());
//rb4.setText(y[27].toString()+","+y[31].toString()+","+y[32].toString());
}
else
{
rb1.setText("Sorry file doesn't exist!!");
}
///////merge code////
static class CopyFileContent {
public static void main(String[] args) {
JSONObject jsonObj2 = new JSONObject();
try {
// Here we convert Object to JSON
jsonObj2.put("date",a.toString());jsonObj2.put("time",c.toString());// Set the first name/pair
} catch (JSONException ex) {
ex.printStackTrace();
}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir,FILENAME12);
File sourceFile2 = new File(myDir,FILENAME13);
File sourceFile3 = new File(myDir,FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4=null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile,true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
output.write(jsonObj2.toString().getBytes());
output.write("]}".getBytes());
output.write("\r\n".getBytes());
output.write("\r\n".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to copy a file to another directory programmatically?

There is an image file inside a directory. How to copy this image file into another directory that was just created ? The two directories are on the same internal storage of the device :)
You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.
Also note you need to have permissions to do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Functions:
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
If you want to copy image programtically then use following code.
File sourceLocation= new File (sourcepath);
File targetLocation= new File (targetpath);
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
** Use FileUtils This Is Simple Fast And Best method and Download Jar file from here**
public void MoveFiles(String sourcepath) {
File source_f = new File(sourcepath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsappStatus/yourfilename.mp4";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source_f , destination);
}
catch (IOException e)
{
e.printStackTrace();
}
}
Go To Link For FileUtils Jar

android unzip file memory leakage

I have below code for unzip file. (from a thread in stackoverflow)
/**
* Unzip a zip file. Will overwrite existing files.
*
* #param zipFile Full path of the zip file you'd like to unzip.
* #param location Full path of the directory you'd like to unzip to (will be created if it doesn't exist).
* #throws IOException
*/
public static void unzip(String zipFile, String location, String excludePath) throws IOException {
int size;
byte[] buffer = new byte[BUFFER_SIZE];
try {
if ( !location.endsWith("/") ) {
location += "/";
}
File f = new File(location);
if(!f.isDirectory()) {
f.mkdirs();
}
FileInputStream fin = new FileInputStream(zipFile);
BufferedInputStream bin = new BufferedInputStream(fin, BUFFER_SIZE);
ZipInputStream zin = new ZipInputStream(bin);
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
//String path = location + ze.getName();
String unzipFilePath = ze.getName().replace(excludePath, "");
String path = location + unzipFilePath;
File unzipFile = new File(path);
if (ze.isDirectory()) {
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
} else {
// check for and create parent directories if they don't exist
File parentDir = unzipFile.getParentFile();
if ( null != parentDir ) {
if ( !parentDir.isDirectory() ) {
parentDir.mkdirs();
}
}
// unzip the file
FileOutputStream out = new FileOutputStream(unzipFile, false);
BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
try {
while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
fout.write(buffer, 0, size);
}
zin.closeEntry();
}
finally {
fout.flush();
fout.close();
out.close();
}
}
}
}
finally {
zin.close();
fin.close();
bin.close();
}
}
catch (Exception e) {
Log.e("bug", "Unzip exception", e);
}
buffer = null;
System.gc();
}
I have no problem in unzipping file. But as my program continue to run. It tried to show the unzipped jpeg image ( 1000px x 800px) by below code. I created a button to show one image at a time.
fisImg = new FileInputStream(new File(imgPath[i]));
Bitmap imgBitmap = BitmapFactory.decodeStream(fisImg );
It has no problem in loading the first image, but when i pressed next button, it tried to load the next image, it called out of memory exception.
I wonder if my unzip code has memory leakage?

Light protection for exported database

In my application I have implemented the possibility to export the database by copying the database file on the sdcard.
Without encrypting the file or require special keys to read it I just want to make sure that anyone who picks the file up is able to read db structure or data just by opening it in a sqlite file reader.
How can I implement a light and simple protection for my file?
The following is my code for db exporting.
public void exportDB() {
final String destFolder = "/"+Constants.Files.APP_FOLDER+"/"+Constants.Files.BACKUP_FOLDER;
try {
File myBackupDir = new File(Environment.getExternalStorageDirectory() + destFolder);
if(!myBackupDir.exists() || !myBackupDir.isDirectory()) myBackupDir.mkdirs();
if(myBackupDir.isDirectory()){
File data = Environment.getDataDirectory();
if (Environment.getExternalStorageDirectory().canWrite()) {
final String currentDBPath= "//data//" + Constants.Files.PACKAGE_NAME + "//databases//" + Constants.Files.DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(myBackupDir, Constants.Files.DB_NAME);
if(currentDB.isFile()){
copyFile(new FileInputStream(currentDB), new FileOutputStream(backupDB))
}
}
}
} catch (Exception e) {
Log.e(mTag, "exportDB", e);
}
}
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
You can use sqlcipher. It has support for android. You can export it with your existing code since the DB is already encrypted.

Categories

Resources