Define relative path in java eclipse? - java

I'm developing a dynamic web application in eclipse(mac), wherein I want to include a folder "templates" in the root directory (alongside src) which contains some template documents(temp1.docx, temp2.docx) which the app will edit whenever needed by the user. My plan is to copy temp1.docx to final.docx, make the required changes to it and finally output it. I'm trying to use the java Files.copy(source, dest) method to make a copy of the desired template document via the following code(servlet):
File source = new File("templates/temp1.docx");
File dest = new File("templates/final.docx");
Files.copy(source.toPath(), dest.toPath());
But I'm getting an exception that statesjava.nio.file.NoSuchFileException: templates/doc1.docx. I want to this app to be portable so I guess I'll have to use relative paths. Two questions-
1)Am I working on the correct lines? If so, how can I fix the error?
2)Is there another way to make it easier/better?
Thanks
Edit: using source.toPath() not source.getPath(); cc dest

Related

Create a folder outside of src folder

I've tried several different things to get this to work, and none of them have. I'm trying to create a file inside of a folder in Java. The project needs to have several text files that all relate to each other, and it would be more manageable to have them all together in one folder. Ideally, this folder would be stored outside of scr/.
Here is my current code for it (I do check for file existence first):
File testFile = new File("\\appts\\Appointments" + name + ".txt");
try {
testFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
However, I get an IOException when I try to run the code. I have tried it how it is above, also /appts/Appointments, appts/Appointments, appts\\Appointments. I tried searching online but couldn't find anything that worked.
Edit: Here is how my project setup currently looks like:
Project_Folder
src
com
weebly
roboticplayer
appointmentbook
CLASSES
Here is how I want it to look:
Project_Folder
src
com
weebly
roboticplayer
appointmentbook
CLASSES
appts
There are two easy ways to do this:
1) Absolute path
"C:\\users\\....\\parent_folder\\filename.txt";
2) relative path,
. (Single dot) is current directory
..(double dots) is parent directory
For example, you want to create text files under project folder. And the following is your file structure.
Project_folder
src
Java_main_file.java
appts
You want to create a file under appts from Java_main_file.java
String filename = "..\\appts\\filename.txt"
Then, create your file with filename. Here is a link how to create a text file.
Note that you need to make sure the folder under which you create the files exists. If it doesn't exist, you will get an error.
You can't create a file and its non-existent parent directories in one step, but you can create the parent directories first with File.mkdirs() and then create the file.
If your using JDK7 you can use nio package.
Path path = Paths.get("C:\\appts\\Appointments");
Files.createDirectories(path);
If you want to do a path relative to your current folder:
FileSystems.getDefault().getPath("appts", "Appointments");
If you want to see the absolute pathname:
FileSystems.getDefault().getPath("appts", "Appointments").toAbsolutePath().toString();
If you need that file object:
FileSystems.getDefault().getPath("appts", "Appointments").toFile();
You can also do .toFile() after the call toAbsolutePath().

Adding/Loading an image in java

I am trying to load an image to display on the screen (just to get an idea of how to do it).
The problem is that when the program tries to load "apple.png" (which is saved on my desktop), it cannot find the image - Where do image files need to be stored in order for them to be found? Here is my loading method:
private void loadImage() {
ImageIcon appleIcon = new ImageIcon("apple.png");
Image appleImage = appleIcon.getImage();
}
If you want to reach it from the desktop, you should use the complete path. The easiest way to handle resources would be to create a folder in you java project, which you can access via "folderName/fileName.example".
Using the full path is an option
C:\filefolder\file.jpg
To answer your question though
Wherever your java file is is where it's going to think "home is" make yourself a java workspace to put your java source files in and inside it create a folder to put any assets you want in that way you will simply be able to call "apple.jpg"
if you want use the file name only, the file path ("apple.png")is relative to the source folder. so you have to place it in there.
you could also use absolute the file path to your desktop (sthg like "C:\Users\your.name\Desktop")
From the javadoc:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
As #Shriram mentioned, when you only specify the filename (with extension), it will search for that file in the current directory.
Hint: There exists an constructor overload which takes an URL as argument.

How to set up Eclipse project to load an image so that it also runs from the command line

