Issue
I have been trying to upload image
to database. So I made a browse
button to go through directories and get the image. Suppose if no image is selected, a default image
will be uploaded to the database. The image is stored in a folder named 'resources'
under source folder.In the image, helper is the folder containting .java files and below is the resources
folder I am uploading the image as FileInputStream
and the code is
File pic=new File(imgloc);
FileInputStream fis=new FileInputStream(pic);
If the image is not selected to upload a default image my code is
File pic=new File(this.getClass().getResource("/resources/profile1.png").getFile());
FileInputStream fis=new FileInputStream(pic);
And my query to database is
ps.setBinaryStream(1,fis ,(int) pic.length()); //While substituing for '?' in query
After build to jar it produce FileNotFoundException
when trying to add default image. May be the question is asked several times I didn't find solution in that. I want read the image as file..Thanks in advance.
Solution
to help illustrate I create a project with a source directory
src
below source I had a package starthere
with a class Main
I create another source directory xxx
and put in a file a.txt
I also created under xxx
a directory called text
and put in a file named b.txt
Also I created under src
a directory called other
and put in a file called c.txt
My code is
URL url = Main.class.getResource("/a.txt");
System.out.println(url);
URL url2 = Main.class.getResource("/text/b.txt");
System.out.println(url2);
URL url3 = Main.class.getResource("/other/c.txt");
System.out.println(url3);
and my output is
D:\temp>java -cp ab.jar starthere.Main
jar:file:/D:/temp/ab.jar!/a.txt
jar:file:/D:/temp/ab.jar!/text/b.txt
jar:file:/D:/temp/ab.jar!/other/c.txt
edit
As you are not wanting to use a File, but simply the InputStream, you can use
InputStream fis = Main.class.getResourceAsStream("/a.txt");
and then set using ps.setBinaryStream(1, fis);
Answered By - Scary Wombat
Answer Checked By - Clifford M. (JavaFixing Volunteer)