I'm trying to upload a file by copying it from mobile app to server app running on windows. I used a file chooser to let the user select the file:
public void openFile(View view) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select file"), LEARN_TREE);
}
Then i got the uri from the intent of onActivityResult. First question here is why it displays a file named "servo.dat" as numbers (in this case it shows "5889")?
After that I put the uri as an extra into another intent and use that intent to start another activity. In the second activity I retrieve the uri. Now I'd like to use FileInputStream to read bytes from my file in order to write them to the ObjectOutputStream created from Socket.getOutputStream(). Here is where it doesn't work. Basically the path provided here
FileInputStream fis = new FileInputStream(uri.getPath());
is incorrect. If I check on my device the file location is Download/servo.dat, the Uri in the app shows Download/5889 and the absolute path that I tried retrieving using a UriUtils library found online shows storage/emulated/0/Download/servo.dat but this one doesn't actually exist on my phone.
I think it's not so hard but I'm getting confused since I'm new to both Android app development and Android itself, please help!
I'm open to any good solution, I saw online there is the ContentResolver class that should be helpful but I didn't manage to understand how to use it :|
First question here is why it displays a file named "servo.dat" as numbers (in this case it shows "5889")?
Because it is not a file. It is a piece of content, and you are attempting to treat the path portion of a Uri
as a filesystem path, which is is not.
If you want a display name for the content:
DocumentFile.fromSingleUri()
, passing in your Uri
, to create a DocumentFile
getDisplayName
on the DocumentFile
Basically the path provided here is incorrect
That is because you are trying to treat the path portion of a Uri
as a filesystem path, which it is not.
To get an InputStream
, call openInputStream()
on a ContentResolver
, passing in your Uri
. See the documentation. So, for example, from a method in an Activity
, you would use InputStream inputStream = getContentResolver().openInputStream(uri);
.
I'm getting confused since I'm new to both Android app development and Android itself
You may wish to consider reading a book on Android app development or taking a course in Android app development.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments