The following program successfully prints 4 properties as expected
public class TestingStringProps {
public static void main(String[] args) throws IOException {
String s = "name=file\npath=/var/log/mine/\nhost=localhost:9092\nport=9999";
Properties props = new Properties();
props.load(new StringReader(s));
System.out.println("Number of Props: " + props.stringPropertyNames().size());
for (final String name : props.stringPropertyNames()) {
System.out.println(props.getProperty(name));
}
}
}
Now, if i pass the same string as Program Argument in eclipse, it considers the whole String as one property.
How to pass a string of properties in eclipse?
Requirement: I have simplified the question here. In our project a program gets a string of properties like the above from another program and it is working fine. I wanted to test the second program independently.
You need to change the code a bit. Then need to set the program arguments as below (need to add space in between each property)
public static void main(String[] args) throws IOException {
String str = String.join("\n", args);
Properties props = new Properties();
props.load(new StringReader(str));
System.out.println("Number of Props: " + props.stringPropertyNames().size());
for (final String name : props.stringPropertyNames()) {
System.out.println(props.getProperty(name));
}
}
program argument: name=file path=/var/log/mine host=localhost:9092 port=9999
Related
I am using this example to read from configuration file (data such as host name, password, etc) . But they did not include the Configurations class itself.
So I am not really sure how that should be implemented.
Here is how I am trying to read the properties from Main class:
Configurations configs = new Configurations(); // Error: cannot find symbol symbol: class Configurations location: class Main
try {
Configuration config = configs.properties(new File("database.properties"));
String dbHost = config.getString("database.host");
int dbPort = config.getInt("database.port");
String dbUser = config.getString("database.user");
String dbPassword = config.getString("database.password", "secret"); // provide a default
long dbTimeout = config.getLong("database.timeout");
} catch (ConfigurationException cex) {
cex.printStackTrace();
}
And this is how my database.properties file looks:
database.host = "dbname";
datatabase.port = 5005;
datatabase.user = "root";
datatabase.password = "";
database.timeout = 60000
P.S. Sorry for my stupidity, I am very new to Java.
You can use the properties class in java, which has a load method that specifies an inputstream.
Then, you can read your properties file via FileInputStream.
example:
public class Test {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
InputStream inputStream =
new FileInputStream("D:\\work_space\\java_workspace\\test-mq\\src\\main\\resources\\database.properties");
properties.load(inputStream);
String host = properties.getProperty("database.host");
// get more properties......
System.out.println(host);
}
}
I am very lost with the concept of getResources.
I have put a simple text file in a bin folder which I would like to access as a resource so I can then build and deploy. However when I try to run the jar file I get a file not found error which I think is down to how I am accessing the resource. How can I use it?
public class Iterator {
static ArrayList<String> myFiles = new ArrayList<String>();
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
static String folderName;
static Path p;
public Iterator() { }
public static void main(String[] args) throws IOException, SAXException, TikaException, SQLException, ParseException, URISyntaxException, BackingStoreException {
Preferences userPrefs = Preferences.userNodeForPackage(TBB_SQLBuilder.class);
p = Paths.get(filename.toURI());
//This iterates through each of the files in the specified folder and copies them to a log.
//It also checks to see if that file has been read already so that it isn't re-inputted into the database if run again
//Loop through the ArrayList with the full path names of each folder in the outer loop
for (String line : Files.readAllLines(p)){
myFiles.add(line);
}
}
}
The error I get
Exception in thread "main" java.nio.file.FileSystemNotFoundException
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Paths.java:143)
at Overview.Iterator.main(Iterator.java:46)
**Edit with #BorisTheSpiders' answer:
public class Iterator {
static ArrayList<String> myFiles = new ArrayList<String>();
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
static String folderName;
static Path p;
public Iterator() {
}
public static void main(String[] args) throws IOException, SAXException, TikaException, SQLException, ParseException, URISyntaxException, BackingStoreException {
Preferences userPrefs = Preferences.userNodeForPackage(TBB_SQLBuilder.class);
InputStream in = filename.openStream( );
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
p = Paths.get(filename.toURI());
//This iterates through each of the files in the specified folder and copies them to a log.
//It also checks to see if that file has been read already so that it isn't re-inputted into the database if run again
//Loop through the ArrayList with the full path names of each folder in the outer loop
for (String line : Files.readAllLines(p)){
myFiles.add(line);
}
but I'm not really sure how I then use the reader to provide a Paths.get with a uri. I think I'm probably not understanding something fundamental here...
As pointed out in the comments, the file in question cannot be found in the file system.
As a suggestion, try replacing
static URL filename= Iterator.class.getResource("/Files/FilesLogged.txt");
with
static InputStream is = Iterator.class.getResourceAsStream("/Files/FilesLogged.txt");
and the block where the file is read with the following:
try (Scanner scanner = new Scanner(is)) {
while(scanner.hasNextLine()){
String line = scanner.nextLine();
myFiles.add(line);
}
}
I am having some trouble reading in a properties file. I want to read it in from console, but for now I am just using a variable to test it. I want to send the String of the file path to another class which will then read and set the properties, though I am getting a nullpointer and I am not sure why.
here is the app.java class with the main:
public static void main(final String [] args){
String path = "C:/Users/aak7133/Desktop/test.properties";
AppConfig config = new AppConfig();
try{
config.loadFile(path);
}catch(NullPointerException | FileNotFoundException e){
System.out.println("fail..");
}
}
and here is the appConfig.java class that receives the string (just the receiving part):
public void loadFile(String filepath) throws FileNotFoundException{
try{
prop.load(new FileInputStream(filepath));
} catch(IOException e){
throw new FileNotFoundException("File '" + filepath + "' not found.");
}
setProperties();
System.out.println(this.getFtpHost());
}
Just to see if I was reading in the properties correctly I did that print with one of the properties. The null pointer is in the main, so is it that I am not handling the try catch correctly or what?
I guess prop is not properly initialized in AppConfig. The NullPointerException may come from here.
I need develop a "launcher" for a java application. This launcher need be able to:
check if main application is up-to-date;
if not, download a update;
run this application and self terminate.
Something like this:
public final class Launcher {
public static void main(String[] args) throws Exception {
String jarName = args[0];
if (jarHasUpdate(jarName)
refreshJar(jarName);
executeJar(jarName);
}
}
What better way of develop the step 3?
I'm trying 2 distinct ways:
1- Run another instance of Java
With the code:
Runtime.getRuntime().exec("java -jar mainApp.jar");
Problem: the launcher still running until mainApp have finished.
2- Using ClassLoader to load .jar at runtime
Like this:
public final class Launcher {
#SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Invalid number of arguments.");
System.exit(1);
}
Refresh.refreshFile(args[0]);
// args[0] .jar name
// args[1] class with main function
File file = new File(args[0]);
try (URLClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL() });) {
Class cls = cl.loadClass(args[1]);
Method method = cls.getDeclaredMethod("main", new Class[] { String[].class });
Object params = new String[] {};
method.invoke(cls, params);
}
}
}
Problem: if "mainApp.jar" has dependencies, this isn't loaded.
Frankly, I do not know even it is possible or not.
But what I am trying to do is just like below.
I made a class file from ClassFile.java via javac command in terminal.
Then I want to get an instance from .java file or .class file.
Next, I made another project in eclipse, As you guess this project path and upper file path are completely different. For instance, ClassFile.java/class file can be located in '~/Downloads' folder, the other hand, new eclipse project can be in '~/workspace/'.
So I read file which referred in step 1 by FileInputStream.
From here, I just paste my code.
public class Main {
private static final String CLASS_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.class";
private static final String JAVA_FILE_PATH =
"/Users/juneyoungoh/Downloads/ClassFile.java";
private static Class getClassFromFile(File classFile) throws Exception {
System.out.println("get class from file : [" + classFile.getCanonicalPath() + " ]");
Object primativeClz = new Object();
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream(classFile));
primativeClz = ois.readObject();
ois.close();
return primativeClz.getClass();
}
public static void main(String[] args) throws Exception {
getClassInfo(getClassFromFile(new File(CLASS_FILE_PATH)));
}
}
just like your assumption, this code has errors.
For example, it shows :
java.io.StreamCurruptedException: invalid stream header : CAFEBABE
this there any way to get object instance from .class file or .java file?
P.S.
I wish do not use extra libraries.
private static final String CLASS_FOLDER =
"/Users/juneyoungoh/Downloads/";
private static Class getClassFromFile(String fullClassName) throws Exception {
URLClassLoader loader = new URLClassLoader(new URL[] {
new URL("file://" + CLASS_FOLDER)
});
return loader.loadClass(fullClassName);
}
public static void main( String[] args ) throws Exception {
System.out.println((getClassFromFile("ClassFile"));
}