Javamail - Why can't I get it to work? - java

I stole this code to test about emailing using java. Javamail is required, obviously. For some reason, I can't get javax.mail to implement. I downloaded the most recent javamail and put them in the jdk and jre lib folders, yet nothing changes. Please and thank you!
//A class which uses this file to send an email :
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/
public final class Emailer {
public static void main( String... aArguments ){
Emailer emailer = new Emailer();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail(
"sean_chili#yahoo.com", "clevelanm#sou.edu",
"Testing 1-2-3", "blah blah blah"
);
}
/**
* Send a single email.
*/
public void sendEmail(
String aFromEmailAddr, String aToEmailAddr,
String aSubject, String aBody
){
//Here, no Authenticator argument is used (it is null).
//Authenticators are used to prompt the user for user
//name and password.
Session session = Session.getDefaultInstance( fMailServerConfig, null );
MimeMessage message = new MimeMessage( session );
try {
//the "from" address may be set in code, or set in the
//config file under "mail.from" ; here, the latter style is used
//message.setFrom( new InternetAddress(aFromEmailAddr) );
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
);
message.setSubject( aSubject );
message.setText( aBody );
Transport.send( message );
}
catch (MessagingException ex){
System.err.println("Cannot send email. " + ex);
}
}
/**
* Allows the config to be refreshed at runtime, instead of
* requiring a restart.
*/
public static void refreshConfig() {
fMailServerConfig.clear();
fetchConfig();
}
// PRIVATE //
private static Properties fMailServerConfig = new Properties();
static {
fetchConfig();
}
/**
* Open a specific text file containing mail server
* parameters, and populate a corresponding Properties object.
*/
private static void fetchConfig() {
InputStream input = null;
try {
//If possible, one should try to avoid hard-coding a path in this
//manner; in a web application, one should place such a file in
//WEB-INF, and access it using ServletContext.getResourceAsStream.
//Another alternative is Class.getResourceAsStream.
//This file contains the javax.mail config properties mentioned above.
input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );
fMailServerConfig.load( input );
}
catch ( IOException ex ){
System.err.println("Cannot open and load mail server properties file.");
}
finally {
try {
if ( input != null ) input.close();
}
catch ( IOException ex ){
System.err.println( "Cannot close mail server properties file." );
}
}
}
}

Just for completeness, here's the answer.
Your Eclipse is telling you
<Some Class> cannot be resolved to a type
This is usually an indication that your classpath is not correct. You said
I downloaded the most recent javamail and put them in the jdk and jre
lib folders, yet nothing changes
Don't do this. Take the javamail.jar and use it on your application Build Path. To do so, drag and drop the jar into your project, right-click it and select Build Path > Add to build path.

Related

java.nio.file.AccessDeniedException to ~/AppData\Local\Temp\unlink-test12695598880278433589.tmp file bt-cli api

