Reputation: 11
I need to get the name of a CSV file selected for the user, but the getName()
method does not return any value.
This is the code
private void readCSV(Uri uri) {
InputStream is;
File file = null;
try {
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't work
is = new FileInputStream(file);
Why does this not return the name of the file?
Edit 1
private void readCSV(Uri uri) {
InputStream is;
File file;
try {
/*This conditional is false*/
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't
is = new FileInputStream(file);
} else {
/* this part is the one that runs */
is = this.getContentResolver().openInputStream(uri);
Log.i("File selected: ", uri.getLastPathSegment()); //i tried this, it returns me 5049 but it is not the name of the selected file
}
Upvotes: 1
Views: 1287
Reputation: 1535
Getting file names through the apachecommons io lib https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
String name = FileNameUtils.getName(uri.getPath());
Upvotes: 0
Reputation: 43
uri.toString()
will return the object reference but not the file path.
You should call uri.getPath()
Upvotes: 2
Reputation: 62419
Use
new File(uri.getPath());
instead of
new File(uri.toString());
NOTE: uri.toString()
returns a String in the format: "file:///mnt/sdcard/image.jpg"
, whereas uri.getPath()
returns a String in the format: "/mnt/sdcard/image.jpg"
.
Upvotes: 1