i want to open a file and return its content. Although it is in the same directory like the class that wants to open the file, the file can't be found. Would be cool if you could help me solving the problem.
Here is the code:
#GET #Produces("text/html") #Path("/{partNO}/") #Consumes("text/html")
public String getPartNoResponseHTML(#PathParam("partNO") String parID) throws WebApplicationException {
PartNoTemplate partNo = getPartNoResponse(parID);
String result = "";
try {
result = readFile(PART_NO_TEMPLATE_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
return e.getMessage() + e.toString();
// throw new WebApplicationException(Response.Status.NOT_FOUND);
} finally {
result = result.replace("{partNO}", parID);
result = result.replace("{inputFormat}", partNo.getFormat().toString());
}
return result;
}
I guess it can't find the file, because its running on tomcat. I'm also using Jersey and JAX-RS. Thank you for your help,
Maxi
If the file is inside the application WAR (or in a jar) you can try by using
InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");
Your problem is similar (I think) with How can I read file from classes directory in my WAR?
Try to get the path of the file from ServletContext.
ServletContext context = //Get the servlet context
In JAX-RS to get servlet context use this:
#javax.ws.rs.core.Context
ServletContext context;
Then get the file from your web application:
File file = new File(context.getRealPath("/someFolder/myFile.txt"));
You don't post the code that actually tries to read the file, but assuming the file is in the classpath (as you mention it's in the same directory as the class) then you can do:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
See here
Related
Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?
I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U
The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);
I am trying to load a properties file from WEb-INF folder in my web application , which is running on Websphere 8.5 . I am using below code to load the file from the location
public class Init {
private final String WEB_INF_DIR_NAME="WEB-INF";
private String web_inf_path;
private final Properties APP_PROPERTIES =null;
InputStream inputStream = null;
public String getWebInfPath() throws IOException {
if (web_inf_path == null) {
web_inf_path = URLDecoder.decode(Init.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF8");
web_inf_path=web_inf_path.substring(0,web_inf_path.lastIndexOf(WEB_INF_DIR_NAME)+WEB_INF_DIR_NAME.length()).substring(1);
}
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
// inputStream = this.getClass().getClassLoader().getResourceAsStream("/config/localhost/accountservice.properties");
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
System.out.println(APP_PROPERTIES.getProperty(AccountServiceDataAccessConstants.INET_LIBRARY_NAME)); // Here i am getting NULL
return web_inf_path;
}
}
I have also tried using servlet context , but its also giving me NULL. I have tried all possible ways to solve it but unfortunately i am not able to do it. I am also giving my folder structure.
Please excuse me if this is a silly question , but i am not really getting any idea about it.
Usually, everything in WebContent is placed in the root of your WAR file. So instead of
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
It would be
inputStream = Init.class.getResourceAsStream("/WEB-INF/config/localhost/accountservice.properties");
The root of the WAR has WEB-INF in it, and then you can descend into your folder structure as normal.
I'm trying to unmarshal my xml file:
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
But I get this errors:
java.io.FileNotFoundException: null (No such file or directory)
Here is my structure:
Why I can't get files from resources folder? Thanks.
Update.
After refactoring,
URL url = this.getClass().getResource("/xmlToParse/companies.xml");
File file = new File(url.getPath());
I can see an error more clearly:
java.io.FileNotFoundException: /content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml (No such file or directory)
It tries to find WEB-INF/classes/
I have added folder there, but still get this error :(
I had the same problem trying to load some XML files into my test classes. If you use Spring, as one can suggest from your question, the easiest way is to use org.springframework.core.io.Resource - the one Raphael Roth already mentioned.
The code is really straight forward. Just declare a field of the type org.springframework.core.io.Resource and annotate it with org.springframework.beans.factory.annotation.Value - like that:
#Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;
To obtain the needed InputStream, just call
companiesXml.getInputStream()
and you should be okay :)
But forgive me, I have to ask one thing: Why do you want to implement a XML parser with the help of Spring? There are plenty build in :) E.g. for web services there are very good solutions that marshall your XMLs into Java Objects and back...
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
you are suppose to give an absolute path (so add a loading ´/´, where resource-folder is the root-folder):
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("/xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
I need to access a file inside the currently executed .jar using a URL.
URL url = BlockConverter.class.getResource("/test.txt");
System.out.println(url.toString());
InputStream is = url.openStream();
This is what I did.
The output is:
jar:file:/C:/Users/User/Desktop/SERVER/plugins/MyJar.jar!/test.txt
My InputStream always ends up throwing an IOException when being initialized, even though the URL is being output correctly.
So how is that possible?
Why can't I open the stream?
EDIT:
Also, please don't answer with "use getResourceAsStream", since it uses the same kind of code:
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
I would open it as a stream directly e.g.
InputStream is = BlockConverter.class.getResourceAsStream("/test.txt");
The above method is the way I normally access resources within a jar (it will open the resource regardless of it being packaged within a jar, or simply as an unpackaged deployment, note)
protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Sending Birthday Wishes... ");
try
{
for(int i=0;i<maillist.length;i++)
{
Email email = new Email();
email.setFrom("spv_it#yahoo.com");
email.setSubject("Happy IndependenceDay");
email.setTo(maillist[i]);
email.setText("<font color=blue><h4>Dear Users,<br><br><br>Wish you a Happy Independence Day!<br><br><br>Regards,<br>Penna Cement Industries Limited</h4></font>");
byte[] data = null;
ClassPathResource img = new ClassPathResource("newLogo.gif");
InputStream inputStream = img.getInputStream();
data = new byte[inputStream.available()];
while((inputStream.read(data)!=-1));
Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);
email.addAttachment(attachment);
emailService.sendEmail(email);
}
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is the error I'm getting:
java.io.FileNotFoundException: class path resource [newLogo.gif] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:135)
at com.mail.schedular.BirthdayWisherJob.executeInternal(BirthdayWisherJob.java:55)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
The best practise is to read/write or to provide reference of any file is by mentioning the ABSOLUTE PATH of that file.
To your question, It shows the FileNotFoundException because, JVM failed to locate the file in your current directory which is by default your source path. So provide the absolute path in ClassPathResource or copy that image file to your current directory. It will solve your problem.
I think you need to put your file inside inside the src folder , if it's there then check whether it's under some directory which is inside the src directory.
Then give the correct location like given details below
src[dir]----->newLogo.gif
ClassPathResource img = new ClassPathResource("newLogo.gif");
or,
src[dir]----->images[dir]---->newLogo.gif
ClassPathResource img = new ClassPathResource("/images/newLogo.gif");
You got this error since the job is running in a separate quartz thread, I suggest that you locate your file newLogo.gif outside the jar and use the following to load it.
Thread.currentThread().getContextClassLoader().getResource("classpath:image/newLogo.gif");