I'm having problems displaying icons in a JList that I've made. I'm passing a path to the function getResource() and then storing the resource in a URL object. However, every time I call the getResource() function it returns a null, even though the images exist in the directory.
I've tried looking around on stackoverflow and other sites but I can't find a solution to this problem. I even tried storing the images in multiple locations inside my project directory but to no avail. If it helps, I'm using the Eclipse IDE. So I've stored the files in the /src/, /src/resources/, and the project folder.
Here is my code:
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.*;
#SuppressWarnings("serial")
public class JListRenderer extends DefaultListCellRenderer
{
private static ArrayList<CakeRecipe> cRecipes;
private ImageIcon[] images;
// Index of cake recipe
private int cakeIndex;
JListRenderer(ArrayList<CakeRecipe> recipes)
{
cRecipes = recipes;
// Initializes an array of ImageIcons FileHander.jpgCounter() counts the amount of JPG's in the folder, FileHandler.getPath() gives you the filepath
images = new ImageIcon[FileHandler.jpgCounter(new File(FileHandler.getPath()))];
for(int i = 0, j = images.length; i < j; i++)
images[i] = createImageIcon("/resources/" + cRecipes.get(cakeIndex).getPhoto()); // cRecipes.get().getPhoto() gives you the filename of the village only (e.g.: photo.jpg)
}
protected static ImageIcon createImageIcon(String path)
{
URL imgURL = JListRenderer.class.getResource(path);
if(imgURL != null)
return new ImageIcon(imgURL);
else
{
System.err.println("Could not find image. Certain menu elements may not display properly");
return null;
}
}
...
Should this code work or am I not using the URL or getResource() properly? The images are in the directory, and I'm passing a path identical to the image's path. Example:
"/resources/photo.jpg"
Any help would be greatly appreciated. Thank you.
EDIT: The problem was with Eclipse. It didn't register the resources in the build path. A simple "Refresh fixed the problem. Thanks for all your help, everyone.
It looks like it should work. I've tried running the following, with a test.txt file in the resources package:
package resourcestest;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Test {
public static void main(String[] args) throws Exception {
final URL test = Test.class.getResource("/");
System.out.println(test);
final URL url = Test.class.getResource("/resources/test.txt");
System.out.println(url);
if(url == null) {
System.out.println("URL is null");
} else {
final File file = new File(url.toURI());
final FileReader reader = new FileReader(file);
final char[] buff = new char[20];
final int l = reader.read(buff);
System.out.println(new String(buff, 0, l));
reader.close();
}
}
}
The first two statements in the main method can be of use to find out what path is considered the relative root at runtime.
I've tried this in NetBeans and Eclipse and in both cases it worked. Now, the real question is, what's your project setup and how do you build? Is there a separate folder for sources and class files or are they put together? Do you use an Ant script or Eclipse build methods?
If you've got the files only in a folder and not in a package, then it's not certain that they're gonna be on the compilation path or on the runtime class path. I suspect the latter may be the case. Try to make sure resources is a package, not a folder. Try creating a jar file from your project, then check its contents to see if your resources were included. Try running from the jar file and see if it makes a difference.
Becasue it's awkward to show all the relevant factors, it may be difficult to identify the problem in your particular situation. Instead, you might start with this working example and compare it with your own implementation.
Related
I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
I'm working on a course project and using this code block my professor gave us to, one, get all files from the current directory and, two, to find which files are in the .dat format. Here is the code block:
// Get all files from directory
File curDir = new File(".");
String[] fileNames = curDir.list();
ArrayList<String> data = new ArrayList<String>();
// Find files which may have data. (aka, are in the .dat format)
for (String s:fileNames)
if (s.endsWith(".dat"))
data.add(s);
However, when I try to compile and test my program, I get this error message in response:
Prog2.java:11: cannot find symbol
symbol : class File
location: class Prog2
File curDir = new File(".");
^
Prog2.java:11: cannot find symbol
symbol : class File
location: class Prog2
File curDir = new File(".");
^
I admittedly have minimal experience with the File class, so it might be my fault entirely, but what's up with this?
Import the File class from the java.io.File package
i.e.
import java.io.File;
Here is documentation for java.io.File and a brief explanation of the File class.
Just add the following statement before the class definition:
import java.io.File;
If you use IDE, like Eclipse, JDeveloper, NetBeans, etc. it can automatilly add the import statement for you.
I think Naveen and Poodle have it right with the need to import the File class
import java.io.File;
Here is another method of getting .dat files that helped me, just FYI =)
It's a general file filtering method that works nicely:
String[] fileList;
File mPath = new File("YOUR_DIRECTORY");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
return filename.contains(".dat");
// you can add multiple conditions for the filer here
}
};
fileList = mPath.list(filter);
if (fileList == null) {
//handle no files of type .dat
}
As I said in the comments, you can add multiple conditions to the filter to get specific files. Again, just FYI.
I am a new programmer to Java. I have a made a small Directory Application that I would like to export, but for some reason, whenever I try to export it to a runnable jar file, the result doesn't contain any of the images I specified within my program. Basically, I ran it in eclipse, and it worked fine, but when I ran it as an runnable JAR, it has no images. I have 5 .java files that are all bundled with eachother. My Images are found at Images/Image.png [I already made The Images folder a source folder.]
I have tried eveything, but for some reason i can't get it to work, if you have any knowledge on the topic, please tell me. I don't know if its because I'm a noob or something I'm doing wrong.
static ImageIcon logoicon = new ImageIcon("Images/Logo.png");
Here is the method I use:
public static ImageIcon createImageIcon(final String path) {
InputStream is = ImageLoader.class.getResourceAsStream(path);
int length;
try {
length = is.available();
byte[] data = new byte[length];
is.read(data);
is.close();
ImageIcon ii = new ImageIcon(data);
return ii;
} catch (IOException e) {
LogManager.logCriticalProblem("Image not found at {} - {}", new Object[]{path, e.getMessage()});
}
return null;
}
If you have problems with this method, try altering the path you're using:
"Images/Logo.png"
"/Images/Logo.png"
"src/Images/Logo.png"
"/src/Images/Logo.png"
Or other combinations depending on your package structure. For example, if your images are actually in net.blah.fizz.Images, your path would be "/net/blah/fizz/Images/image.png"
Did you try getResourceAsStream() method ? Checkout this page for more information
I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}
So here is my program, which works ok:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;
public class ScanSum {
public static void main(String[] args) throws IOException {
Scanner s = null;
double sum = 0;
try {
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
s.useLocale(Locale.US);
while (s.hasNext()) {
if (s.hasNextDouble()) {
sum += s.nextDouble();
} else {
s.next();
}
}
} finally {
s.close();
}
System.out.println(sum);
}
}
As you can see, I am using absolute path to the file I am reading from:
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
The problem arises when I try to use the relative path:
s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
I get an error:
Exception in thread "main" java.lang.NullPointerException
at ScanSum.main(ScanSum.java:24)
The file usnumbers.txt is in the same directory as the ScanSum.class file:
D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt
How could I solve this?
If aioobe#'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:
new File(".").getAbsolutePath()
From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)
If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".
The NullPointerException is due to the fact that new FileReader() expression is throwing a FileNotFoundException, and the variable s is never re-assigned a non-null value.
The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.
To fix the first problem, never assign a meaningless null value just to hush the compiler warnings about unassigned variables. Use a pattern like this:
FileReader r = new FileReader(path);
try {
Scanner s = new Scanner(new BufferedReader(r));
...
} finally {
r.close();
}
For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which java is run.
It must be a FileNotFoundException causing NPE in the finally block.
Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorld in your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab
Since your working directory is “D:/java-projects/HelloWorld”
#pdbartlett's id is great, But
String filePath = new File(".").getAbsolutePath()
will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.
I suggest with String filePath = new File("").getAbsolutePath() which return the project root folder
In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".
By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)
Put the file in resources folder.
ClassLoader classLoader = getClass().getClassLoader();
String file1 = classLoader.getResource("myfile.csv").getPath();