How to import an Image to Project resource folder - java

I'm developing a java based application using NetBeans.
What i want to do:
My project folder includes a resources folder which contains all the Images that are needed by the project for basic stuff (setting background,icons etc).
Now suppose end user wants to save an new Image on the run time. File Chooser opens up. User selects a source(.jpg) file and the image gets copied. What i want is, to save this image to my resources folder rather than on LocalDisk path. I'm having no trouble copying this image to a LocalDisk path.
Is there any way through which i can do this?
My resource folder path is:
(ProjectName)\src\resources
Code I'm using to save image to Local Address:
InputStream input = null;
OutputStream output = null;
String fileName = itemId.getText();
try
{
input = new FileInputStream(srcPath.getText()); //Getting Source File Absolute Path Through FileChooser
output = new FileOutputStream("C:\\Users\\BUN\\Documents\\Folder\\"+fileName+".jpg");
byte[] buf = new byte[1024];
int bytesRead;
while((bytesRead = input.read(buf))>0)
{
output.write(buf,0,bytesRead);
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
Thank's in advance!

Related

Java: Read image from current src directory

I would like to load an image from my current src directory where the java class files are located as well. However, I always get an IOException..
And how can I make sure the file gets loaded properly on Mac/Linux as well on Windows?
My code so far:
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
IOException message:
Can't read input file!
(My path is correct - is it because of the space between Google and Drive?)
/Users/myMac/Google Drive/Privat/Programming/Logo_transparent.png
Kind regards and thank you!
I think It's because you didn't create the file, You can create the file if it doesn't exist by using this code
if(!imageFile.exists()) imageFile.createNewFile();
You're code will look like this
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
if(!imageFile.exists()) imageFile.createNewFile();
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
Also you shouldn't concat child files like that instead pass it as a second argument.
File imageFile = new File(System.getProperty("user.dir"), "Logo_transparent.png");
If your image files will be packaged together with your class files (for example in the same .jar) you should not use File but read it as a resource:
bufferedImage = ImageIO.read(this.getClass().getResourceAsStream("/Logo_transparent.png"));
Notice the '/' before the file name. This means to search in the root path of the classpath.
If you specify without / it will search in the package of this (the current class)
this.getClass().getResourceAsStream("Logo_transparent.png")
You can try to build the absolute path to the image like here and read it afterward.

How do you send an html file along with its images through a socket in java

I'm required for a project to send an html file through a socket in Java. I managed to get the text to appear in the browser but none of the pictures load. I found this code online to help me send the html file in the first place, but I am wondering if there is any way to send the pictures. I have all of the images in an img folder, which is where the html file is located.
public class SimpleFileServer {
public final static int SOCKET_PORT = 9000; // you may change this
public final static String FILE_TO_SEND = "D:\\Project 2\\index.html"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
try {
sock = servsock.accept();
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
System.out.println("Done.");
} finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
} finally {
if (servsock != null) servsock.close();
}
}
}
Are you sure your project does not also require you to parse the HTML and request the images separately? It sounds like you're simulating something like a web server. Generally speaking a browser will download the HTML of a page, parse it, then send follow-up requests to the server for each image or other resource (CSS, off-site Javascript, etc.) contained in the page.
Doing one request per resource can also simplify your server, because it only has to deal with the resource being requested at the time, which pushes some of the logic and complication back onto the client to be able to know which resources to ask for.
Things have changed somewhat in HTTP 2, but that's another matter that is probably outside the scope of your question.
Typically, image files are not included in the html download, but are requested subsequently as the html file is parsed. The problem of why the images are not showing in your case can probably be fixed by correcting the src locations in the tags. IF you do need to download everything together though, I would recommend sending a .zip archive
I think you are trying to achieve the "save as" functionality in web browsers.
You need to save the html file separately and the assets such as image files, embedded contents separately.
Since you already have the images in img folder, you need to alter the src attribute of image tag in the html - to pick the images from the image folder.

Save a directory from a jar file to the user's disk

I need to save a directory of resource files from the currently running JAR file to a temporary directory on the user's disk.
Currently, I'm saving files one by one. But now I have a large folder of native libraries to save that I would rather not save this way.
I tried my current code, just in case it treated the directory as a file and saved it anyway.
public void saveResource(String name, File outFile) {
try (InputStream in = this.getClass().getResourceAsStream(
name);
OutputStream out = new FileOutputStream(outFile);) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
But sadly, it didn't work. So what's the best way to save a directory of resources to disk?
You need to loop through all the files in that folder and save the files one by one. I guess this is what you are doing now. You can't copy the folder entirely.
or you can use commons-io FileUtils

FileUploader - Save data in the project

I am uploading a file with the PF 3.5 File Uploader
My Upload Method looks like that:
public void handleFileUpload(FileUploadEvent event) {
log.info("Method handleFileUpload invoked");
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
InputStream inputStream = null;
OutputStream out = null;
try {
File targetFolder = new File("\\resources\\uploads");
if(!targetFolder.exists()) {
targetFolder.mkdirs();
}
inputStream = event.getFile().getInputstream();
File outFile = new File(targetFolder, event.getFile().getFileName());
log.info("copy file stream to " + outFile.getAbsolutePath());
out = new FileOutputStream(outFile);
int read = 0;
byte[] bytes = new byte[size];
log.info("read file stream");
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
} catch (IOException e) {
log.error(e);
} finally {
...
}
at the moment my files get uploaded to \\resources\\uploads". Thats the path to a folder on theC:`.
However, I want to upload my uploads to a path in my eclipse project. How to change the path? I really appreciate your answer!!!
However, I want to upload my uploads to a path in my eclipse project.
That's absolutely not recommended for the reasons mentioned in this answer: Uploaded image only available after refreshing the page. The point is: the IDE's workspace and server's deploy folder is absolutely not intented as a permanent file storage. The uploaded files would be unreachable and/or disappear like by magic.
Just keep them in a path external to the IDE's workspace and server's deploy folder. You're doing it fine. I'd only make the path configurable by a system property, environment variable or properties file setting so that you don't need to edit, recompile, rebuild, etc the code everytime when you change the upload location.
If your concrete problem is more the serving of the uploaded file, then just add the upload folder as another context in server's configuration, or create a simple servlet for the serving job, or as you're using PrimeFaces, just use <p:fileDownload> or <p:graphicImage> with StreamedContent pointing to the desired FileInputStream.
See also:
How to save uploaded file in JSF

Create a file object from a resource path to an image in a jar file

I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:
URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());
but it doesn't work. Does anyone know of another way to do it?
To create a file on Android from a resource or raw file I do this:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Don't forget to close your streams etc
This should work.
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Usually, you can't directly get a java.io.File object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:
URL imageResource = getClass().getResource("image.gif");
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));
You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.

Categories