For a few days now, I have been trying to get my Java project to load some properties from a file located in it's JAR file. However, I am constantly getting a null pointer when trying to load in the file.
The folder hierarchy has the properties file in /data, and all the source files in /emp/**/** ...
Code
Properties defaultProps = new Properties();
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("data/build_info.properties");
//InputStream in = new URL("file:data/build_info.properties").openStream();
defaultProps.load(in);
in.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
} catch (NullPointerException e){
Log.E("NPE- Properties not loaded", "properties");
revision = "Properties file not found";
}
if (defaultProps.getProperty("build.major.number") == null) {
Log.W("Properties not loaded", "properties");
revision = "Properties file not found";
} else {
Log.V("Properties Loaded Successfully", "properties");
revision = "Version: " + defaultProps.getProperty("build.major.number")
+ "." + defaultProps.getProperty("build.minor.number") + " "
+ "Revision: "
+ defaultProps.getProperty("build.revision.number");
}
If data is in the root of your jar, and if build_info.properties is inside the data directory in the jar, and if the jar is on the classpath, then getClass().getClassLoader().getResourceAsStream("data/build_info.properties"); will find that properties file. You could also use getClass().getResourceAsStream("/data/build_info.properties");.
Peculiarities can arise if getClass() returns a class loaded by a classloader different than the one that has your jar on its classpath.
You could alternatively try --
Thread.currentThread().getContextClassLoader().getResourceAsStream("data/build_info.properties");
I had the same issue with a dead-simple console application. Eventually I found a hint at https://stackoverflow.com/a/1464541/1792291 and I made my console app into a swing app, and suddenly everything worked.
The explanation in the link above does make some sense: since the console app gets its properties (including CLASSPATH) once when the shell is created, it won't know about the classpath defined during/for/by the JVM.
Related
I just started to work with files today with Android and have been pulling my hair out all day. This throws a FileNotFoundException:
public void writeConfig(){
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "AppName", "TimetableConfiguration");
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getActivity().getSharedPreferences("periods", MODE_PRIVATE).getString("periods", null).getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
P.rint("Didn't find file");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I notice that instead of creating a file, it creates a child folder. Why is it doing this?
Thanks for any help :)
FileNotFoundException: Creates child folder instead of file
Yes. That is what you do.
You first create with mkdirs() a directory with a certain name.
After that you try to create a file with the same name which is impossible as there cannot be two files or directories with the same name.
So have a look and you will find that directory.
Well you had deduced most all yourself already. Now try to understand your code.
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
You will see that printed every time you repeat the code. You should have seen this too. And have told us.
You should only call mkdirs if the directory does not exist yet.
I have created my sqlite database (employeertest.sql) and puted it in the Assets folder, then run
this code.
Unfortunately in the line getBaseContext().getAssets().open("employeertest") compiler says No such file or directory
try {
String destPath = "/data/data/" + getPackageName() +"/databases";
File f = new File(destPath);
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("employeertest"),
new FileOutputStream(destPath + "/employeertest"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Have you tried
CopyDB(getBaseContext().getAssets().open("employeertest.sql")
instead? Considering the file doesn't exist, I'm assuming the extension is missing and it cannot find the file.
you can use Context.getDatabasePath(String) to retrieve the correct path to the database directory. Please be aware that the directory could also not be there when you try to copy the db from the assets
i am using eclipse for develop the java desktop application and working with file but got the above error
my code is as following please try to help me how to give path in eclipse and also get same problem to load image from the given task
i have put the "files" folder out side the "src" folder
how to give path dynamically
my code is ass following
public int getTimeId()
{
LOG.info("The File name is :- " + fileName);
LOG.info("The path is :- ");
int count=0;
FileInputStream fileInputStream;
ObjectInputStream objectInputStream;
try
{
fileInputStream=new FileInputStream("/files/storetime.txt");
objectInputStream=new ObjectInputStream(fileInputStream);
while(objectInputStream.readObject()!=null)
{
count++;
}
}
catch(IOException e)
{
System.out.println("Error in file is :- " + e);
} catch (ClassNotFoundException e) {
System.out.println("Error in class not found :- " + e);
}
return count;
}
}
You are providing the absolute path by prep-ending / in the path. It means root directory in Unix file system. so, you have to give a relative path of the file from the current directory.You can put files directory in the root directory of your project folder and use
fileInputStream=new FileInputStream("files/storetime.txt");
So, it will be picked up
Use FileInputStream(new File("files/storetime.txt")); don't use /file -> it will check for /file partition in linux as /root
I am using icefaces to upload files to relative path in my web app (mywebapp/audio), then after the file is getting uploaded I rename it to save its extension as follows:
public static File changeExtToWav(FileInfo fileInfo,
StringBuffer originalFileName) {
log.debug("changeExtToWav");
int mid = fileInfo.getFile().getName().lastIndexOf(".");
String fileName = fileInfo.getFile().getName().substring(0, mid);
originalFileName.append(fileName);
log.debug("originalFileName: " + originalFileName);
String newFileName = fileName + "_" + new Date().getTime() + "."
+ "wav";
File newFile = new File(fileInfo.getFile().getParent() + "/"
+ newFileName);
log.debug("newFileName: " + newFile.getName());
fileInfo.getFile().renameTo(newFile);
return newFile;
}
after the file is getting uploaded, sometimes I want to delete it from UI button as follows:
try {
File fileToDelete = new File(filePath); // correct file path
log.debug("file exists: " + fileToDelete.exists()); // true
fileToDelete.delete();
} catch (Exception e) {
e.printStackTrace();
}
the file path is correct, and I get no exceptions, but the file is not deleted (I am using java 6 btw).
please advise how to fix this issue.
UPDATE: using the following useful method, I can get that the file is opened, any ideas how to close it ?
public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
try {
if (!file.exists())
return "It doesn't exist in the first place.";
else if (file.isDirectory() && file.list().length > 0)
return "It's a directory and it's not empty.";
else
return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
} catch (SecurityException e) {
return "We're sandboxed and don't have filesystem access.";
}
}
Well if the file is open, then there is two solutions :
You have a stream in your program open on this file. Note that afaik it's a problem on Windows, with Unix I can delete a File even if a stream is opened on it.
You have an other process using this file. So in this case you can't do anything from Java.
In the log it tells also that it can be a permission problem, are you sure you have enough privileges?
You can also use Files#delete(Path path) (jdk7) to have more details about the issue.
I'm maintaining properties files containing database credentials in protected folders on our internal server for each app that I deploy. I'm not allowed to store the credentials within the WAR file.
When testing on my PC the path is a windows mount, but when I depoloy to the server it is a unix path
I have been handling the retreival as such
//siteDbCedentialFolder obtained from web.xml
Properties prop = new Properties();
InputStream in = null;
try {
//assume running on server first
in = new FileInputStream("/abc/data/" + siteDbCedentialFolder + "/props.txt");
} catch (java.io.IOException ex) {
// Probabaly Running locally
in = new FileInputStream("W:/internal/abc/data/" + siteDbCedentialFolder + "/props.txt");
} catch (Exception xx) {
xx.printStackTrace();
}
prop.load(in);
in.close();
is my approach to use a catch to get the local path OK or is there a better way to code this?
Better way is to put the txt file in user home directory and get it by
System.getProperty("user.home");
and to get the full path
String pathToFile = System.getProperty("user.home") + File.separator + "data" + File.separator + "props.txt";
It would work across all the platform, provided that you need to put the file at proper place (user home)