Converting a File:///... string to an Absolute URI - java

So I am making an app that lets users pick images from their gallery to display, as well as take photos from the camera.
The image is previewed via a bitmap that takes the string of the file path. When the user takes a photo the code below handles it (and works):
String path = mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"
File pictureFile = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
image1.setImageBitmap(bitmap);
The path is of the format like this:
/storage/emulated/0/Pictures/App/IMG_20150512_130719.jpg
However when I try to select from my library, my code is setup so that the string I am returning formatted like this:
file:////storage/emulated/0/Pictures/App/IMG_20150512_130719.jpg
Now obviously I can (and currently am) split the string and get the path to match the above, but I am curious if there is a standard way to convert between these to?
I saw Uri.parse() but that doesn't work because that returns a URI and I want a String that I can make a file from and then get the absolute path.
If you have a clean suggestion on how I can move from the file://// string to the / string I'm all ears.
Thanks

Converting from file uri to file path:
String fileUri = "file:///storage/emulated/0/";
String filePath = Uri.parse(fileUri).getPath();
Converting from file path to file uri:
String filePath2 = "/storage/emulated/0/";
String fileUri2 = Uri.fromFile(new File(filePath2)).toString();

Related

unable to get relative path to absolute path in java

Im giving the path of the image to properties file and getting the path to Image class in my pdfGenerating class. like:
properties.load(DownloadPdf.class.getResourceAsStream("/resource.properties"));
System.out.println("--properties----"+properties);
System.out.println("-path-"+properties.getProperty("logoPath"));
//String path = properties.getProperty("logoPath");
//URL uri = Paths.get(path).toUri().toURL();
System.out.println("---path-"+properties.getProperty("logoPath"));
Image image = Image.getInstance(properties.getProperty("logoPath"));
Here my logopath is:
path----------------C:/Users/Home/Documents/workspace-gofindo/.metadata/.plugins/org.eclipse.wst.server.core/.....
But i'm getting the path in
Image.getInstance(properties.getProperty("logopath"));
like
C:\Users\Home\Documents\workspace-gofindo\.metadata\.plugins\org.
I have tried with replace and replaceAll() methods to convert '\' to '/'
again the image class converting into '\'.
How to get my absolute path which i have specified in properties file exactly into Image.getInstance() method
I have remodified the way i can read the path of the file like below.
// Load path of the Image from Properties file
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream(
"/resource.properties"));
// To get the Path of the Context
String contextPath = request.getContextPath();
String split_path[] = contextPath.split("/");
contextPath = request.getRealPath(split_path[0]);
Image image = Image.getInstance(contextPath
+ properties.getProperty("logoPath"));
image.scaleAbsolute(120f, 60f);// image width,height

Get character from string between similar sings

I am trying to get a path of an image in my android device, such as:
/ storage/emulated/0/DCIM/Camera/NAME.jpg
and just trying to grab the image name, but i can.
I am trying with ...
String s = imagePath;
Where the route imagePath
            
s = s.substring (s.indexOf ("/") + 1);
s.substring s = (0, s.indexOf () ".");
Log.e ("image name", s);
it returns me :
storage/emulated/0/DCIM/Camera/NAME.jpg
and i only want
NAME.jpg
You need String.lastIndexOf():
String imagePath = "/path/to/file/here/file.jpg";
String path = imagePath.substring(imagePath.lastIndexOf('/') + 1);
You can do something like that:
File imgFile = new File(imagePath);
String filename = imgFile.getFilename();
This saves you a lot of hassle when you want to use your application cross-platform, because on Linux you have "/" as path delimiters and "\" on Windows
In case, if you are dealing with File object, then you can use its predefined method getName().
i.e.:
File mFile = new File("path of file");
String filename = mFile.getName();

extracting filename with extension form URL

