I have a png file in a folder "Movies" on the sdcard. I want to copy and rename that file in the same folder. I'm confused on how to properly call the method SaveImage.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
isbn = scanningResult.getContents();
SaveImage();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private void SaveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Movies/");
String fname = "Image-"+ isbn +".jpg";
File file = new File (myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I simply want to duplicate the same file and rename it
Thanks for making it more clearly. You can use this to copy from source file to destination file.
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();
}
So your question is, how to properly call your SaveImage(Bitmap finalBitmap) method, right ? as your SaveImage method get a Bitmap as parameter you need to send it a Bitmap as parameter.
You can use BitmapFactory to create a Bitmap object from your file and send this Bitmap object to your SaveImage method :
String root = Environment.getExternalStorageDirectory().toString();
Bitmap bMap = BitmapFactory.decodeFile(root + "/Movies/myimage.png");
SaveImage(bMap);
Rename file:
File source =new File("abc.png");
File destination =new File("abcdef.png");
source.renameTo(destination);
Copy File:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path source=Paths.get("abc.png");
Path destination=Paths.get("abcdef.png");
Files.copy(source, destination);
Related
I am trying to create an app which downloads and plays music. For stopping users from copying the music files, I want to encrypt the file as soon as it is downloaded. I am struggling with the code for days, but cannot find out what is causing the errors. Here is the relevant code -
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadID == id) {
Toast.makeText(DownloadActivity.this, "Download completed", Toast.LENGTH_SHORT).show();
Context appContext = getApplicationContext();
MasterKey mainKey = new MasterKey.Builder(appContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
String fileToWrite = songName + ".mp3";
EncryptedFile encryptedFile = new EncryptedFile.Builder(context,
new File(getExternalFilesDir(null), fileToWrite),
mainKey,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
byte[] fileContent = convert(getExternalFilesDir(null).getAbsolutePath() + "/" + songName + ".mp3");
OutputStream outputStream = encryptedFile.openFileOutput();
outputStream.write(fileContent);
outputStream.flush();
outputStream.close();
}
}
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1;) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
}
I also wrap the necessary lines with try-catch. Removed it here for simplifying the code.
Also, I will be very grateful if I could get advice on what is the best way to play encrypted audio files, while keeping them safe. Is creating temporary file for playing a good option?
I'm trying to copy the file as the Android path comes, without success, although it already existed as permissions on AndroidManifest, it's as if the file did not exist or know it there.
Here's a piece of code:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String origem = uri.getPath();
File src = new File(origem);
if(src.isFile()){
Log.d(TAG,src.toString());
}
File root = Environment.getExternalStorageDirectory();
root = new File(root.toString(), "Kcollector/importa/import.csv");
try {
copy(src,root,true);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static void copy(File origem, File destino, boolean overwrite) throws IOException{
Date date = new Date();
if (destino.exists() && !overwrite){
System.err.println(destino.getName()+" já existe, ignorando...");
return;
}
FileInputStream fisOrigem = new FileInputStream(origem);
FileOutputStream fisDestino = new FileOutputStream(destino);
FileChannel fcOrigem = fisOrigem.getChannel();
FileChannel fcDestino = fisDestino.getChannel();
fcOrigem.transferTo(0, fcOrigem.size(), fcDestino);
fisOrigem.close();
fisDestino.close();
Long time = new Date().getTime() - date.getTime();
System.out.println("Saiu copy"+time);
}
The error that returns me when trying to copy:
W/System.err: java.io.FileNotFoundException: /external_storage/Kcollector/importa/kvendasajustado.csv (No such file or directory)
W/System.err: at java.io.FileInputStream.open0(Native Method)
check the runtime permissions or use the method indicated in the first response
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
Finally check the url if is formed good.
Otherwise you can de bug with a breakpoint(search these words), and find exactly where the problem comes from
I am writing an App to save files (pictures) as a certain name given by a column from csv-file. The user have to choose the csv with the filebrowser first and then the file will be copyied to my Dir-Data directory.
Everything worsk fine but it seems like the Path i get form the File src Object doesn't work with the Operation.
I expect the error obviously here(2nd Code-Box)
And sry in advance if it is obvious/easy to avoid, it is my first Android-Project ever.
I already tryed to use different Copy Functions with different parameter types and also tryed other formats such as String given by uri.toString().
//CSV Opener
public void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened"
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only .csv using the image MIME data type.
// For all it would be "*/*".
intent.setType("text/comma-separated-values");
startActivityForResult(intent, READ_REQUEST_CODE);
}
//create paths
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if (resultData != null) {
Uri path = resultData.getData();
stringUri = path.getPath();
File src = new File(stringUri);
File destination = new File(getFilesDir().getPath());
try {
copyDirectoryOneLocationToAnotherLocation(src,destination);
}
catch(IOException e) {
e.printStackTrace();
System.out.print("error in upload");
}
Toast.makeText(MainActivity.this, "Path: "+stringUri , Toast.LENGTH_SHORT).show();
}
}
}
//copy-operation from StackOverflow
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
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();
}
}
I want the choosen file to be copied in my data/data/... directory to be used later in the App.
BUT: the path i get from the objets doesn`t work for me
Thx #Mike M. , the tip with using getContentResolver() brougth me the anwser after trying around.
Finally is used an other Copy funktion and reworked the onActivityResult();
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if (resultData != null) {
try {
String destination = getFilesDir().getPath();
InputStream src = getContentResolver().openInputStream(resultData.getData()); // use the uri to create an inputStream
try {
convertInputStreamToFile(src, destination);
} catch (IOException e) {
e.printStackTrace();
System.out.print("error in upload");
}
} catch (FileNotFoundException ex) {
}
String destination = getFilesDir().getPath();
Toast.makeText(MainActivity.this, "Success!: CSV-File copyed to : " +destination , Toast.LENGTH_SHORT).show();
}
}
}
public static void convertInputStreamToFile(InputStream is, String destination) throws IOException
{
OutputStream outputStream = null;
try
{
File file = new File(destination + "/Student.csv");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
finally
{
if(outputStream != null)
{
outputStream.close();
}
}
}
Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
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);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.
I'm trying to obtain the filepath of my stored Image that's stored like so after using the ACTION_IMAGE_CAPTURE intent:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageOne.setImageBitmap(imageBitmap);
SaveImageOne(imageBitmap);
}
SaveImageFunction
private void SaveImageOne(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-1.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This way I can store this 'filepath' of the stored File to SharedPreferences to be accessed later on and say passed into the ACTION_SEND as an image attachment.
after this line out.close(); write this line
String pathString = file.getAbsolutePath(); // gives you the path of the file
now use it how you want it