I have file "recipients.txt" that contains as you might have guessed list of recipients. I will need to update it from time to time, therefore I was planning on having it in the same directory as the .jar file I exported in order to do so.
At the moment i have it in the "bin" directory of my project in my eclipse workspace. I load the file into variable using FileReader.
When I tried exporting it as "runnable jar file" i could not access it. I've put an option there to show a JOptionPane with the path that the application was looking in, and it is weird.
The pane tells me that it was looking for file "\Desktop\JarFile.jarrecipients.txt".
Yes, that is correct, one "\" is missing.
So what am I doing wrong and how do I do this right? I am pretty sure I am doing it all wrong, in which case how would I do it right? How could I have a file that I can keep up to date on a regular basis? And how would I export it all to make it work?
The code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class DeliveryPackage {
public String recipientList="No Recipients";
public String recipientFileName = "recipients.txt";
public String recipientFilePath = DeliveryPackage.class.getProtectionDomain().getCodeSource().getLocation().toString().replace("file:/","").replace("/", "\\") + recipientFileName;
public File recipientFile = new File(recipientFilePath);
public String fileNotFoundMessage = "File not found";
private String messageContents = "";
private String messageSubject = "";
public void setMessageSubject(String subject) {
messageSubject = subject;
}
public String getMessageSubject() {
return messageSubject;
}
public void setMessageContents(String message) {
messageContents = message;
}
public String getMessageContents() {
return messageContents;
}
public DeliveryPackage() {
loadRecipients();
}
public String getRecipients(){
return recipientList;
}
public String getRecipientFileName() {
return recipientFileName;
}
public File getRecipientFile(String recipientFilePath) {
File recipFile = new File(recipientFilePath);
return recipFile;
}
public String getFileNotFoundMessage() {
return "File not found";
}
public void loadRecipients() {
if(recipientFile.exists() && !recipientFile.isDirectory()) {
String recipient;
recipientList = "";
try {
FileReader fileReader = new FileReader(recipientFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((recipient = bufferedReader.readLine()) != null) {
if (recipient.trim().length() > 0) {
if (recipientList == "") {
recipientList = recipient;
} else {
recipientList = recipientList + "," + recipient;
}
}
}
// Always close files.
bufferedReader.close();
} catch (Exception e) {
}
} else {
recipientList = getFileNotFoundMessage();
}
}
}
Thanks