Last active
September 7, 2017 04:24
-
-
Save 6londe/1ad6b4a4b8cfe17254e9f7f4dc5feb8f to your computer and use it in GitHub Desktop.
Java set configuration from text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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