Directly from this API:
Otherwise, getBundle attempts to locate a property resource file using
the generated properties file name. It generates a path name from the
candidate bundle name by replacing all "." characters with "/" and
appending the string ".properties". It attempts to find a "resource"
with this name using ClassLoader.getResource.
What do they mean with replacing all "." characters with "/" What would be an example?
PS:I am ok with appending .properties at the end.
Say you have a package named
com.yourgroup.bundles
containing a file named
hello_en_US.properties
you would have to specify either of the following to load a bundle
ResourceBundle bundle = ResourceBundle.getBundle("com.yourgroup.bundles.hello");
ResourceBundle bundle = ResourceBundle.getBundle("com/yourgroup/bundles/hello");
Basically the javadoc is telling you how it translates the argument you pass to the getBundle method to find the resource on your classpath. For me, the default Locale is en_US, so
com.yourgroup.bundles.hello
translates to
com/yourgroup/bundles/hello_en_US.properties
It can then use the ClassLoader to find that resource.
The ResourceBundle implementation it returns might actually be a custom class, if you map its name correctly. Follow the javadoc for that. Otherwise, it's just a Properties resource bundle.
The magic happens in ResourceBundle#newBundle(...)
String bundleName = toBundleName(baseName, locale); // baseName being 'com.yourgroup.bundles.hello' in my example above
...
final String resourceName = toResourceName(bundleName, "properties");
and that is simply
public final String toResourceName(String bundleName, String suffix) {
StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
return sb.toString();
}
....
URL url = classLoader.getResource(resourceName);
...
bundle = new PropertyResourceBundle(stream); // stream comes from url
Related
I have a bit problem, and i dont seem to understand what is causing it.
i have a folder in my project, and in that folder i have a class, and i have a resource file (in this case jasper report).
but the only way i can access file is with absolute path or some path that starts from root of my project.
String path = "src/main/java/Views/LagerMain/lager.jrxml";
^^this works, both my class LagerController and lager.jrxml are under LagerMain folder, but when i try to do this :
String path = "lager.jrxml";
i have an error that file is not found.
I tried googling this to have a better understanding but i found nothing.
Bottom line, why cant i access my file, from class when they are both on same place, why does not relative path work.
If the main class is in a different directory, then the program will try to accesslager.jrxml there instead of the directory of the regular class.
For regular-class directory:
String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");
If that doesn't work, try this:
// your directory
File f = new File("src");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("lager") && name.endsWith("jrxml");
}
});
If you have more than one file with the name lager.jrxml, then this method will return both of them and you will need to use a for to cycle through them. Otherwise, you can just use
String path = new String(matchingFiles[0].getAbsolutePath())
For main-class directory:
String path = new String(System.getProperty("user.dir")
+ System.getProperty("line.separator") + "lager.jrxml");
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);
I am wondering if it is possible to assign a String Variable the path of the file? If Yes, then is it possible to update the File Dynamically?
I am trying to create Files dynamically (which I am able to do so), but I want to link these dynamically created files to a String variable.
Please help. Thanks in advance.
File dir = new File("Data");
if(!dir.exists()){
dir.mkdir();
}
String filename = "file1";
File tagfile = new File(dir, filename+".txt");
if(!tagfile.exists()){
tagfile.createNewFile();
}
System.out.println("Path : " +tagfile.getAbsolutePath());
String s = new File("xyz.txt").getAbsolutePath();
or
String s = new File("xyz.txt").getCanonicalPath();
Both of the above assign (in my case) c:\dev\xyz.txt to the string s.
To get the full system path windows or linux
public static void main(String []args){
String path = "../p.txt";//works on windows or linux, assumes you are not in root folder
java.io.File pa1 = new java.io.File (path);
String s = null;
try {
s = pa1.getCanonicalFile().toString();
System.out.println("path " + s);
} catch (Exception e) {
System.out.println("bad path " + path);
e.printStackTrace();
}
Prints out full path like c:\projects\file\p.txt
Here is the code to do that:
File file = new File("C:\\testfolder\\test.cfg");
String absolutePath = file.getAbsolutePath();
This is what javadoc says about the getAbsolutePath API:
getAbsolutePath
public String getAbsolutePath() Returns the absolute pathname string
of this abstract pathname. If this abstract pathname is already
absolute, then the pathname string is simply returned as if by the
getPath() method. If this abstract pathname is the empty abstract
pathname then the pathname string of the current user directory, which
is named by the system property user.dir, is returned. Otherwise this
pathname is resolved in a system-dependent way. On UNIX systems, a
relative pathname is made absolute by resolving it against the current
user directory. On Microsoft Windows systems, a relative pathname is
made absolute by resolving it against the current directory of the
drive named by the pathname, if any; if not, it is resolved against
the current user directory.
Returns: The absolute pathname string denoting the same file or
directory as this abstract pathname
I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);
public static void loadFilters() throws MalformedURLException {
File filtersFile = new File(CONFIG_DIR + "/" + FILTERS_FILE);
URL[] urls = {filtersFile.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle bundle = ResourceBundle.getBundle(FILTERS_BASE, Locale.getDefault(), loader);
if (StringUtils.isNotBlank(getStringValue(bundle, ALLOW_TYPE_PATTERN_KEY))) {
ALLOWED_TYPES = Pattern.compile(getStringValue(bundle, ALLOW_TYPE_PATTERN_KEY));
}
if (StringUtils.isNotBlank(getStringValue(bundle, DENY_TYPE_PATTERN_KEY))) {
DENIED_TYPES = Pattern.compile(getStringValue(bundle, DENY_TYPE_PATTERN_KEY));
}
ALLOWED_MIME_TYPES = getListValue(bundle, ALLOW_MIME_PATTERN_KEY);
DENIED_MIME_TYPES = getListValue(bundle, DENY_MIME_PATTERN_KEY);
}
I am trying to load properties file using resource bundle kept outside the code in a separate directory. But when I try to do this way(above code) I am getting error as
ERROR [main] Can't find bundle for base name filters, locale en_US
And If I am keeping this file filters.properties in src/main/resources folder then this code is working fine... but when I keep it outside it doesn't works.. Don't know why..
And CONFIG_DIR contains \my\dir\conf and FILTERS_FILE contains filters.properties file.
FILTERS_FILE has value filters.properties and FILTERS_BASE has value filters and urls got the value as [file:/C:/my/dir/conf/filters.properties]
And filters.properties file is in /my/dir/conf/filters.properties
Try having the file point to the directory rather than the actual properties file. So just change the first statement of that method to
File filtersFile = new File(CONFIG_DIR + "/");
If FILTERS_BASE contains filters, that should be enough. You don't need the full filters.properties name since the .properties prefix is appended by the getBundle method.