i know how to copy paste afile but with one button that make acopy and paste .
static void copyFile(String readFile,String writeFile ){
try {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
fi = new FileInputStream(readFile);
fo = new FileOutputStream(writeFile);
//Read File
byte[] byt = new byte[fi.available()];
int r =0;
while((r=fi.read(byt))!=-1){
//fo.write(byt);
fo.write(byt, 0, r);
}
fi.close();
fo.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
finally{
}
but how to copy by one button and paste with another?
You can call method which copy file from source to path within your onClickEvent of your Button.
onClickEvent Handler snippet :
Button button1 = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
copy(filesrcpath, filedestpath); // Pass Filesrc and FilePath
}
});
Copy() snippet which takes two parameter one source and another destination path.
public void copy(File src, File dst) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// 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();
}
Related
I would like to copy an existing video file to another video file.
I trying to do it like this:
byte c;
try {
FileOutputStream newFile = new FileOutputStream (VIDEO_PATH_TMP);
FileInputStream oldFile = new FileInputStream (VIDEO_PATH);
while ((c = (byte) oldFile.read()) != -1) {
newFile.write(c);
}
newFile.close();
oldFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it doesn't work. The output file was created, but i can't see the video.
How can i implement this?
Thanks!
Ok, I found the answer and this is the code:
try {
FileOutputStream newFile = new FileOutputStream (VIDEO_PATH_TMP);
FileInputStream oldFile = new FileInputStream (VIDEO_PATH);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = oldFile.read(buf)) > 0) {
newFile.write(buf, 0, len);
}
newFile.close();
oldFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I just added the Buffer array and it solved the problem :)
I think you should call flush before close:
newFile.flush();
newFile.close();
This is the original code for copying one file from asset to internal storage I found online:
Context Context = getApplicationContext();
String DestinationFile = Context.getFilesDir().getPath() + File.separator + "DB.sqlite";
if (!new File(DestinationFile).exists()) {
try {
CopyFromAssetsToStorage(Context, "Database/DB.sqlite", DestinationFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
CopyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}
The above code is working fine for copying one file. However, what I want is to copy multiple files instead of one file. Following MT8, I modified my the code to below:
public class MainActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> destFiles = new ArrayList<String>();
destFiles.add("FileB.jpg");
destFiles.add("FileC.jpg");
destFiles.add("FileD.jpg");
for(int i =0 ; i < destFiles.size(); i++) {
Context Context = getApplicationContext();
String DestinationFile = Context.getFilesDir().getPath() + File.separator + "FileA.db";
if (!new File(DestinationFile).exists()) {
try {
CopyFromAssetsToStorage(Context, "database/FileA.db", destFiles.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
CopyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}
}
However, the files won't be copied. Any part that I did wrongly?
Step 1 : u need to put the All files name in Arraylist first say ArrayList<String> destFiles .
ArrayList<String> destFiles = new ArrayList<String>();
destFiles.add("FileA");
destFiles.add("FileB");
destFiles.add("FileC");
Step 2 : For loop :
for(int i=0;i<destFiles.size;i++)
{
Context Context = getApplicationContext();
String DestinationFile = Context.getFilesDir().getPath() + File.separator + "DB.sqlite";
if (!new File(DestinationFile).exists()) {
try {
CopyFromAssetsToStorage(Context, "Database/DB.sqlite", destFiles.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
CopyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}
}
You can copy all the data from Asset folder into Internal Storage (Download Folder of Android), Call the copyAsset() function in onCreate.
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);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/";
File outFile = new File(outDir, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
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 have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How can I create a ZIP file from an XML file?
I want to take a backup of all my inbox messages in XML, and compress the XML file and store it on an SD card.
The following code solved my problem.
public class makeZip {
static final int BUFFER = 2048;
ZipOutputStream out;
byte data[];
public makeZip(String name) {
FileOutputStream dest=null;
try {
dest = new FileOutputStream(name);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
}
public void addZipFile (String name) {
Log.v("addFile", "Adding: ");
FileInputStream fi=null;
try {
fi = new FileInputStream(name);
Log.v("addFile", "Adding: ");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("atch", "Adding: ");
}
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(name);
try {
out.putNextEntry(entry);
Log.v("put", "Adding: ");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count;
try {
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
//Log.v("Write", "Adding: "+origin.read(data, 0, BUFFER));
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("catch", "Adding: ");
}
try {
origin.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeZip () {
try {
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If you have a FOLDER in SDCard and you want to create a zip of it, then simply copy and paste this code in your project and it will give you a zip Folder. This code will create a zip of the folder which only contains files no nested folder should be inside. You can further modify for your self.
String []s=new String[2]; //declare an array for storing the files i.e the path of your source files
s[0]="/mnt/sdcard/Wallpaper/pic.jpg"; //Type the path of the files in here
s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file
zip((s,"/mnt/sdcard/MyZipFolder.zip"); //call the zip function
public void zip(String[] files, String zipFile)
{
private String[] _files= files;
private String _zipFile= zipFile;
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.d("add:",_files[i]);
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
Also add permissions in android-manifest.xml using this code
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
You may take a look at this two links:
ZipOutputStream http://developer.android.com/reference/java/util/zip/ZipOutputStream.html
Zipping files http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29
Hope this helps
The Android SDK has the gZip API, by which you can read/write conpressed data. See public class GZIPOutputStream.
Use the following code, but if you want to save to the SD card, do a fileoutputstream rather than bytearrayoutputstream.
private String compressData(String uncompressedData) {
String compressedData = null;
try {
if (uncompressedData.length() > 200) {
// Perform Compression.
byte[] originalBytes = uncompressedData.getBytes();
Deflater deflater = new Deflater();
deflater.setInput(originalBytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
while (!deflater.finished()) {
int byteCount = deflater.deflate(buf);
baos.write(buf, 0, byteCount);
}
deflater.end();
byte[] compressedBytes = baos.toByteArray();
compressedData = new String(compressedBytes, 0, compressedBytes.length);
}
}
catch (Exception e) {
compressedData = null;
}
return compressedData;
}
I have an application to download zip file and save to sdcard. But I get zipentry=null while reading inputstream, it doesn't enter the while block. Could anyone help me in solving this problem, please?
try {
// fileInputStream = new InputStream(input);
ZipInputStream zipInputStream
= new ZipInputStream(new BufferedInputStream(input));
ZipEntry zipEntry=zipInputStream.getNextEntry();
Toast.makeText(getApplicationContext(), "I have entered try block zipentry"+zipEntry,Toast.LENGTH_LONG).show();
System.out.println("Zipentry is"+zipEntry);
while ((zipEntry = zipInputStream.getNextEntry()) != null){
Toast.makeText(getApplicationContext(), "Entered into while block",Toast.LENGTH_LONG).show();
String zipEntryName = zipEntry.getName();
File file = new File(to + zipEntryName);
if (file.exists()){
} else {
if(zipEntry.isDirectory()){
file.mkdirs();
}else{
byte buffer[] = new byte[BUFFER_SIZE];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream
= new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
int count;
while ((count
= zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
zipInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "File not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Input outout error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
You already have one ZipEntry zipEntry=zipInputStream.getNextEntry(); before condition in the while loop. Leave it out and initialize it only in the while loop. Something like:
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null){
//
}