Skip to content

Instantly share code, notes, and snippets.

@6londe
Last active September 7, 2017 04:24
Show Gist options
  • Save 6londe/1ad6b4a4b8cfe17254e9f7f4dc5feb8f to your computer and use it in GitHub Desktop.
Save 6londe/1ad6b4a4b8cfe17254e9f7f4dc5feb8f to your computer and use it in GitHub Desktop.
Java set configuration from text file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
public class Configuration {
private String resource = null;
private File file = null;
private URL res = null;
public Configuration(String resource) {
/* resource string example: /com/org/pkg/project.properties */
super();
this.resource = resource;
this.res = getClass().getResource(resource);
}
public String getProperty(String key) {
Properties prop = new Properties();
InputStream input = null;
String value = null;
if (res.toString().startsWith("jar:")) {
input = getClass().getResourceAsStream(resource);
} else {
file = new File(res.getFile());
try {
input = new FileInputStream(file.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
try {
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
value = prop.getProperty(key);
if (input != null){
try{
input.close();
} catch (IOException e){
e.printStackTrace();
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment