How to load the image from a jar file? - java

This code works only if I run my project, but if I run the Jar file, I get a NullPointerException. The image is in src directory.
try {
URL resource = Sticker.class.getResource("\\transparentSticker.png");
img = null;
this.img = ImageIO.read(Paths.get(resource.toURI()).toFile());
System.out.println("c");
} catch (IOException | URISyntaxException e) {
System.out.println("caught");
}
If I use this code, an IllegalArgumentException is being thrown.
InputStream input = Sticker.class.getResourceAsStream("\\transparentSticker.png");
if (input == null) {
input = Sticker.class.getClassLoader().getResourceAsStream("\\transparentSticker.png");
}
try {
img = ImageIO.read(input);
} catch (IOException e) {
e.printStackTrace();
}
How to load the image?

You did say the PNG is in the src folder?
Let's see, after reading this and this, I think it needs to be:
InputStream input = Sticker.class.getResourceAsStream("/src/transparentSticker.png");
or
URL resource = Sticker.class.getResource("/src/transparentSticker.png");
Think unix, not windows.

Related

problem when upload file in play framework

I tried uploading a file, and placed the file in the "public / images" directory and it worked, but the file I uploaded was zero in size and certainly couldn't be opened
public Result upload() throws IOException {
Http.MultipartFormData<File> requestBody = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> profile_pic = requestBody.getFile("profile_pic");
String dirPath = "public/images/";
if(profile_pic != null) {
String name = profile_pic.getFilename();
File file = profile_pic.getFile();
System.out.println(file);
File theDir = new File(dirPath);
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdirs();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
try {
File filex = new File(dirPath + name.toLowerCase());
filex.createNewFile();
file.renameTo(filex);
}catch (Exception e) {
// TODO: handle exception
}
return ok("File uploaded ");
}else {
return badRequest("Eroor");
}
}
this is my file after upload
I think creating a new file and renaming your old file to that name may cause trouble. I would recommend using the move method, see docs here.
Does your System.out.println(file); print what looks like a normal png file?

ImageIO can't read image input file

This is my first post. Excuse me if I'm making an obvious mistake.
BufferedImage img = null;
File file = new File("com/game/assets/badlogic.jpg");
try {
img = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
This is my code and it can't read my image input file for some reason.
This is the error message:
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at com.engine.Main.run(Main.java:41)
at java.base/java.lang.Thread.run(Thread.java:844)
at com.engine.Main.start(Main.java:32)
at com.game.GameManager.main(GameManager.java:51)
I have no clue what am I doing wrong. Anyways Thank You, kind Strangers.
I got it to work!
BufferedImage img = null;
try {
img = ImageIO.read(new FileInputStream("/Users/earmalys/Desktop/InteliJ projects/mantengine/src/com/game/assets/badlogic.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
But the file path is very exact. Is there anyway I can get around this?
Whenever I get a BufferedImage from a file, I find it much easier to use a FileInputStream rather than a File. Here's an example:
try {
BufferedImage image = ImageIO.read(new FileInputStream("com/game/assets/badlogic.jpg"));
}
catch (IOException e) {
e.printStackTrace();
}

Generate doc use docx4j, it gose different on windows and linux server

when I use docx4j to generate doc from HTML and output through java servlet, it works well on Windows system, I can download and open the doc file normally.
When I put the project on Linux server, I can also download the doc file, but when openging file, it alert that the file is broken. I must click the confirm and restore the file.then open it normally.
my core code is like this.
how can i get the same result as windows?
code in jsp:
String vhtml = DownHtml2DocUtil.replaceSvgData2Base64(request);
response.reset();
response.setContentType("application/octet-stream");//设置为字节流
OutputStream output = null;
try {
output = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".doc");
DownHtml2DocUtil.genDocFromHtml(vhtml, output);
} catch (Exception e) {
} finally {
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
}
}
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
code in java like this:
public static void genDocFromHtml(String html, OutputStream out)
throws EMPException {
try {
WordprocessingMLPackage wordMLPackage;
wordMLPackage = WordprocessingMLPackage.createPackage();
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(
wordMLPackage);
wordMLPackage.getMainDocumentPart().getContent()
.addAll(XHTMLImporter.convert(html, "utf-8"));
// wordMLPackage.save(out); -- i tried both method
new Save(wordMLPackage).save(out);
} catch (InvalidFormatException e) {
throw new EMPException(e);
} catch (Docx4JException e) {
throw new EMPException(e);
} catch (Exception e) {
e.printStackTrace();
}
}
any suggestion will be appreciate , thanks anyway;

How to place a file for jar and read it with FileInputStream

This is the code
public static void readCharacters() {
try (FileInputStream fi = new FileInputStream("main/characters.dat"); ObjectInputStream os = new ObjectInputStream(fi)) {
characterList = (LinkedList<Character>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is the structure:
And this is the Error
java.io.FileNotFoundException: main\characters.dat (The system cannot find the path specified)
What I want is to include the characters.dat file in my jar, and be able to read and write it while the program runs. Is there a different way to write the path? or to put the .dat file in a different position.
Also the writing method:
public static void writeCharacters() {
try (FileOutputStream fs = new FileOutputStream("main/characters.dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing Characters...");
os.writeObject(characterList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can't. You can do one or the other. JAR files are not file systems, and their entries are not files. You can read it with an input stream:
InputStream in = this.getClass().getResourceAsStream("/main/characters.dat");
Check it for null before proceeding.
The jar is for read-only resources. You can use it for the initial file, as a kind of template.
Path path = Paths.get(System.getProperty("user.home") + "/myapp/chars.dat");
Files.mkdirs(path.getParentPath());
if (!Files.exists()) {
try (InputStream in =
Controller.class.getResourceAsStream("/main/characters.dat")) {
Files.copy(in, path);
}
}
The above copies the initial.dat resource from the jar to the user's home "myapp" directory, which is a common solution.
System.getProperty("user.dir") would the running directory. One can also take the jar's path:
URL url = Controller.class.getResource("/main/characters.dat");
String s = url.toExternalForm(); // "jar:file:/.... /xxx.jar!/main/characters.dat"
From that you can also construct the jar's directory. Mind to check Windows, Linux, spaces and such.
URL url = Controller.class.getProtectionDomain().getCodeSource().getLocation();
The solution above risks a NullPointerException, and works a bit differenly running inside the IDE or stand-alone.
Important note:
When using getResourceAsStream, you must start your path by slash /, this specifies the root of your jar, .getResourceAsStream("/file.txt");
In my case my file was a function argument, String filename, I had to do it like this:
InputStream in = this.getClass().getResourceAsStream("/" + filename);

Loading images in java (eclipse vs IntelliJ)

One would load an image:
project>res>img.png (path = "res/img.png")
BufferedImage image = loadImage(path);
Where LoadImage is:
protected BufferedImage loadImage(String path) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(path));
} catch(IOException e) {
System.err.println("could not load: " + path);
}
return img;
}
Someone using Eclipse used:
(path = "/img.png")
BufferedImage image = null;
try {
image = ImageIO.read(Sprite.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
But using this in IntelliJ gives:
Exception in thread "Game_main" java.lang.IllegalArgumentException:
input == null!
why getResourceAsStream fails?
getResourceAsStream() uses (by default) the system classloader to find the file. Therefore, the resources directory has to be on the classpath - check that the IntelliJ project is correctly including the res directory and marking it as a resource directory.

Categories