how to read values from property file? - java

How to read the values from properties file in java script?
I goggling about it but not satisfied.Please share me some samples or links. My application develops by jsp-servlet, eclipse LUNA and Windows7.

Javascript is executed on the client side and cannot access local files (except the html5 web storage).
If you want to access properties which are defined in a properties file on the server side you have two options:
Server side parsing
Read the properties file at the server side and write the values to the html response as JS values
// output a property as JS value to the client. Make sure this is inside a
// <script> tag
void printProperty(Properties properties, String key) {
Sytem.out.println("var " + key + "='"properties.getProperty("key") + "'");
}
Client side parsing (more complex)
Make the properties file available through an URL (http:/.../conf.properties)
Read the file via ajax
Parse the properties file

You can read property file in many way, below is one of the way. Good Link
config.properties
dbpassword=password
database=localhost
dbuser=mkyong
App.java
package com.mkyong.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// 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();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Google Links

Related

Properties file not loading and updating for relative path but working fine for absolute path

I am trying to access a properties file from the src/main/resources folder but when I try to load the file using a relative path it is not getting updated. But it is working fine for an absolute path.
I need the dynamic web project to work across all platforms.
public static void loadUsers() {
try(
FileInputStream in = new FileInputStream("C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties")) {
// write code to load all the users from the property file
// FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
in.close();
}
catch(Exception e){
e.printStackTrace();
}
First of all you are using Spring, at least that is what the tags at the bottom say. Secondly C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties is the root of your classpath. Instead of loading a File use the Spring resource abstraction.
As this is part of the classpath you can simply use the ClassPathResource to obtain a proper InputStream. This will work regardless of which environment you are in.
try( InputStream in = new ClassPathResource("users.properties").getInputStream()) {
//write code to load all the users from the property file
//FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
} catch(Exception e){
e.printStackTrace();
}
NOTE: you are already using a try with resources so you don't need to close the InputStream that is already handled for you.
Changing things inside your application simply won't work, as this would mean you could change resources (read classes) in your jar which would be quite a security risk! If you want something to be changable you will have to make it a file outside of the classpath and directly on the file-system.
Try the following code
import java.io.FileInputStream;
import java.io.IOException;
public class LoadUsers {
public static void main(String[] args) throws IOException {
try(FileInputStream fis=new FileInputStream("src/main/resources/users.properties")){
Properties users=new Properties();
users.load(fis);
System.out.println(users);
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

How to load external properties file with Java without rebuilding the Jar?

I use gradle which structures projects in maven style so I have the following
src/main/java/Hello.java and src/main/resources/test.properties
My Hello.java look like this
public class Hello {
public static void main(String[] args) {
Properties configProperties = new Properties();
ClassLoader classLoader = Hello.class.getClassLoader();
try {
configProperties.load(classLoader.getResourceAsStream("test.properties"));
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath
public class Hello {
public static void main(String[] args) {
String configPath = "test.properties";
if (args.length > 0) {
configPath = args[0];
} else if (System.getenv("CONFIG_TEST") != null) {
configPath = System.getenv("CONFIG_TEST");
}
File file = new File(configPath);
try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
Properties configProperties = new Properties();
configProperties.load(input);
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST
Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.

Use properties file to set directory where to load file

I have a java/mule application that loads a file from a directory created and displays it on the server eg localhost/file.txt
File dir = new File("C:\\folder");
dir.mkdirs();
File file1 = new File(dir, filePath);
The filepath is taking from the URL - it takes the param http.request.path eg file.txt and reads the file
Is there anyway I can move the hard coded bit of code for setting the folder to a mule/java properties file instead of hard coding it?
You can put the path in a properties file, and use the Properties class in Java, to read it.
Sample code :
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
}catch(IOException e){
//handle exception
}
More details--
You have to create a new property file, which is just a file with .properties extension. Let's call it sample.properties. You can put values, which will be key-value pairs there. This is how you will put values there :
dirpath = /home/dextr/Documents/docs/
fileName = puzzle.txt
You you will have to place the properties file in ROOT of the application or you will have to provide the relative path in order to read it.
Then you use a code like the following one to read the values in a properties object. Depending upon what value you need, you use the appropriate key.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SoSample {
public static void main(String[] args) {
Properties properties = new Properties();
InputStream input = null;
try {
input = new FileInputStream("sample.properties");
properties.load(input);
String dirPath = (String)properties.get("dirpath");
System.out.println(dirPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}

java.lang.IllegalArgumentException: 'hello' does not contain an equals sign

I am currently using the Apache commons configuration library to write and read data from a file. I am able to save the key value pair colors=hello to the user..properties file, but when i try to read the value is get the below exception.
Exception in thread "main" java.lang.IllegalArgumentException: 'hello' does not contain an equals sign
at org.apache.commons.configuration.AbstractConfiguration.getProperties(AbstractConfiguration.java:625)
at org.apache.commons.configuration.AbstractConfiguration.getProperties(AbstractConfiguration.java:579)
at com.code.prep.CommonsMain.readProperties(CommonsMain.java:21)
at com.code.prep.CommonsMain.main(CommonsMain.java:12)
The code is as below
package com.code.prep;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class CommonsMain {
public static void main(String[] args) {
CommonsMain main = new CommonsMain();
main.readProperties();
// main.writeProperties();
}
public void readProperties(){
PropertiesConfiguration config = new PropertiesConfiguration();
try {
config.load("user.properties");
System.out.println(config.getProperties("colors"));
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public void writeProperties(){
PropertiesConfiguration config = new PropertiesConfiguration();
try {
config.load("user.properties");
config.setProperty("colors", "hello");
config.save("user.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}
The Jars in the class path are:
commons-configuration-1.9.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
user.properties contains
colors = hello
user = thejavamonk
You should not be using
config.getProperties("colors")
but
config.getProperty("colors")
"getProperties(code)" is looking for (multiple) lines in your user.properties file of the form:
code key=val
so it's expecting your code as it stands to have lines like :
colors foreground=black
colors background=white
etc.
This does not look like library issue. Open your file and check whether the data is actually available. From you code it looks like you are doing -
main.readProperties();
// main.writeProperties();
Why would there be any data unless you write it? Call writeProperties() method first and then read it back.

want to copy a file from a server to a client

i want to copy a file from a server to a client in java.this is my code up to now
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Problem is , the server is not uploadded online , but it is on my local drive, and the URL thing doesnt work. is there any other way? is this way correct? thanks
If you're expecting to access your file from the local file system (whether that be via network drive or a local disk), you'll need to treat this as if it is a straight file copy.
If you're expecting to access your file as if it is available for download from an HTTP server, you will need to treat it as an HTTP download (which is what it looks like you're trying to do with the URL).
If you want to test the HTTP download functionality using a file on your local system, just set up a simple HTTP server on your dev machine with a directory on your local system, and give your HTTP-downloading code a URL pointing to that local server (on http://localhost, or using your IP address).
Unfortunately, HTTP is a very different animal from a file system, and I don't think there's any way to use the same code to handle both scenarios. If you want your program to ultimately support both protocols, you should build methods/classes to handle both situations, and then have your program detect and use the appropriate protocol for a given path. You'll need to do the same for any other protocol you wish to support (FTP, SFTP, etc).

Categories