How to specify, which resource file to be used while running? - java

I wants my application to be in both Hindi and English language, so I have created a ResourceBundle named as Resources. In this directory I have create label.properties,label_en_US.properties and label_hi_IN.properties and these file have putted some values like ab=xy_default, ab=xy_in_en and ab=xy_in_hindi respectively.
And Now I planned to use them as label text, so in property of that label i mantioned the default one, like this
Here code is key and In label_defualt is code=Code : , in label_en_US code=Code : and in label_hi_IN code=कोड :. How can I specify which of label.properties to be useout of label, label_en_US or label_hi_in. I have stored user preference in my database like which language to use. I want to know how I can force or tell it use that particular file out of label, label_en_US, label_hi_IN in main function or somewhere else. As now it's taking values from label.properties file only, if user want it to be in hindi then how internally we force to use that label_hi_IN.properties file.

If you've got your files sorted out OK, the right internationalization should occur naturally depending on your locale. If you want to test other supported locales in your software, set the appropriate system properties:
java -Duser.country=IN -Duser.language=hi …
or
java -Duser.country=US -Duser.language=en …

ResourceBundle uses a “fallback” strategy. If the user’s current locale is hi-IN:
ResourceBundle.getBundle will look in label_hi_IN.properties (if that resource exists)
If that file is not found, ResourceBundle.getBundle will look for label_hi.properties (if that resource exists)
If that file is not found, ResourceBundle.getBundle will look for label.properties (if that resource exists)
This means you should do the following:
If label.properties contains English entries, remove label_en_US.properties from your project
If label.properties contains Hindi entries, remove label_hi_IN.properties from your project
Rename label_hi_IN.properties, if it is still present, to label_hi.properties, so all Hindi locales will use that file
Rename label_en_US.properties, if it is still present, to label_en.properties, so all English locales will use that file

Finally I got it, We have to just set Default Locale.
Locale locale = new Locale("hi","IN");
Locale.setDefault(locale);

Related

How to access XML files through the URL

I am a beginner in Struts 2 and I am stuck in an issue, I would like to access an .xml file in the project doc, when the user goes to the link www.sitename.com/sitemap.xml. But right now I can only access it by going to the URL www.sitename.com/sitemap, i.e. without the extension. When I specify the action name as sitemap.xml it does not work. How could I make the user access the URL www.sitename.com/sitemap.xml. Sorry If the question does not make any sense.
The standard extension in Struts 2 for action name is .action. But it's configurable via using a setting struts.action.extension. It's available in the default.properties, which is used by the default action mapper.
You might use a comma separated list, e.g. struts.action.extension=action,xml,whatsoever
The blank extension used to map directories treated as action names. Static content is mapped via specifying a blank extension, e.g. struts.action.extension=, or struts.action.extension=a,b,c,,, or struts.action.extension=a,,b,c.

Translate the Properties File from one language to another using ResourceBundle

I have message.properties file. by default it will load as English when I use Locale and Resource Bundle in Java file. Now, I need to specify the Country Code or Type in Locale, Then the message.properties file key values should be load as the specified Country in Locale. How can I do this.?
Oracle has some example code of this here.
Basically you create bundles with the correct name for the language of the Localeand then load it with:
ResourceBundle.getBundle("LabelsBundle", currentLocale);
More information about internationalization..
Also, before asking a question try googling for yourself....

Failed to check if file with German name is exist in the file system

