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();
Related
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'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();
EDIT: I recommend against saving .jasper files to the temp directory and then attempting to load from that location. It's a lot of trouble.
I am attempting to add JasperReport functionality to a Spring web app. The idea is that a pre-compiled .jasper file can be added to the server's Temp folder and filled then exported by the user.
I can successfully read .jrxml from the classpath, compile it into a JasperReport, fill it, and export it within the same method. In trying to separate these tasks, I've run into trouble. Specifically, when attempting to open an input stream from the temp directory.
The following code successfully creates a compiled .jasper file in the temp directory (I have omitted checks against filename for brevity).
Resource res = appContext.getResource("classpath:jasperreports/"
+ filename + ".jrxml");
File f = new File(
org.apache.commons.lang.SystemUtils.getJavaIoTmpDir(), filename
+ ".jasper");
JasperCompileManager.compileReportToStream(res.getInputStream(),
new FileOutputStream(f));
Trying to READ from the temp folder causes a problem. After checking the temp folder for the newly-created .jasper, I call the following code.
Map<String, Object> params = new HashMap<String, Object>();
String resourcePath = org.apache.commons.lang.SystemUtils.getJavaIoTmpDir().getPath().toString();
Resource compiledReport = appContext.getResource(resourcePath + "/" + filename + ".jasper");
//Directly accessing the folder didn't work, either
//Resource compiledReport = appContext.getResource("C:/Users/<MyUsername Here>/AppData/Local/Temp/SimpleEmployeeReport.jasper");
JasperPrint filledReport = JasperFillManager.fillReport(compiledReport.getInputStream(),
params, mds.getConnection());
Which results in an exception thrown at getInputStream:
java.io.FileNotFoundException: Could not open ServletContext resource [/C:/Users/<MyUsername>/AppData/Local/Temp/SimpleEmployeeReport.jasper]
I'd appreciate any light you can shed on this!
Multipart held tmp files that caused new file names. Creating my own temp directory solved the issue. On Linux the getProperty is missing the trailing slash
String tempDirectory = System.getProperty("java.io.tmpdir");
if( !tempDirectory .endsWith("/") && !tempDirectory .endsWith( "\\") ) {
tempDirectory = tempDirectory +"/";
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()