I am trying to set System.setProperty to a file path:
//properties key
String propFile = "propertiesFile";
String pathToFile = "properties/prop.properties";
File file = new file(pathToFile);
//properties value
String path = file.getAbsolutePath();
System.setProperty(propFile, path);
//using properties.....
And I am getting FileNotFoundException.
when printing the file I get the absolutePath - c:\Project...\prop.properties
Is setting System.setProperty should be done another way?
the properties - package inside src.
Your problem is not related to the method System.setProperty as your path is managed as any other String, your problem is more that new File(pathToFile) refers to a non existing file as you provide a relative path and the absolute path is created from the user directory (value of System.getProperty("user.dir")) which is probably not what you expect. If you call new File(pathToFile).exists() it will return false check the resulting path first.
Related
I created an empty File and store the extracted value/content from a jar. The jar is running on linux.
String filename ="base_script";
File targetFile = new File( filename + ".sh");
String pathStr=null;
//empty file
targetFile.createNewFile();
if(targetFile.exists()) {
InputStream link = (getClass().getResourceAsStream(this.userScriptPath));
Files.copy(link,
targetFile.getAbsoluteFile().toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
pathStr = targetFile.getAbsolutePath();
}
This is the file path ./base_script.sh
And this is file absolute path apps/MyApps/./base_script.sh
My question is why there's an extra ./ on the absolute path?
It's not clear why you have "./" in the name as you define the value without it. Anyway this will resolve the path to the real name without any "./" or ".." in a path:
pathStr = targetFile.toPath().toRealPath().toString()
I have to access a database file in my Java project but I can't get the path right.
The full path is C:\Hogwarts\db\hogdb.fdb.
I tried to use this code line to find the the current relative path:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
and it says the current relative path is: C:\Hogwarts.
Right now my code looks like this :
minDataBas = new InfDB("db\\HOGDB.FDB");
new HuvudFonster(minDataBas).setVisible(true);
What am I missing?
In fact all elements are there; just use an absolute path.
String cwd = System.getProperty("user.dir"); // Alternative
Path cwdPath = Paths.get(cwd);
Path dbPath = Paths.get(cwd, "db/hogdb.fdb");
String db = dbPath.toAbsolutePath().toString();
if (!Files.exists(dbPath)) {
throw new IllegalStateException("Wrong path for database: " + db);
}
minDataBas = new InfDB(db);
From the InfDB.java file:
#param path Path to the Firebird DB, for example C:/DB.FDB or for Mac /User/DB.FDB
Providing the absolute path, as opposed to relying on the method inferring you are using a relative path, should resolve the issue. Hence, use:
minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");
or if you know that the database file will be similarly relative to the current working directory for wherever it has launched, you could use the previously found working directory path and append the remaining location as such
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
minDataBas = new InfDB(s + "\\db\\HOGDB.FDB");
If you cannot be sure where the file will there are a variety of techniques you could use to have the user define where the file is. Setting a path variable, configuration files or simply taking user input.
I think instead it should be
minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");
I am reading properties file to get a file path as below.
String result = "";
InputStream inputStream = null;
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = GetPropertyValues.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
The properties file has the path specified like below.
configSettingsFilePath = C:\\\\ConfigSetting.xml
Now I get this below exception when I run my code saying file is not found.
Creating instance of bean 'configSettingHelper'
configSettingsFilePath = C:\ConfigSetting.xml
2017-09-18 14:47:00 DEBUG ConfigSettingHelper:42 - ConfigSettingHelper :: ConfigSetting File:configSettingsFilePath = C:\ConfigSetting.xml
javax.xml.bind.UnmarshalException
- with linked exception:
[java.io.FileNotFoundException: C:\Java\eclipse\eclipse\configSettingsFilePath = C:\ConfigSetting.xml (The filename, directory name, or volume label syntax is incorrect)]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
Instead of reading the path from properties file, if I directly use "C:\ConfigSetting.xml" in the code, it reads the file.
Can you please suggest what I should use in the properties file to specify the path?
Reading the file only fails when the .jar is running.
Running the app from within Netbeans is fine. (Different path)
Also, the path is coming from
URL resourceURL = MyClass.class.getResource("mydir/myfile.txt");
Printing out the path is perfect.
Also, a mypicture.gif in the very same directory loads fine:
ImageIcon mypicture = new ImageIcon(imageURL, description)).getImage();
even when running the .jar. IE: the actual path must be fine.
It is only a text file I try reading via
InputStream input = new FileInputStream(fileName);
is when it fails - and only if it is in the jar.
This is probably because C:\ is not on the classpath. You're using getClassLoader() which presumably returns a ClassLoader.
According to the docs for ClassLoader#getResource:
This method will first search the parent class loader for the
resource; if the parent is null the path of the class loader built-in
to the virtual machine is searched. That failing, this method will
invoke findResource(String) to find the resource.
That file is in the root of the drive, which is not going to be on the classpath or the path of the class loader built-in to the VM. If those fail, findResource is the fallback. It's unknown where findResource looks without seeing the implementation, but it doesn't appear to pay attention to the C:.
The solution is to move the properties file into your classpath. Typically, you'd put property files like this in the src/main/resources folder.
String dirPath = fileObj.getParentFile().getAbsolutePath();
system.out.println(dirPath);
I tried this way but its returning the Java Project Path that is Workspace path..
.getParentFile() is probably returning the parent directory, which depending on the location of your file could be the project directory. If fileObj is an object of type File, just try using fileObj.getAbsolutePath() instead.
So try this:
File fileObj = new File("myFile.xls");
String dirPath = fileObj.getAbsolutePath();
System.out.println(dirPath);
This should result in output similar to:
C:/[your project directory]/myFile.xls
JavaDoc for getParentFile():
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#getParentFile()
Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...