I'm using camel to create some routes.
I have a file in the resources folder and I only want the file path + name. Not the content.
When I use:
from(URI)
.log("resource:classpath:llave.txt")
I got the content of llave.txt but I need something like
C:\something\llave.txt
Thanks!!
Edit for clarity: I do not need the file information from a File endpoint (also, is easy get that info using file language or the exchange's header).
I need the info of a file located in the resource folder in the project.
Get the file:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("llave.txt").getFile());
Get the path:
//full path ( including the file )
String absolutePath = file.getAbsolutePath();
// path only
String filePath = absolutePath.
substring(0, absolutePath.lastIndexOf(File.separator));
You can access the path using the headers that Camel sets after calling the File component:
from(URI)
.log("$simple{headers.CamelFileAbsolutePath}")
You can read more about the File component here:
http://camel.apache.org/file2.html
With java.nio you can get the full path:
String fullPath = Paths.get(getClass().getResource("llave.txt").toURI()).toString();
And the file name:
String fileName = Paths.get(getClass().getResource("llave.txt").toURI()).getFileName();
Related
I get the error "java.io.FileNotFoundException: AuthKey_7RHM5B8NS7.p8 (No such file or directory)", the file is clearly in my directory and I am using the relative path for the file. Here is my projects directory.
Project directory Image
final ApnsClient apnsClient = new ApnsClientBuilder()
.setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setSigningKey(ApnsSigningKey.loadFromPkcs8File(new File("AuthKey_7RHM5B8NS7.p8"),
"GL87ZNESF6", "7RHM5B8NS7"))
.build();
As you are trying to fetch file from resource folder hence you need to specify path for that.
File file = new File(getClass().getResource("/AuthKey_7RHM5B8NS7.p8").getFile());
or to get the URL
URL res = getClass().getClassLoader().getResource("AuthKey_7RHM5B8NS7.p8");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
You should not use the ApnsSigningKey.loadFromPkcs8File method but instead use the loadFromInputStream method.
The reason is that you are using a resource - and if you build a JAR file from your code, as is often done, your resource will be inside the JAR file and you will not be able to get a File object that points to it.
Code:
InputStream in = getClass().getResourceAsStream("/AuthKey_7RHM5B8NS7.p8");
final ApnsClient apnsClient = new ApnsClientBuilder()
.setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setSigningKey(ApnsSigningKey.loadFromInputStream(in, "GL87ZNESF6", "7RHM5B8NS7"))
.build();
in.close();
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.
I'm trying to create a new file in:
project/src/resources/image.jpg
as follows:
URL url = getClass().getResource("src/image.jpg");
File file = new File(url.getPath());
but I get error:
java.io.FileNotFoundException: file:\D:\project\dist\run560971012\project.jar!\image.jpg (The filename, directory name, or volume label syntax is incorrect)
What I'm I doing wrong?
UPDATE:
I'm trying to create a MultipartFile from it:
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "image/jpeg", IOUtils.toByteArray(input));
You are not passing the image data to the file!! You're trying to write an empty file in the path of the image!!
I would recommend our Apache friends FileUtils library (getting classpath as this answer):
import org.apache.commons.io.FileUtils
URL url = getClass().getResource("src/image.jpg");
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
FileUtils.copyURLToFile(url, f);
This method downloads the url, and save it to file f.
Your issue is that "image.jpg" is a resource of your project.
As such, it's embedded in the JAR file. you can see it in the exception message :
file:\D:\project\dist\run560971012\project.jar!\image.jpg
You cannot open a file within a JAR file as a regular file.
To read this file, you must use getResourceAsStream (as detailed in this this SO question).
Good luck
I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.
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...