Want to download torrents via bt-cli. I tryed to launch bt-cli as module of bt parent and launch bt-cli-demo as project, but I aslways get java.nio.file.AccessDeniedException to temp files.
I tryed through Intellij Idea and through shell, all time the same problem.
Also tryed to dowload with -f and with -m keys (link to the project and keys description https://github.com/atomashpolskiy/bt)
I always get the same exception:
exception screen
Maybe I have to change folder for temp files, but I don't know to do it
Code:
public static void main(String[] args) throws IOException {
Options options;
try {
options = Options.parse(args);
} catch (OptionException e) {
Options.printHelp(System.out);
return;
}
configureLogging(options.getLogLevel());
configureSecurity();
registerLog4jShutdownHook();
CliClient client = new CliClient(options);
client.start();
}
all params I get from shell, api parses it and create configureation according income params. Then it starts.
Params for shell:
static {
parser = new OptionParser() {
{
acceptsAll(Arrays.asList("?", "h", "help")).isForHelp();
}
};
metainfoFileOptionSpec = parser.acceptsAll(Arrays.asList("f", "file"), "Torrent metainfo file")
.withRequiredArg().ofType(File.class);
magnetUriOptionSpec = parser.acceptsAll(Arrays.asList("m", "magnet"), "Magnet URI")
.withRequiredArg().ofType(String.class);
targetDirectoryOptionSpec = parser.acceptsAll(Arrays.asList("d", "dir"), "Target download location")
.withRequiredArg().ofType(File.class)
.required();
shouldSeedOptionSpec = parser.acceptsAll(Arrays.asList("s", "seed"), "Continue to seed when download is complete");
sequentialOptionSpec = parser.acceptsAll(Arrays.asList("S", "sequential"), "Download sequentially");
enforceEncryptionOptionSpec = parser.acceptsAll(Arrays.asList("e", "encrypted"), "Enforce encryption for all connections");
verboseOptionSpec = parser.acceptsAll(Arrays.asList("v", "verbose"), "Enable more verbose logging");
traceOptionSpec = parser.accepts("trace", "Enable trace logging");
inetAddressOptionSpec = parser.acceptsAll(Arrays.asList("i", "inetaddr"), "Use specific network address (possible values include IP address literal or hostname)")
.withRequiredArg().ofType(String.class);
torrentPortOptionSpec = parser.acceptsAll(Arrays.asList("p", "port"), "Listen on specific port for incoming connections")
.withRequiredArg().ofType(Integer.class);
dhtPortOptionSpec = parser.accepts("dhtport", "Listen on specific port for DHT messages")
.withRequiredArg().ofType(Integer.class);
shouldDownloadAllFiles = parser.acceptsAll(Arrays.asList("a", "all"), "Download all files (file selection will be disabled)");
}
/**
* #throws OptionException
*/
public static Options parse(String... args) {
OptionSet opts = parser.parse(args);
return new Options(
opts.valueOf(metainfoFileOptionSpec),
opts.valueOf(magnetUriOptionSpec),
opts.valueOf(targetDirectoryOptionSpec),
opts.has(shouldSeedOptionSpec),
opts.has(sequentialOptionSpec),
opts.has(enforceEncryptionOptionSpec),
opts.has(verboseOptionSpec),
opts.has(traceOptionSpec),
opts.valueOf(inetAddressOptionSpec),
opts.valueOf(torrentPortOptionSpec),
opts.valueOf(dhtPortOptionSpec),
opts.has(shouldDownloadAllFiles));
}
AccessDeniedException can mean lots of things. The documentation says: "a file system operation is denied, typically due to a file permission or other access check", and I would pay attention to the word "other".

Updating resource files at runtime

When my application starts it reads a configuration properties file using the following code:
Properties properties = new Properties();
// parse the config resource
try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename))
{
if (input == null)
{
// throw exception
}
// read the property list (key-value pairs) from the input byte stream
properties.load(input);
}
I am able to read and set individual properties.
The properties file is located in src/main/resources and after I build the application using maven, a copy of it is placed in target/classes. The jar file that is created also has a copy of it in the root directory when I open it up.
I would also like to be able to overwrite the properties file so that next time the application starts up, then it will read the new updated file. How do I achieve this? Is it even possible?
I found this question but no answers.
I've tried this:
try (OutputStream output = new FileOutputStream(filename))
{
properties.store(output, null);
}
which works if I just want to create a new file altogether. I would then have to modify the application so that it reads from a given folder rather than what originated from the resources folder. Is this what I should be doing?
I'm fairly new to Java so please go easy.
Storing the initial, default properties in the jar file, as resources is fine.
But if you want them to be writable, then you need to really store them as a file somewhere on the disk. Typically, under a .yourapp directory (or in a .yourapp file) inside the user's home directory.
So, try finding the file, and if not present, fallback to the resources. When writing, always write to the file.
This is an example code you can use for this. You create a config folder in the project root directory, an inside it you place your app.properties file
package com.yourparckage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
/* Create basic object */
private ClassLoader objClassLoader = null;
private Properties commonProperties = new Properties();
public static final String CONFIG_FILE = "config/app.properties";
/**
* This method loads config data from properties file
*
*/
public Config() {
objClassLoader = getClass().getClassLoader();
}
public String readKey(String propertiesFilename, String key)
{
/* Simple validation */
if (propertiesFilename != null && !propertiesFilename.trim().isEmpty() && key != null
&& !key.trim().isEmpty()) {
/* Create an object of FileInputStream */
InputStream objFileInputStream = null;
/**
* Following try-catch is used to support upto 1.6. Use try-with-resource in JDK
* 1.7 or above
*/
try {
/* Read file from resources folder */
objFileInputStream = new FileInputStream(propertiesFilename);
/* Load file into commonProperties */
commonProperties.load(objFileInputStream);
/* Get the value of key */
return String.valueOf(commonProperties.get(key));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
/* Close the resource */
if (objFileInputStream != null) {
try {
objFileInputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
return null;
}
}

PeerUnavailableException using JAIN SIP API on Android

I'm trying to build SIP application using JAIN SIP 1.2 and the NIST implementation on android.
I have rebuilt jain-sip-api-1.2.jar and jain-sip-ri-1.2.1111.jar from source, and renamed javax -> jain_javax and gov.nist.javax -> jain_gov.nist.jain_javax. I tested the jar files on textclient example on standard java without problem. However, when I run it on Android I still get the error:
"The Peer SIP Stack: jain_gov.nist.jain_javax.sip.SipstackImpl could not be instantiated. Ensure the Path Name has been set".
Did I miss anything here?
It is not sufficient to rename the packages. JAIN-SIP has internal references to some classes by their original package name "gov.nist". You should also double check all your code to rename any "gov.nist" references such as the prefix for the stack classes.
Android has built-in an older version of JAIN-SIP which is taking over some of the existing references to those "gov.nist" classes. It's not an exported API, so not quite obvious. That's why it may behave differently on desktop machines. Post you code and full error messages/debug logs if you need more help.
Sovled. Jain Sip is using log4i-1.2.x.jar which does not work properly on Android. There are lots of discussion on Internet how to make log4j working on Android but none of them works for me. I have removed all log4j related code from Jain Sip source and now the sip stack is working properly on Android.
I am using JAIN-SIP-1-2-164. Here is the app code:
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.*;
import android.os.Handler;
import jain_javax.sip.*;
import jain_javax.sip.address.*;
import jain_javax.sip.header.*;
import jain_javax.sip.message.*;
public class SipLayer implements SipListener {
private SipStack sipStack;
private SipFactory sipFactory;
private Properties properties;
private String local_ip;
int listen_port;
/** Here we initialize the SIP stack. */
public SipLayer(int listen_port) {
try {
setUsername(username);
this.local_ip = InetAddress.getLocalHost().getHostAddress();;
this.listen_port = listen_port;
// Create the SIP factory and set the path name.
this.sipFactory = SipFactory.getInstance();
this.sipFactory.setPathName("jain_gov.nist");
// Create and set the SIP stack properties.
this.properties = new Properties();
this.properties.setProperty("jain_javax.sip.STACK_NAME", "stack");
this.properties.setProperty("jain_javax.sip.IP_ADDRESS", local_ip);
if(proxy != null)
this.properties.setProperty("jain_javax.sip.OUTBOUND_PROXY", proxy + ':' + server_port + '/' + protocol);
//DEBUGGING: Information will go to files textclient.log and textclientdebug.log
this.properties.setProperty("jain_gov.nist.javax.sip.TRACE_LEVEL", "32");
// this.properties.setProperty("jain_gov.nist.javax.sip.SERVER_LOG", "textclient.txt");
// this.properties.setProperty("jain_gov.nist.javax.sip.DEBUG_LOG", "textclientdebug.log");
// Create the SIP stack.
this.sipStack = this.sipFactory.createSipStack(properties);
}
catch (Exception e) {
msgProc.processError("SipLayer failed: " + e.getMessage() + "\n");
}
}
}
Same code runs ok on java on a windows machine, but android emulator I got above mentioned error message.
I found that it failed in following Jain SIP 1.2 routine at "SipStack sipStack = (SipStack) sipStackConstructor.newInstance(conArgs);"
private SipStack createStack(Properties properties)
throws PeerUnavailableException {
try {
// create parameters argument to identify constructor
Class[] paramTypes = new Class[1];
paramTypes[0] = Class.forName("java.util.Properties");
// get constructor of SipStack in order to instantiate
Constructor sipStackConstructor = Class.forName(
getPathName() + ".jain_javax.sip.SipStackImpl").getConstructor(
paramTypes);
// Wrap properties object in order to pass to constructor of
// SipSatck
Object[] conArgs = new Object[1];
conArgs[0] = properties;
// Creates a new instance of SipStack Class with the supplied
// properties.
SipStack sipStack = (SipStack) sipStackConstructor.newInstance(conArgs);
sipStackList.add(sipStack);
String name = properties.getProperty("jain_javax.sip.STACK_NAME");
this.sipStackByName.put(name, sipStack);
return sipStack;
} catch (Exception e) {
String errmsg = "The Peer SIP Stack: "
+ getPathName()
+ ".jain_javax.sip.SipStackImpl"
+ " could not be instantiated. Ensure the Path Name has been set.";
throw new PeerUnavailableException(errmsg, e);
}
}
Any suggestion or how to debug further?

FTP exception 501 "pathname" more than 8 characters

I am trying to access a file via a URI using the FTP protocol. For obvious security reasons I had to make some changes but this is where the problems seem to be coming from.
My URI is as follows:
ftp://user:pasword#host.net/u/Bigpathname/XYZ/ABC/BigPathname/bigpathname/xyz/abc/MY_LOG.LOG
And I see this exception:
sun.net.ftp.FtpProtocolException: CWD Bigpathname:501 A qualifier in "Bigpathname" is more than 8 characters
This is really confusing as I can access the file from a Windows 7 command line with the CD command just fine. Both one directory at a time and as a full path.
I found one article mentioning that MVS file names must be 8 or fewer characters but this does not explain how I can get to these same files from my command line! They do exist there is data there that I can download manual but I can not get there via a URI in Java.
PS I use .toURL().openStream() to get files on my local machine just fine, it only fails when I try to get them from my server.
EDIT October 1st
I am able to access files on the MVS host using FileZilla and the basic FTP client from the Windows 7 command line - but I still cannot get them from a URI/URL. I downloaded a very basic Java built FTP client and tried accessing the same file in my program from there and the path works but because my file name has a dot in it "MY_LOG.LOG" I am getting File does not exist 501 Invalid data set name "MY_LOG.LOG". Use MVS Dsname conventions. I am utterly perplexed by this...
EDIT Ocotober 1st afternoon :)
OK I finally got it to work with a FTP client in my Java code - but I still want to use the URL class as I have logs on both local and remote machines. Is there a way to encode a URL string so that it can retrieve a file from a remote machine with the FTP protocol? I am not sure how it works in the Java URL class but in the FTP client I had to use the CWD and then the RETR command.
If I can do this then I have one solution for getting all my logs, otherwise I will have to detect if it is a file or ftp URL and then behave differently. Not the end of the world but not what I want...
The code that tries to get the file with just a URL is as follows: (sysc is a valid host)
void testFTP()
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URI uri = new URI(ftp);
URL ftpFile = uri.toURL();
BufferedReader in = new BufferedReader(new InputStreamReader(ftpFile.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
In this case I think the problem is also Server Related, It all works fine for me with Filezilla Server except when the filename length(including directories) exceeds 255 chars but if you want to use the URL class with another FTP you must override or implement your own URLStreamHandlerFactory.
URL.setURLStreamHandlerFactory(...);
I haven't found any for my favorite java FTP Client witch is Apache one so I have developed one but may need a few touch ups.
package net.custom.streamhandler.apacheftp;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ApacheURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
//this will only override the chosen protocol
if ( protocol.equalsIgnoreCase("ftp") )
return new CustomHandler();
else
return null;
}
}
class CustomHandler extends URLStreamHandler {
protected URLConnection openConnection(URL url)
throws IOException {
return new CustomURLConnection(url);
}
}
class CustomURLConnection extends URLConnection {
int reply;
FTPClient ftp = new FTPClient();
InputStream in;
static int defaultPort = 21;
static String defaultPath = "/";
CustomURLConnection ( URL url)
throws IOException {
super( url );
}
synchronized public void connect() throws IOException {
try {
int port;
if ((port = url.getPort()) == -1 )
port = defaultPort;
ftp.connect(url.getHost(), port);
String login = "anonymous";
String password = "";
if(url.getAuthority().indexOf(':')>-1 &&
url.getAuthority().indexOf('#')>-1){
String []auxArray = url.getAuthority().replaceAll("#", ":").split(":");
login = auxArray[0];
password = auxArray[1];
}
ftp.login(login, password);
reply = ftp.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Apache Success");
} else {
System.out.println("Connection Apache Failed");
ftp.disconnect();
}
in = ftp.retrieveFileStream(url.getFile());
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
connected = true;
}
synchronized public InputStream getInputStream()
throws IOException {
if (!connected)
connect();
return ( in );
}
}
*Keep in mind that you can implement new ways to handle different protocols for the java.net.URL this way.
Your code...
...
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URL.setURLStreamHandlerFactory(new ApacheURLStreamHandlerFactory());
...
G'Bye
**(To err is human, to forgive is divine)
Try using the short name for the path. Something like /U/BIGPAT~1/XYZ/ABC/BIGPAT~1/BIGPAT~1/XYZ/ABC/MY_LOG.LOG
You can find the short name for any directory longer than 8 characters with dir /x.
FTP clients are notoriously difficult to write given the variation of (and bugs in) server implementations.
I'm betting that MVS is not completely supported by sun.net.ftp.FtpClient, which is the class used under the hood when you call URL.openStream on an FTP URL.
The Apache Commons Net library should support MVS, but it sounds like you already found a working client.
Have you considered using an RMI for transporting the files that way you can give a direct path to the file as a parameter without the use of ftp then have the file sent back in a byte array.

How can I change the running directory of a program - by setting it in the exe shortcut?

I have an exe process that is running with a shortcut.
In the "Start in" property of the shortcut I set it to the folder where all app resources are. The process still looks for files at the location of the exe and not the location written in the shortcut.
I can also see it in Process Explorer - the "current directory" is the location of the exe.
Is there a way to change it?
(If I wasn't clear enough -
I want to put my app in a central network location and not in each user folder - but I want it to run - above each user folder by putting a shortcut in each user folder.)
BTW : Why don't I solve it with code writing? Because of third party jars I have in my exe (I am using exe4j to make an exe)
From exe4-j documentation.., it seems this can be configured in exe4j project.
Working directory
For some applications (especially GUI applications) you might want to change the working directory
to a specific directory relative to the executable, for example to read config files that are in a fixed
location. To do so, please select the Change working directory to: checkbox and enter a
directory relative to the executable in the adjacent text field. To change the current directory to the
same directory where the executable is located, please enter a single dot.
One alternative is to use a System Property. Just create a shortcut like this:
java -Dmyproperty="\\myserver\myfolder" -jar yourjar.jar
And get this property on your program:
System.getProperty("myproperty");
You can also set multiple System Properties.
I would start the java application via a cmd or bat file, then change to the work dir before you call javaw. If you don't do any thing special in your java application code all the paths in it will be relative to the place where you started java.
Jess
You can hack the classpath programatically which would allow you to specify a specific folder or series of folders to access the data.
import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURI().toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
with the property loader file of
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
public abstract class PropertyLoader
{
/**
* Looks up a resource named 'name' in the classpath. The resource must map
* to a file with .properties extention. The name is assumed to be absolute
* and can use either "/" or "." for package segment separation with an
* optional leading "/" and optional ".properties" suffix. Thus, the
* following names refer to the same resource:
* <pre>
* some.pkg.Resource
* some.pkg.Resource.properties
* some/pkg/Resource
* some/pkg/Resource.properties
* /some/pkg/Resource
* /some/pkg/Resource.properties
* </pre>
*
* #param name classpath resource name [may not be null]
* #param loader classloader through which to load the resource [null
* is equivalent to the application loader]
*
* #return resource converted to java.util.Properties [may be null if the
* resource was not found and THROW_ON_LOAD_FAILURE is false]
* #throws IllegalArgumentException if the resource was not found and
* THROW_ON_LOAD_FAILURE is true
*/
public static Properties loadProperties (String name, ClassLoader loader)
{
if (name == null)
throw new IllegalArgumentException ("null input: name");
if (name.startsWith ("/"))
name = name.substring (1);
if (name.endsWith (SUFFIX))
name = name.substring (0, name.length () - SUFFIX.length ());
Properties result = null;
InputStream in = null;
try
{
if (loader == null) loader = ClassLoader.getSystemClassLoader ();
if (LOAD_AS_RESOURCE_BUNDLE)
{
name = name.replace ('/', '.');
// Throws MissingResourceException on lookup failures:
final ResourceBundle rb = ResourceBundle.getBundle (name,
Locale.getDefault (), loader);
result = new Properties ();
for (Enumeration keys = rb.getKeys (); keys.hasMoreElements ();)
{
final String key = (String) keys.nextElement ();
final String value = rb.getString (key);
result.put (key, value);
}
}
else
{
name = name.replace ('.', '/');
if (! name.endsWith (SUFFIX))
name = name.concat (SUFFIX);
// Returns null on lookup failures:
in = loader.getResourceAsStream(name);
if (in != null)
{
result = new Properties ();
result.load (in); // Can throw IOException
}
}
}
catch (Exception e)
{
result = null;
}
finally
{
if (in != null) try { in.close (); } catch (Throwable ignore) {}
}
if (THROW_ON_LOAD_FAILURE && (result == null))
{
throw new IllegalArgumentException ("could not load [" + name + "]"+
" as " + (LOAD_AS_RESOURCE_BUNDLE
? "a resource bundle"
: "a classloader resource"));
}
return result;
}
/**
* A convenience overload of {#link #loadProperties(String, ClassLoader)}
* that uses the current thread's context classloader.
*/
public static Properties loadProperties (final String name)
{
return loadProperties (name,
Thread.currentThread ().getContextClassLoader ());
}
private static final boolean THROW_ON_LOAD_FAILURE = true;
private static final boolean LOAD_AS_RESOURCE_BUNDLE = false;
private static final String SUFFIX = ".properties";
} // End of class
then you can add a path as follows
try {
//First Load up the properties and populate the config
ClassPathHacker.addFile("/pathtomyapp");
} catch (IOException ex) {
ex.printStackTrace();
}
properties = PropertyLoader.loadProperties("myapp");
or you can also use getResourceBundle to get your resources, this is just one example of hacking the classpath to allow files to be available, you can always just add the classpath programatically and let the jar files you need to be available to reside there, so if you always ensure that the app network path is Q: you can add Q:\ to the classpath.

Categories

Resources