I've built a Java application that loads an image at runtime. The location of the image is fixed relative to the project.
I would like to be able to run the program from both within Eclipse and the command line and for it to load the image correctly. However, I can only do one or the other but not both. This seems like such a trivial thing to want to do but I can't find out how to do it.
The project is set up so that it creates a bin directory for the output and puts the image in a resources sub-folder. This is fine when running from the command line as I can write my code to look in that sub folder for the file.
But when I run the program from within eclipse the current working directory is different.
What am I missing?
TIA
Update - adding some code
This is what I had originally:
BufferedImage awtImage = ImageIO.read(new File(System.getProperty("user.dir") + "/resources/image-name.png"));
Following the advice in the comments I am trying to use getResourceAsStream but I don't know what to pass to the File constructor.
InputStream temp = MyClass.class.getResourceAsStream("resources/image-name.png");
BufferedImage awtImage = ImageIO.read(new File(???));
The resource is being found because temp is not null.
I think there's 2 solutions.
1) you specify an absolute path
2) your image is in the classpath so you could load it via :
YouClass.class.getResourceAsStream("YourImg.png");
The working directory, if that's really what you mean, is not a great place to load an image from. It appears that you have an image that you would distribute with your finished program so that the program could use it. In that case, I suggest that you use Class.getResourceAsStream(), and put the image in the directory with (or near) that class.
EDIT:
Here is code I used in one of my programs for a similar purpose:
ImageIcon expandedIcon = null;
// ...
expandedIcon = new ImageIcon(TreeIcon.class.getResource("images/Expanded.png"));
The ImageIcon class is part of Swing; I don't know if you're using that, but this should serve to show you the idea. The getResource() method takes a URL; again, you might need something a little different. But this shows the pathname relative to the path of the class on which the method is called, so if TreeIcon is in x/y/z/icons, the PNG file needs to be in x/y/z/icons/images, wherever that is on that computer.
TreeIcon is a class of mine, and its internals will not help you, so I'm not posting them. All it's doing here is providing a location for the PNG file I'm loading into an ImageIcon instance.
In addition to working on a disk with a directory structure, this also works in a jar file (which is a common way to distribute a java program or library). The jar file is just a zip file, and each file in the jar/zip file has its directory associated with it, so the image can be in the jar in the correct directory just as the java classes are in their directories.
getResourceAsStream() returns a stream; if you want to use that byte stream to load as an image, find a class that converts an stream to something your image class can use as a constructor or in a load method and hook them up. This is a common thing to have to figure out with Java i/o, unfortunately there is no cookbook way to do it across all images and situations, so we can't just tell you what it is.
EDIT 2:
As from the comment, try:
ImageIO.read(new File(MyClass.class.getResource("resources/image-name.png");
I set up my Eclipse projects like this.
The input directory is added to the classpath (JavaBuildPath in Eclipse).
Finally, you access the image and / or text files like this.
private BufferedImage getIconImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Extract resource folder from running jar in Java 7

My resources folder inside my jar includes a directory with several binary files. I am attempting to use this code to extract them:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
This is throwing the error
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
Which comes from
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
in UnixException.java. Even though in Files.java the correct options are passed:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
from Files.copy. Of course there's not! That's why I'm trying to make it. I don't yet understand Path and Files enough to do this right. What's the best way to extract the directory and all its contents?
Confused because the docs for Files.copy claims
By default, the copy fails if the target file already exists or is a symbolic link
(Apparently it fails if the target file doesn't exist as well?)
And lists the possible exceptions, and NoSuchFileException is not one of them.
If you're using Guava:
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
You could of course just chain that all into one line; I declared the variables to make it more readable.
The file that does not exist may actually be the directory you're trying to create the file in.
/home/dan/wkhtmltoimage
Does /home/dan exist? Probably not if you're on a Mac.

How to create a Path and a File that does not Exist in Java

This is the problem I have: If part or all of the path does not already exist, the server should create additional directories as necessary in the hierarchy and then create a new file as above.
Files.createDirectories(path);
That's what I am currently using, but it does not create the end file. For example is the path="/hello/test.html" it will create a directory called "hello" and one called "test.html", I want the test.html to be a file. How can I do that?
This is what I did to solve this "problem" or misuse of the libraries.
Files.createDirectories(path.getParent());
Files.createFile(path);
The first line will get the parent directory, so lets say this is what I want to create "/a/b/c/hello.txt", the parent directory will be "/a/b/c/".
The second like will create the file within that directory.
Have you looked at the javadoc? createDirectories only creates... directories. If you're intent on using Files.createDirectories, parse off the file name, call createDirectories passing only the path portion, then create a new file passing the entire path. Otherwise this is a better approach.
Files.createDirectories(path.substring(0, path.lastIndexOf(File.separator)+1));
File yourFile = new File(path);
you can parse the 'path' variable to isolate the file and the directory using delimiter as '/', and do File file = new File(parsedPath); This would work only when you know that you ALWAYS pass the file name at the end of it.
If you know when you are a) creating a directory b) creating a directory and file, you can pass the boolean variable that would describe if file needs to be created or not.

Categories