Let's say I have the following string
http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png
What would be the best way to extract b84.png from it? My program will be getting a list of image URLs and I want to extract the file name with its extension from each URL.
I would recommend using URI to create a File like this:
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
URI uri = URI.create(url);
File f = new File(uri.getPath());
The uri.getPath() returns only the path portion of the url (i.e. removes the scheme, host, etc.) and produces this:
/photos/images/original/000/748/132/b84.png
You can then use the created File object to extract the file name from the full path:
String fileName = f.getName();
System.out.println(fileName);
Output of print statement would be:
b84.png
However if you are not at all concerned by the input format of the url(s) then the substring answers are more terse. I figured I would offer an alternative. Hope it helps.
Try,
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String fileName = url.subString(url.lastIndexOf("/")+1);
String[] urlArray=yourUrlString.split("/");
String fileName=urlArray[urlArray.length-1];
I think, string lastIndexOf method is the best way to extract file name
String str = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String result = str.substring(str.lastIndexOf('/')+1,str.length());
The method perfect for you
public String Name(String url){
url=url.replace('\\', '/');
return url.substring(url.lastIndexOf('/')+1,url.length());
}
this method returns any filename of any directory...whitout errors because convert the "\" to "/" so never will have problems with diferent directories
You can try this-
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png"
url = url.substring(url.lastIndexOf("."));
If you don't png instead of .png, just change the last line to this-
url = url.substring(url.lastIndexOf(".") + 1);

Get Uri from file in either assets or res/raw

I have tried to get this working and I have looked at many different resources online (as you can see from all of the comments I have made). I want to access a .pdf file that is either located in assets or res; It does not matter to which one so the easiest way will do.
I have the method below that will get the actual file and will call another method(under the first method below) with the Uri in the parameters.
Thank you very much for your help and I will be standing by to answer questions or add more content.
private void showDocument(File file)
{
//////////// ORIGINAL ////////////////////
//showDocument(Uri.fromFile(file));
//////////////////////////////////////////
// try 1
//File file = new File("file:///android_asset/RELATIVEPATH");
// try 2
//Resources resources = this.getResources();
// try 4
String PLACEHOLDER= "file:///android_asset/example.pdf";
File f = new File(PLACEHOLDER);
//File f = new File("android.resource://res/raw/slides1/example.pdf");
//getResources().openRawResource(R.raw.example);
// try 3
//Resources resources = this.getResources();
//showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));
showDocument(Uri.fromFile(f));
}
protected abstract void showDocument(Uri uri);
from link & Get URI of .mp3 file stored in res/raw folder in android
sing the resource id, the format is:
"android.resource://[package]/[res id]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);
or, using the resource subdirectory (type) and resource name (filename without extension), the format is:
"android.resource://[package]/[res type]/[res name]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");
If you do not know the ID of your resource, but just the name, you can use the getIdentifier(...) method of the Android Resouces object. You can retrieve the latter using the getResources() of your application context.
If, for example, your resource is stored in the /res/raw folder:
String rawFileName = "example" // your file name (e.g. "example.pdf") without the extension
//Retrieve the resource ID:
int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
if ( resID == 0 ) { // the resource file does NOT exist!!
//Debug:
Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");
return;
}
//Read the resource:
InputStream inputStream = context.getResources().openRawResource(resID);
Very Helpful post.
Here's an alternative: Work with a FileDescriptor instead of the Uri, where possible.
Example: (In my case its a raw audio file)
FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();
this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);

url = new java.net.URL()

url = new java.net.URL(s) doesn't work for me.
I have a string C:\apache-tomcat-6.0.29\webapps\XEPServlet\files\m1.fo and need to make a link and give it to my formatter for output, but malformed url recieved. It seems that it doesn't make my string to url.
I want also mention, that file m1.fo file is in files folder, in my webapp\product\, and I gave the full path to string like: getServletContext().getRealPath("files/m1.fo"). What I am doing wrong? How can I recieve the url link?
It is possible to get an URL from a file path with the java.io.File API :
String path = "C:\\apache-tomcat-6.0.29\\webapps\\XEPServlet\\files\\m1.fo";
File f = new File(path);
URL url = f.toURI().toURL();
Try: file:///C:/apache-tomcat-6.0.29/webapps/XEPServlet/files/m1.fo
It isn't preferable to write file:/// . Indeed it works on windows system,but in unix - there were problems.
Instead of using
myReq.put("xml", new String []{"file:" + System.getProperty("file.separator") +
getServletContext().getRealPath(DESTINATION_DIR_PATH) +
System.getProperty("file.separator") + xmlfile});
you can write
myReq.put("xml", new String [] {getUploadedFileURL (xmlfile)} );
, where
public String getUploadedFileURL(String filename) {
java.io.File filePath = new java.io.File(new
java.io.File(getServletContext().getRealPath(DESTINATION_DIR_PATH)),
filename);
return filePath.toURI().toURL().toString();
A file system path is not a URL. A URL is going to need a protocol prefix for one. To reference file system use "file:" in front of your path.

Categories

Resources