Copy file from one folder to another - java

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

Related

How to upload a video to parse server?

#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selected = data.getData();
File file = new File(String.valueOf(selected));
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[(int) file.length()];
try {
for (int readnum; (readnum = fis.read(buf)) != -1; ) {
bos.write(buf, 0, readnum);
}
} catch (Exception e) {
e.printStackTrace();
}
byte[] bytes = bos.toByteArray();
ParseFile parseFile =new ParseFile("video.mp4",bytes);
ParseObject parseObject = new ParseObject("video2");
parseObject.put("video2", parseFile);
parseObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(userlist.this, "video has been uploaded successfully :)", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(userlist.this, "sorry we could't upload the video ", Toast.LENGTH_SHORT).show();
}
}
});
}
This is my current code. I managed to access the phone gallery and then I convert the video to byte array to be able to upload it to Parse but i guess the problem is that any video i choose returns null i access the gallery using this code :
public class userlist extends AppCompatActivity {
public void getphoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
here is my stack trace
java.io.FileNotFoundException: content:/media/external/video/media/14146 (No such file or directory)
2020-07-05 17:28:03.965 31930-31930/com.parse.starter W/System.err: at com.parse.starter.userlist.onActivityResult(userlist.java:85)
2020-07-05 17:28:03.967 31930-31930/com.parse.starter W/System.err: at com.parse.starter.userlist.onActivityResult(userlist.java:92)
2020-07-05 17:28:03.981 31930-32065/com.parse.starter W/System: Ignoring header Content-Type because its value was null.

How to fix my "FileNotFoundException"(No such file or directory) error with Uri-Path in Android-Studio?

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

Opening a file present in assets folder using an intent

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.

Opening a downloaded file and copying it

I am trying to open a file I demand from my user to download so I can use it so I am trying to copy it to my internal storage.
I tried using this code:
Intent myIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
myIntent.setType("text/*");
myIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(myIntent, 100);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
Uri result= data.getData();
Log.e("fag", result.getPath());
copyFile(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
Log.e("", "canceled");
}
}
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
}
private void copyFile(Uri inputFile) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(inputFile.getPath());
out = openFileOutput(NAME , MODE_PRIVATE);
byte[] buffer = new byte[1024];
while ( in.read(buffer) != -1) {
out.write(buffer);
}
in.close();
in = null;
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
fnfe1.printStackTrace();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
But when I run this code, I got a File Not Found Exception. so I checked what URI I get from the intent and it isn't the path to the file but this path
/document/primary:Download/5643_05072018-13-48.csv
and I don't know how to use this URI.
I got a simmmilar resualt using the ACTION_GET_CONTENT intent.
So my question is can I use this code and the URI that I got to copy that file or I need to do it in an other way? and how in both cases?
in = new FileInputStream(inputFile.getPath());
Change to:
InputStream is = getContentResolver().openInputStream(inputFile);
And dont name that inputFile but uri.

Copy existing png file and rename programmatically

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

Categories