Hi Everyone I am trying to copy an image from one folder to another which user selects from the gallery. It's not throwing any error as well. Please check the below code.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName = "";
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY) {
try {
Uri selectedImageUri = data.getData();
String path = getPathFromURI(selectedImageUri);
switch (cameraNo) {
case 1:
Bitmap bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
imageBtn1.setImageBitmap(bitmap1);
reduceImageSize(path);
fileName = path.substring(path.lastIndexOf("/")+1);
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
String destinationImagePath= "/MyImages/file.jpg";
File source= new File(path);
File destination= new File(sd, destinationImagePath);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
imageArrayList.add(path);
imageNameList.add(fileName);
break;
}}
this is working for me, give it a try ;):
public static void copyFile(String inputPath, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputPath);
out = new FileOutputStream(outputPath);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;
LOGGER.debug("Copied file to " + outputPath);
} catch (FileNotFoundException fnfe1) {
LOGGER.error(fnfe1.getMessage());
} catch (Exception e) {
LOGGER.error("tag", e.getMessage());
}
}
if you have a source path and destination path then try this one
/**
* copy contents from source file to destination file
*
* #param sourceFilePath Source file path address
* #param destinationFilePath Destination file path address
*/
private void copyFile(File sourceFilePath, File destinationFilePath) {
try{
if (!sourceFilePath.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFilePath).getChannel();
destination = new FileOutputStream(destinationFilePath).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
All the best
Related
Short answer is it possible to get original file from Gallery request,and if it possible how can i do it? This code doesn't work for me.
Uri uri = data.getData();
File file = new File(uri.getPath());
And the long Answer)):
I use this code to make gallery intent
addGallery.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_IMAGE_REQUEST);
}
});
In mu onActivityResult i use this code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
switch (requestCode)
{
case GALLERY_IMAGE_REQUEST:
if (data != null)
{
try
{
Uri uri = data.getData();
File file = new File(uri.getPath());
FileInputStream inputStream = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
inputStream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
And i cant get file.
The same code with getting bitmap from data works well but i need to get exactly file from gallery but not only Uri or Bitmap.
try
{
Uri uri = data.getData();
InputStream imageStream = getContentResolver().openInputStream(uri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
imageStream.close();
} catch (Exception e)
{
e.printStackTrace();
}
If you want to import a picture from gallery into your app (in a case your app own it), you need to copy it to your app data folder.
in your onActivityResult():
if (requestCode == REQUEST_TAKE_PHOTO_FROM_GALLERY && resultCode == RESULT_OK) {
try {
// Creating file
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d(TAG, "Error occurred while creating the file");
}
InputStream inputStream = getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(photoFile);
// Copying
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "onActivityResult: " + e.toString());
}
}
Creating the file method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Copy method:
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
I get a song from the user's library like this:
Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
selectIntent.setType("audio/*");
startActivityForResult(selectIntent, SONG_REQUEST_CODE);
and retrieve it like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SONG_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if ((data != null) && (data.getData()!=null)) {
song = data.getData(); //song is an Uri defined previuosly
}
}
}
I need to import it into a folder I defined and created like this:
final File dir2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Chords/Imported Audio");
dir2.mkdirs();
I tried like this as suggested by Commonsware but the file is not created:
private void importAudio(Uri uri) {
String source = uri.getPath();
String destinationFile = dir2 + File.separator + songName;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(source));
bos = new BufferedOutputStream(new FileOutputStream(destinationFile, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The file is not there though. How can I fix this?
The file is not there though
Most likely, you have a stack trace in LogCat. song.getPath() is unlikely to be useful. song probably does not have a file scheme, and so getPath() is meaningless.
Use ContentResolver and openInputStream() to get an InputStream on song, then use that InputStream to copy the content.
Also:
Make sure that you have runtime permissions set up properly
Index the destination file so that it can be seen from more apps plus desktop OSes
According to my code that I can select a file after that how can I save that selected file in given directory?
Here I captured Uri but I could not save that audio file in Specific folder.
Where can be the issue?Any mistake which I have done while writing outputStream?
public class Upload extends AppCompatActivity {
File folder;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
folder = new File(Environment.getExternalStorageDirectory() + "/Audios");
File folder1 = new File(Environment.getExternalStorageDirectory() + "/");
if (!folder.exists()) {
folder.mkdir();
}
for (File f : folder.listFiles()) {
if (f.isFile()) {
String name = f.getName();
// System.out.print(name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
// Do your stuff
}
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
FileInputStream fileInputStream = null;
//the selected audio.
Uri uri = data.getData();
Toast.makeText(getApplicationContext(), uri.getPath(), Toast.LENGTH_SHORT).show();
File test = new File(uri.getPath());
try {
fileInputStream = new FileInputStream(test);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileOutputStream outputStream = new FileOutputStream(folder, true);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This does not "select a file". It allows the user to choose a piece of content.
In onActivityResult(), if the result code is RESULT_OK, the Intent will have a Uri pointing to the selected piece of content. Use ContentResolver and openInputStream() to get an InputStream on that content. From there, do what you need to do, such as open a FileOutputStream to some file and then copy the bytes from the InputStream to the OutputStream.
BTW, ACTION_GET_CONTENT does not take a Uri as input. Replace setDataAndType() with setType().
I used this piece of code to get the image from the gallery and then crop the image before saving it. Its running up and nicely for android built in gallery but giving NullPointerException in onActivityResult method where we get extras.getParcelable("data") on using google photos app on android. Any help would be appreciated. Thanks in advance :D
//This is called in oncreate() on clicking the upload from gallery button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK , android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
galleryIntent.putExtra("crop", "true");
startActivityForResult(galleryIntent,PICK_FROM_FILE);
//This is called on onActivityResult() method
if (requestCode == PICK_FROM_FILE && data != null) {
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//do whatever with thePic
}
It worked for me.
//This is my onActivityResult method.
if (resultCode == RESULT_OK && data != null) {
final Uri selectedImage = data.getData();
String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
File createDir = new File(root + "AppName" + File.separator);
if (!createDir.exists()) {
createDir.mkdirs();
}
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyhhmmss");
String format = s.format(new Date());
File file = new File(root + "AppName" + File.separator + format);
if (!file.exists()) {
try {
file.createNewFile();
copyFile(new File(getRealPathFromURI(selectedImage)), file);
} catch (IOException e) {
e.printStackTrace();
}
}
String filePath = file.GetAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
mImageView.setImageBitmap(bmp);
}
And this is the copyFile method that i have used in this.
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
Hope it works for you as well :D
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