Background:
I have 2 machines: one is running German windows 7 and my PC running English(with Hebrew locale) windows 7.
In my Perl code I'm trying to check if the file that I got from the German machine exists on my machine.
The file name is ßßßzllpoöäüljiznppü.txt
Why is it failed when I do the following code:
use Encode;
use Encode::locale;
sub UTF8ToLocale
{
my $str = decode("utf8",$_[0]);
return encode(locale, $str);
}
if(!-e UTF8ToLocale($read_file))
{
print "failed to open the file";
}
else
{
print $read_file;
}
Same thing goes also when I'm trying to open the file:
open (wtFile, ">", UTF8ToLocale($read_file));
binmode wtFile;
shift #_;
print wtFile #_;
close wtFile;
The file name is converted from German to utf8 in my java application and this is passed to the perl script.
The perl script takes this file name and convert it from utf8 to the system locale, see UTF8ToLocale($read_file) function call, and I believe that is the problem.
Questions:
Can you please tell me what is the OS file system charset encoding?
When I create German file name in OS that the locale is Hebrew in which Charset is it saved?
How do I solve this problem?
Update:
Here is another code that I run with hard coded file name on my PC, the script file is utf8 encoded:
use Encode;
use Encode::locale;
my $string = encode("utf-16",decode("utf8","C:\\TestPerl\\ßßßzllpoöäüljiznppü.txt"));
if (-e $string)
{
print "exists\r\n";
}
else
{
print "not exists\r\n"
}
The output is "not exists".
I also tried different charsets: cp1252, cp850, utf-16le, nothing works.
If I'm changing the file name to English or Hebrew(my default locale) it works.
Any ideas?
Windows 7 uses UTF-16 internally [citation needed] (I don't remember the byte order). You don't need to convert file names because of that. However, if you transport the file via a FAT file system (eg an old USB stick) or other non Unicode aware file systems these benefits will get lost.
The locale setting you are talking about only affects the language of the user interface and the apparent folder names (Programme (x86) vs. Program Files (x86) with the latter being the real name in the file system).
The larger problem I can see is the internal encoding of the file contents that you want to transfer as some applications may default to different encodings depending on the locale. There is no solution to that except being explicit when the file is created. Sticking to UTF-8 is generally a good idea.
And why do you convert the file names with another tool? Any Unicode encoding should be sufficient for transfer.
Your script does not work because you reference an undefined global variable called $read_file. Assuming your second code block is not enclosed in any scope, especially not in a sub, then the #_ variable is not available. To get command line arguments you should consider using the #ARGV array. The logic ouf your script isn't clear anyway: You print error messages to STDOUT, not STDERR, you "decode" the file name and then print out the non-decoded string in your else-branch, you are paranoid about encodings (which is generally good) but you don't specify an encoding for your output stream etc.

getBytes() With UTF-8 Doesn't Work for Upper-Case German Umlauts

For development I'm using ResourceBundle to read a UTF-8 encoded properties-file (I set that in Eclipse' file properties on that file) directly from my resources-directory in the IDE (native2ascii is used on the way to production), e.g.:
menu.file.open.label=&Öffnen...
label.btn.add.name=&Hinzufügen
label.btn.remove.name=&Löschen
Since that causes issues with the character encoding when using non-ASCII characters I thought I'd be happy with:
ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", Locale.getDefault());
String value = resourceBundle.getString(key);
value = new String(value.getBytes(), "UTF-8");
Well, it does work nicely for lower-case German umlauts, but not for the upper-case ones, the ß also doesn't work. Here's the value read with getString(key) and the value after the conversion with new String(value.getBytes(), "UTF-8"):
&Löschen => &Löschen
&Hinzufügen => &Hinzufügen
&Ã?ber => &??ber
&SchlieÃ?en => &Schlie??en
&Ã?ffnen... => &??ffnen...
The last three should be:
&Ã?ber => &Über
&SchlieÃ?en => &Schließen
&Ã?ffnen... => &Öffnen...
I guess that I'm not too far away from the truth, but what am I missing here?
Google found something similar, but that remained unanswered.
EDIT: a little more code
The problem is you're calling String.getBytes() without specifying an encoding - which will use the default platform encoding. You're then using the binary result of that operation as if it were in UTF-8.
If you use UTF-8 in both directions, it'll be fine:
// Should be a round-trip
value = new String(value.getBytes("UTF-8"), "UTF-8");
... but if you were trying to use this to read a UTF-8-encoded property file without telling the code which is performing the initial read, that won't work.
The code you've presented is basically always the wrong approach. Your "Since that causes issues with the character encoding" suggests that you'd already run across an earlier problem - so I'd go back to that, instead of trying to apply a broken fix. If you've already lost data when constructing the ResourceBundle, it's too late to go back later... you need to make sure the ResourceBundle itself is loaded correctly.
Please tell us exactly what problems you had with the ResourceBundle, and we can see if we can fix the root cause.
EDIT: It's not clear how you're running native2ascii. The fix may be as simple as changing to use:
native2ascii -encoding UTF-8 input.properties output.properties
Some notes:
If it is a String it is UTF-16 and if it isn't it is a corrupt string (and too late to fix.)
new String(value.getBytes(), "UTF-8"); - this code will (at best) do nothing on a system that uses UTF-8 as the default encoding; otherwise it will corrupt the string.
.properties files must be ISO 8859-1 (the Properties type supports other formats and encodings, but I don't know how you would tell ResourceBundle that.)
System.out can introduce its own transcoding bugs (the PrintStream encodes UTF-16 strings to the default encoding; the receiving device must decode the bytes using the same encoding.)
I suspect you are trying to fix your problems in the wrong place.
You are encoding the text with a different encoding to the one you are decoding with.
Try instead using the same character set for encoding and decoding.
value = new String(value.getBytes("UTF-8"), "UTF-8");
String s = "ßßßßß";
s += s.toUpperCase();
s = new String(s.getBytes("UTF-8"), "UTF-8");
System.out.println(s);
prints
ßßßßßSSSSSSSSSS
Today I was talking to one of my colleagues and he was pretty much on the same path as the other answers have mentioned. So I tried to achieve what Jon Skeet had mentioned, meaning creating the same file as in production. Since rebuilding the project after each change of a resource is out of question and I hadn't done any of what solved this (and I guess this will be new to some) let me line it out (even if it may be just for personal reference ;) ). In short this uses Eclipse' project builders.
Create an Ant-style build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
<property name="dir.resources" value="src/main/resources" />
<property name="dir.target" value="bin/main" />
<target name="native-to-ascii">
<delete dir="${dir.target}" includes="**/*.properties" />
<native2ascii src="${dir.resources}" dest="${dir.target}" includes="**/*.properties" />
</target>
</project>
Its intention is to delete the properties-files in the target directory and use native2ascii to recreate them. The delete is necessary as native2ascii won't overwrite existing files.
In Eclipse go to the project properties and select "Builders", click "New...", pick "Ant Builder" (that's the slightly enhanced editor for run configurations)
In "Main" let "Buildfile" point to the Ant-script, set "Base Directory" to ${project_loc}
In "Refresh" tick "Refresh resources upon completion" and pick "The project containing the selected resource"
In "Targets" click "Set Targets" next to the "Auto Build" and pick native-to-ascii there (note that for some reason I had to do this later again)
This might not be necessary for everybody, but in "JRE" pick a proper execution environment
In "Build Options" tick off "Allocate Console" (however, you may want to keep this ticked on until you see that it's all working)
"Apply", "OK"
I was told that the newly created builder should be somewhere underneath the Java Builder (use Up/Down-button)
In the "Java Build Path" select the source folder with the resources (src/main/resources for me) and add an exclusion for **/*.properties
That should have been it. If you edit a properties-file and save it, it should automatically be converted to ASCII in the output folder. You can try with entering ü, which should end up as \u00fc.
Note that if you have a lot of properties-files, this may take some time. Just don't save after every keypress. :)

Does Java provide some sort of Register\"Cookies" for storing of temporary data?

Does the Java provide some sort of registry- or cookie mechanism where I can store small pieces of data to load next start I start an java application- or applet?
For example the application settings such as last opened file etc
See the Java Preferences API.
It allows you to store preferences per-user and per-system. It'll store preferences in hidden files on Unix/Linux, and use the registry in Windows-based systems (although that's implementation-dependent).
Note: I'm not sure that it'll work with applets (due to security restrictions).
Java Properties are widely used both as persistence format (file) both in memory. They are also widely supported by tools like IDE, ant, maven, etc.
The class Properties is very simple to use and it has several useful method for your purpose (store, load and store):
Properties preferences = new Properties();
preferences.put("color", "red");
preferences.put("style", "bold");
preferences.store(new FileOutputStream("prefs.properties"), "preferences");
// reload the properties
Properties preferences = new Properties();
preferences.load(new FileInputStream("prefs.properties"));
A Java .properties file looks like:
# You are reading the ".properties" entry.
! The exclamation mark can also mark text as comments.
website = http://en.wikipedia.org/
language = English
# The backslash below tells the application to continue reading
# the value onto the next line.
message = Welcome to \
Wikipedia!
# Add spaces to the key
key\ with\ spaces = This is the value that could be looked up with the key "key with spaces".
# Unicode
tab : \u0009

Categories

Resources