Create a copy of video (.mp4) file android - android

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();

Related

Android: Encrypt multiple files in one file and decrypt one of them

I encrypted multiple files in one file in order.
Now I want to decrypt only one of those files. for this purpose I did this:
I got all bytes of encrypted files as array Like this: (first index: byte offset of every file in the encrypted file, second index: length of file bytes in the encrypted file)
int[] file1 = new int[] {0 ,109624}
int[] file2 = new int[] {109624,40480}
int[] file3 = new int[] {150104,153640}
int[] file4 = new int[] {303744,24320}
Now for getting specific file from the encrypted file and decrypt it I should to read the encrypted file. First of all, skip the bytes of previous files.
for skipping them I use this method (for example I want to encrypt file2):
int fromByte = file2[0];
int fileLength = file2[1];
FileInputStream fis = new FileInputStream(sourceFile);
CipherInputStream cis = new CipherInputStream(fis,cipher);
long skipBytes = cis.skip(fromByte);
Then it reads byte to byte of source file in "while" loop and when length of read file bytes equals to fileLength, it breaks loop.
I brought all the codes at the end here.
When I decrypt first file (from byte:0 and file length:109624 and it dosn't need to "skip bytes"), It works well.
But when I decrypt other files (for example for encrypt file2 it needs to skipt 109624 byte from source file), It doesn't work well and created file is not decrypted.
Why it dosn't work for other files?
Here's my codes:
public void decryptFile(File sourceFile, File targetFile, int fromByte, int lengthToRead, SecretKeySpec keySpec) {
try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,keySpec);
CipherInputStream cis = new CipherInputStream(fis,cipher);
int readPart,currentLength = 0, bufferSize = 8;
long skipBytes;
byte[] bytes = new byte[bufferSize];
skipBytes = cis.skip(fromByte);
while ((readPart = cis.read(bytes)) != -1) {
fos.write(bytes,0,readPart);
currentLength += bufferSize;
if (currentLength >= lengthToRead) {
break;
}
}
cis.close();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
Here's My codes for encrypt multiple files in on file:
public void encryptFile(File[] sourceFiles, File targetFile, SecretKeySpec keySpec) {
try {
FileOutputStream fos = new FileOutputStream(targetFile);
FileInputStream fis;
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,keySpec);
CipherOutputStream cos = new CipherOutputStream(fos,cipher);
int readPart,bufferSize = 8;
byte[] bytes = new byte[bufferSize];
for (File sourceFile : sourceFiles) {
fis = new FileInputStream(sourceFile);
while ((readPart = fis.read(bytes)) != -1) {
cos.write(bytes, 0, readPart);
}
fis.close();
}
cos.flush();
cos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
I realized the problem, After many reviews.
There are two problem in this codes:
problem 1: in skip method. we should check the skipBytes and if it is not equal to fromByte, it must repeat. for this purpose add these codes:
while (skipBytes<fromByte) {
fromByte -= skipBytes;
skipBytes = cis.skip(fromByte);
}
problem 2: in encrypt function. if the file length is not multiple of 8, encryption method add some bytes until its length is multiple of 8. for fix this problem we should to add those bytes to the file ourselves before encrypt it. for this purpose add these codes before encrypt every file:
int remaining = (int) (sourceFile.length() % 8);
if (remaining>0) {
BufferedWriter bw = new BufferedWriter(new FileWriter(sourceFile,true));
while (remaining<8) {
bw.write(" ");
remaining++;
}
bw.close();
}
This codes modifies source file. If you want to don't modifying source file, instead of above codes, use this codes after ending encryption while loop:
int remainder = (int)(sourceFile.length() % 8);
if (remainder>0) {
StringBuilder sb = new StringBuilder("");
while (remainder<8) {
sb.append(" ");
remainder++;
}
byte[] additionBytes = sb.toString().getBytes(Charset.forName("UTF-8"));
cos.write(additionBytes, 0, additionBytes.length);
}

Write .3gp file on sd card

I have .3gp audio file which is stored in SD Card.I want to copy that file into another folder of sd card.I have googled a lot about it but didn't get any working idea.Please help me if anyone knows.The code I have tried till now is given below:
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(file_save);
out.close();
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buffer = bos.toByteArray();
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is always create a new file with the size of 100.Thanks in advance...
The code when i call this save() method is:
mFileFirst = new File(mFileName);//mFileName is the path of sd card where .3gp file is located
save(mFileFirst);
Try this
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
FileInputStream fis = new FileInputStream(file_save);
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buf = new byte[1024];
int len;
int total = 0;
while ((len = fis.read(buf)) > 0) {
total += len;
fos.write(buf, 0, len);
// Flush the stream once every so often
if (total > (20 * 1024)) {
fos.flush();
}
}
fos.flush();
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Android: Accessing File from Internal Storage Using RandomAccessFile

I am creating an app that needs to read data from a file. I was initially reading it from the assets folder using a BufferedReader and an InputStreamReader but I was running into memory issues (see Android: File Reading - OutOfMemory Issue). One suggestion was to copy the data from the assets folder to the internal storage (not the SD card) and then access it via RandomAccessFile. So I looked up how to copy files from the assets to internal storage and I found 2 sources:
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww
http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html
I decided to use the code from the second one and modified it for my file. So it looks like this:
public void copyFile() {
//Open your file in assets
Context context = getApplicationContext();
String destinationFile = context.getFilesDir().getPath() + File.separator + "text.txt";
if (!new File(destinationFile).exists()) {
try {
copyFromAssetsToStorage(context, "text.txt", destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int length = Input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
}
private void copyFromAssetsToStorage(Context context, String sourceFile, String destinationFile) throws IOException {
InputStream inputStream = context.getAssets().open(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
copyStream(inputStream , outputStream );
outputStream.flush();
outputStream.close();
inputStream.close();
}
I am assuming that this copies the file into the app's data directory. I have not been able to test it because I would like to be able to access the file using RandomAccessFile. However, I have never done either one of these two (copying the file from assets and RandomAccessFile) so I am stuck. The work on this app has come to a standstill because this is the only thing that is preventing me from completing it.
Can anyone provide me with corrections, suggestions, and correct implementations of how to access the data using RandomAccessFile? (The data is a list of strings 4-15 characters in length on each line.)
EDIT*
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = context.getAssets().open(filename);
fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return cacheFile;
}
1- Copy the file from assets to the cache directory
This code just for illustration, you have to do appropriate exception handling and close resources
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = context.getAssets().open(filename);
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
fileOutputStream.close();
inputStream.close();
return cacheFile;
}
2- Open the file using RandomAccessFile
File cacheFile = createCacheFile(context, "text.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");
// Process the file
randomAccessFile.close();
On a side note, you should follow Java naming conventions, e.g. your method and variable name should start with small letter such as copyFromAssetsToStorage and destinationFile
Edit:
You should make a separate try/catch for each close() operation, so if one fails the other still get executed and check that they are not null
finally {
try {
if(fileOutputStream!=null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Creating a ZIP file with Android

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;
}

Android external write permitted but file not found exception

In the emulator I'm trying to write to the file:
/mnt/sdcard/Android/data/com.Me.MyApp/files/myFile.txt
I have set external write permissions in the Manifest, but I keep receiving a file not found exception. The emulator is configured to have an sd-card.
Why might that be?
InputStream is = c.getResources().openRawResource(R.raw.my_raw_file);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try
{
while (zis.getNextEntry() != null)
{
File destFile = new File(destinationPath);
// EXCEPTION THROWN NEXT LINE!
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[BUF_SIZE];
int count;
while ((count = zis.read(buffer)) != -1)
{
os.write(buffer, 0, count);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
zis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Try below code
String path = "/mnt/sdcard/Android/data/com.Me.MyApp/files";
File mFile = new File(path);
mFile.mkdirs();
Nammari's answer plus:
Android Tutorial: Creating and Using an SD Card in the Emulator
http://www.streamhead.com/android-tutorial-sd-card/

Categories

Resources