I am trying to run the below sample code in java.
import java.util.Locale;
import java.util.ResourceBundle;
public class InternationalizationDemo {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.CANADA_FRENCH);
System.out.println("Message in "+Locale.CANADA_FRENCH +":"+bundle.getString("greeting"));
}
}
1.The above code executes properly when MessageBundle.properties is placed in the class path.
But I want to execute the above code successfully by removing the MessageBundle.properties from the classpath and placing it in some other location.
How can I do this?
Thanks in Advance.
You could use PropertyResourceBundle and get the path of your properties file from a System property for example something like that:
String configPath = System.getProperty("config.path");
ResourceBundle bundle = new PropertyResourceBundle(new FileReader(configPath));
Then in your launch command you will need to add -Dconfig.path=/path/to/my/config.properties
You can load properties file externally by this:
// Path to your file, if you have it on local, use something like C:\\MyFolder or \home\usr\etc
File file = new File("YOUR_PATH");
URL[] url = {file.toURI().toURL()};
ResourceBundle rb = ResourceBundle.getBundle("MessageBundle", Locale.CANADA_FRENCH, new URLClassLoader(url));
Example is from here: https://coderanch.com/t/432762/java/java/absolute-path-bundle-file
You are able to use remote Properties file or file which is saved on local.
Related
In Eclipse, my directory structure is this:
-src
-com.xxx.yyy
- MyClass.java
-assets
- car.txt
MyClass.java looks like this :
public class MyClass {
private static String FILE_PATH = "../assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
...
}
}
I this by default, the classpath is src/, so I point to my car.txt file by ../assets/car.txt. But I get :
java.io.FileNotFoundException: ../assets/car.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
Why ?
Relative file paths a relative to the execution, assuming that the program is executed in the same location as the src and assets directory, then the path should be assets/car.txt
You can check the current execution location using System.out.println(new File(".").getCanonicalPath());
Whe you run the program it is compiled to the parent folder of the src folder as far as I know. You should better add the assets folder to your build path and access the file using getClass().getResource[AsStream]().
To add the folder do the following:
Right click on your project
Click Build Path
Choose Configure Build Path
Select Source
Click Add Folder...
Select your assets folder
Inside your code you can either call it with MyClass.class.getResource[AsStream]() or getClass().getResource[AsStream]().
getResource() returns an URL and getResourceAsStream() an InputStream. Both methods expect a path as parameter. Check the docs for more information.
Your path is incorrect
Since you are inside com.xxx.yyy, you are inside three folders. You need to get out of all of them.
So you can use, the relative path as
FILE_PATH = "../../../assets/car.txt";
As src is a source folder, all the contents come directly in the classpasth, you can also use
FILE_PATH = "assets/car.txt";
You are in second level in directory structure.
Try
FILE_PATH = "../../assets/car.txt";
Hope, this will help you...
package com.xxx.yyy;
import java.io.File;
import java.io.FileInputStream;
public class MyClass {
private static String FILE_PATH = "src/assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
catch (Exception e){
e.printStackTrace();
}
}
}
Ankit Lamba 's suggestion works: that's using String FILE_PATH = "assets/car.txt";
I have a FileInputStream in a class in the package com.nishu.ld28.utilities, and I want to access sound files in the folder Sounds, which is not in the com.nishu.ld28 package. I specify the path for loading like so:
"sounds/merry_xmas.wav"
And then try to load it like this:
new BufferedInputStream(new FileInputStream(path))
When I export the jar, the command line prompt that I run it through says it can't find the file. I know how to access the files when I am running the program in Eclipse, but I can't figure out how to point the FileInputStream to the Sounds folder when I export it.
Edit: As requested, here's my code:
public void loadSound(String path) {
WaveData data = null;
data = WaveData.create(GameSound.class.getClassLoader().getResourceAsStream(path));
int buffer = alGenBuffers();
alBufferData(buffer, data.format, data.data, data.samplerate);
data.dispose();
source = alGenSources();
alSourcei(source, AL_BUFFER, buffer);
}
WaveData accepts an InputStream or other types of IO.
You don't need a FileInputStream, because you aren't reading from the filesystem. Use the InputStream returned by ClassLoader.getResourceAsStream(String res) or Class.getResourceAsStream(String res). So either
in = ClassLoader.getResourceAsStream("sounds/merry_xmas.wav");
or
in = getClass().getResourceAsStream("/sounds/merry_xmas.wav");
Note the leading slash in the second example.
I would put the com.nishu.ld28.utilities in the same package of your class , let's call it MyClass.
Your package:
Your code:
package com.nishu.ld28.utilities;
import java.io.InputStream;
public class MyClass {
public static void main(String[] args) {
InputStream is = MyClass.class.getResourceAsStream("sound/merry_xmas.wav");
System.out.format("is is null ? => %s", is==null);
}
}
Output
is is null ? => false
I am adding email sending capability to my web app. SMTP server settings will be read from a java.util.Properties file. I wouldn't like to hardcode path to this file.
Where should I keep this file?
How should I access this file?
A good pattern to follow is to keep your static resources (like property files) under your WEB-INF/classes/ directory.
That way they can be read from the classpath and not accessed by the browser:
for example, put your settings file under WEB-INF/classes/mail-settings.properties, and use the following to read it:
InputStream is = MyClass.class.getResourceAsStream("mail-settings.properties");
Properties p = new Properties();
p.load(is);
is.close();
Keep property file in classpath location like in folder : WEB-INF/classes/mail.properties
Here property file is - mail.properties. To read this file you can use below code
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class EmailPropertyReader {
private static ResourceBundle myResources;
public static String FILENAME = "mail";
static{
initialize(FILENAME);
}
public static void initialize(String propertyFile) throws MissingResourceException
{
try{
myResources = ResourceBundle.getBundle(FILENAME, Locale.getDefault());
}catch(Exception ex){
//Logger
}
}
private static String getParameter(String parmName)
{
String param = null;
try
{
param = myResources.getString(parmName) ;
}catch(Exception e){
param = null;
//Logger
}
if (param != null)
return param.trim();
else
return param;
}
}
You just create object and enter code here use method getParameter() ->
For example:
mail.properties :
EMAILID=a#a.com
then
String strEmailid=EmailPropertyReader.getParameter("EMAILID");
if you want to keep it with your code you may just as well create the Properties instance programmatically.
Properties mailProperties = new Properties();
mailProperties.setProperty("mail.transport.protocol", "smtp");
mailProperties.setProperty("mail.smtp.host", "localhost");
mailProperties.setProperty("mail.smtp.port", "587");
mailProperties.setProperty("mail.smtp.auth", "false");
javax.mail.Session.getInstance(mailProperties);
If you want to have it in a properties file anyway you can load it as a classpath resource. Have a look at getResourceAsStream in java.lang.Class. Update: see epochs answer for how to do this!
Here is a solution:
I have placed EmailSettings.properties file into WebContent\WEB-INF\classes. This code now works:
InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream("EmailSettings.properties");
Properties emailConfig = new Properties();
emailConfig.load( inputFile );
.
.
.
If the settings are stage dependent ,you could set the path to the File via a vm Enviorment varibable.
-DmyPropertyFilePath=....
Also there is a good artikel about loading property files (even so it is a bit Dated) on Java World
suppose I put a file a.txt in package com.xyz and the try access it like following. Will it work?
Hi All,
import com.xyz.*;
public class Hello
{
File f = new File("a.txt");
...
}
It is not working for me. Is there any workaround?
Use Class.getResource() or Class.getResourceAsStream(). see for example the Sun demo source at http://jc.unternet.net/src/java/com/sun/WatermarkDemo/WatermarkDemo.java
I will offer the same answer as jcomeau_ictx, but a lot shorter (around 30 lines in one file as opposed to >380 in 1 source file of 5), ..and with a screenshot. ;)
import javax.swing.*;
import java.net.URL;
class GetResource {
GetResource() {
Class cl = this.getClass();
final URL url = cl.getResource( cl.getName() + ".java" );
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JEditorPane ep = new JEditorPane();
try {
ep.setPage(url);
JScrollPane sp = new JScrollPane(ep);
sp.setPreferredSize(new java.awt.Dimension(400,196));
JOptionPane.showMessageDialog(null, sp);
} catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
e.getMessage() + " See trace for details.");
}
}
});
}
public static void main(String[] args) {
new GetResource();
}
}
Based on your responses to the comments above. If you are looking for a work around, just specify the path to the .txt file on the file system. Putting it in a package does not help.
new File ("a.txt")
looks for a file on the the file system and not within a package.
Please also read the javadocs on File:
http://download.oracle.com/javase/6/docs/api/java/io/File.html
However I do not see the rationale in putting the file inside a package unless you would want to use it as a resource. In which case #jcomeau_ictx has the right solution
It's depend on your class path of java from where you can run this class. If both are in same place then it will work. Then no need to define path in file. But the file was not in the classpath dir then must be define path of that file otherwise file not found.
This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 7 years ago.
I am using servlets where I hard-code the database connection details, so if make any change I have to recompile the code. So instead I'd like to use a .properties file (which I can modify later) and use that as the source for my database connection.
The problem is I don't know how to read the property file. Could someone please help me to read the file?
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create application properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
Example is coming from here Properties (Java)
The methods of Properties can throw exceptions.
- When the file path is not valid (FileNotFoundException). Please try to create a File object and check, whether the File is existing.
- ...
You may take a look at Apache Commons Configuration. Using it you can read properties file like that:
Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");
This information regarding file location may be also important:
If you do not specify an absolute
path, the file will be searched
automatically in the following
locations:
in the current directory
in the user home directory
in the classpath
So in case of reading properties file in a servlet you should put properties file in a classpath (e.g. in WEB-INF/classes).
You can find more examples at their website.
You can use java.util.Properties
The biggest problem in reading a property file in web application is that you actually don't know about the actaul path of the file. So we have to use the relative path and for that we have to use various functions and classes like getresourceAsStream(), InputStream, FileinputStream etc.
And the method getReourceAsStream behaves differently in static and non static methogs..
you can do this in below way
Non Static
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
Static
InputStream input = ReadPropertyFile.class.getClassLoader().getResourceAsStream("config.properties");
For complete reference you can follow these links..
http://www.codingeek.com/java/using-getresourceasstream-in-static-method-reading-property-files
http://www.codingeek.com/java/read-and-write-properties-file-in-java-examples/
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
Properties p = new Properties();
p.load(in);
in.close();
The below code, will add a Listener which checks for file configured with dbprops system property. For every given interval it will look if the file is modified, if it is modified it will load the Properties from the file.
package com.servlets;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DBPropsWatcherListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Timer timer = new Timer("ResourceListener");
timer.schedule(new MyWatcherTask(servletContext), 15);
}
public void contextDestroyed(ServletContextEvent event)
{
}
private class MyWatcherTask extends TimerTask
{
private final ServletContext servletContext;
private long lastModifiedTime = -1;
public MyWatcherTask(ServletContext servletContext)
{
this.servletContext = servletContext;
}
public void run()
{
try {
File resourceFile = new File(System.getProperty("dbProps"));
long current = resourceFile.lastModified();
if (current > lastModifiedTime) {
java.io.InputStream dbPropsStream = new FileInputStream(resourceFile );
java.util.Properties dbProps = new java.util.Properites();
dbProps.load(dbPropsStream);
realoadDBProps();
}
lastModifiedTime = current;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
Below program read the properties file a display using key value pair
File f1 = new File("abcd.properties");
FileReader fin = new FileReader(f1);
Properties pr = new Properties();
pr.load(fin);
Set<String> keys = pr.stringPropertyNames();
Iterator<String> it = keys.iterator();
String key, value;
while (it.hasNext())
{
key = it.next();
value = pr.getProperty(key);
System.out.println(key+":"+value);
}
}
If your application is small enough with only a handful of properties coming from just one or two property files, then I would suggest to use the JDK's own Properties class which load the properties from a file and use it just like the way you use a hashtable. Properties class itself inherits from Hashtable. But, your application is significantly large with sizable number of properties coming from different sources like property files, xml files, system properties then I would suggest to use Apache commons configuration. It presents a unified view of properties from across different configuration sources and allows you to define an override and preference mechanism for common properties appearing in different sources. Refer this article http://wilddiary.com/reading-property-file-java-using-apache-commons-configuration/ for a quick tutorial on using the commons configuration.
This may work::
Properties prop = new Properties();
FileReader fr = new FileReader(filename);
prop.load(fr);
Set<String> keys = pr.stringPropertyNames();
//now u can get the values from keys.
The Properties class has a convenient load method. That's the easiest way to read a java properties file.
That is a good idea to read the database values from properties file
You can use a properties class from Util package. The important thing to keep in mind is closing the stream after reading the file or writing the file to disk. Otherwise it causes problems. Here is an example for your reference:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class App
{
public static void main( String[] args )
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
localhost
mkyong
password
ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
assuming mybundle.properties file is in classpath
Read this.Usually the properties file is kept in the classpath so that this method can read it.