I'm trying access image in java code.
For jboss server getting file not found exception.
Image logo = new getImage("/images/test_image.bmp");
public getImage(String fileName) throws Exception
{
try{
image=Image.getInstance(ImageIO.read(getClass().getResourceAsStream(fileName)),null);
}catch (Exception e ){
e.printStackTrace();
}
}
exception -
java.io.FileNotFoundException: /images/test_image.bmp
test_image.bmp is stored in src->images folder.
Is there any solution?
Yes you can achieve this by using ServletContext as follows
ServletContext servletContext = new ServletContext();
String relativePath = "/images/test_image.bmp";
String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
Image img = Image.getInstance(absoluteDiskPath);
use img object where you want.
Related
I'm new to SpringBoot web dev.
I need to save an image to a directory in the current project. I have given path as "String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();" but the image not save to the "./src/main/imageuploads/" directory in eclipse project.
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(#RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
This is the saveFile method for ref.
public static void saveFile(MultipartFile multipartFile, String fileName, String uploadDir) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
System.out.println(filePath.toFile().getAbsolutePath());
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
I need to upload the image to this directory,
when I get the absolute path, it shows like this "/Users/chathura/eclipse/jee-2021-03/Eclipse.app/Contents/MacOS/./src/main/imageuploads/24/new file.jpg".
There is no way to go to this directory but I can access that directory using the terminal.
Please tell me what is the mistake here?
Note : I'm using macos
Thanks in advance
Could you try 'src/main/resources/imagesuploads' (without .)
Just a reminder: This directory will disappear when you package your application (production mode)
This directory should be configurable from an external file (application. properties for example)
Thank you Ali, your response gave a lead to the solution. My project sits on MacOS partition therefore, I couldn't write a file without permission. I simply changed the location to another partition and it worked.
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(#RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "/Volumes/My Data/Fileupload"+ savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
Thank you
I am new to Spring-boot/Java and trying to read the contents of a file in a String.
What's the issue:
I'm getting "File not found exception" and unable to read the file. Apparently, I'm not giving the correct file path.
i've attached the directory structure and my code. I'm in FeedProcessor file and want to read feed_template.php (see image)
public static String readFileAsString( ) {
String text = "";
try {
// text = new String(Files.readAllBytes(Paths.get("/src/main/template/feed_template_head.php")));
text = new String(Files.readAllBytes(Paths.get("../../template/feed_template_head.php")));
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
You need to put template folder inside resource folder. And then use following code.
#Configuration
public class ReadFile {
private static final String FILE_NAME =
"classpath:template/feed_template_head.php";
#Bean
public void initSegmentPerformanceReportRequestBean(
#Value(FILE_NAME) Resource resource,
ObjectMapper objectMapper) throws IOException {
new BufferedReader(resource.getInputStream()).lines()
.forEach(eachLine -> System.out.println(eachLine));
}
}
I suggest you to go though once Resource topic in spring.
https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/resources.html
I know what the problem is I just do not know how to fix it. So I have an image that I am trying to render in my program. I use ImageIO to load the image. But it seems to have a problem wit the path I am giving it. I am using NetBeans as my IDE and I dont know if I am saving the image file correctly.
First method:
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/sprite_sheet.png");
}catch(IOException e){
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1,1,32,32);
}
the loader BufferedImageLoader class:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
I have the image saved under a 'res' folder under 'src' folder.
Error:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
Thank you.
Why do you need to use getClass().getResource() ?
Most simple usage of ImageIO.read is as follows.
image = ImageIO.read(new File(path));
You may need to add folders to path also.
spriteSheet = loader.loadImage("/src/res/sprite_sheet.png");
Try using an absolute path for your file or if you need a relative check this post (eg assuming you have a res folder under default package did you try "/res/yourfile"
Im trying to load an image from my res folder which is already part of the Java BuildPath. Sadly it seems I am no able to find the image neither with relative nor with an absolute path to the file.
Im always getting this error message:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at schneider.twodgame.BufferedImageLoader.loadImage(BufferedImageLoader.java:14)
at schneider.twodgame.Game.init(Game.java:64)
at schneider.twodgame.Game.run(Game.java:99)
at java.lang.Thread.run(Unknown Source)
And here is a part of the code:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException {
System.out.println(getClass());
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
This is the method I am trying to load the image with. The method is part of my Main Class:
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/res/sprite_sheet.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Have a look here.
spriteSheet = loader.loadImage("/sprite_sheet.png");
Should work.
It is currently looking in your .class file folder or .jar file at the location of your class files in:
[root folder of class files]/res/sprite_sheet.png
Maybe it should be looking in:
[root folder of class files]/schneider/twodgame/res/sprite_sheet.png
In that case you should remove the leading slash (/).
I have a form with that code:
public Form()
{
initComponents();
try
{
File file= new File("avatar.jpg");
BufferedImage image= ImageIO.read(file);
}
catch (IOException ex)
{
System.out.println("Failed to load image");
}
}
The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:
What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?
Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().
It would be something like:
public class Test {
private static final String absName = "/yourpackage/yourimage.jpg";
public static void main(String[] args) {
Class c=null;
try {
c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
} catch (Exception ex) {
// This should not happen.
}
InputStream s = c.getResourceAsStream(absName);
// do something with it.
}
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResourceAsStream(name); // A system class.
}
return cl.getResourceAsStream(name);
}
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResource(name); // A system class.
}
return cl.getResource(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
}
Reference:
Accessing Resources
It looks like you have a namespace of poker.*
It all depends on where the jvm is initialized from.
Where is your main? Is it in /Users/ramy/NetBeansProjects/Poker/src?
Also, I suggest you use getResource() for all of your file loading needs, especially inside jars.
this.getClass().getResource("/resource/buttons1.png")
or
this.getClass().getResourceAsStream("/resource/TX_Jello2.ttf")
You can find out where your programs default path is by doing the following:
System.getProperty("user.dir");
Without seeing the error I would say the most likely cause is it can't find the file. So I suggest you replace "avatar.jpg" in the File constructor with the absolute file path to it. e.g.
File file = new File("INSERT_PATH_TO_FILE/avatar.jpg");
You cannot assume the image will be "there" because the relative path between your .java and the image seems ok.
Accessing a resource depends of your "kind" of project (Web, standalone....). In your case, you can try to get the image from your classpath
final File inputFile = new ClassPathResource("....").getFile();
final BufferedImage inputImg = ImageIO.read(inputFile);