简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM