All I am trying to do is create a JLabel using an image located in the same directory as the .jar and if it does not exist it will load a default photo located inside the .jar iteself. The picture exists in the folder however it always defaults to the picture inside the .jar
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(path + "logo.png");
JLabel lblNewLabel_1;
if (logo.exists()){
lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
} else {
lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}
frame.getContentPane().add(lblNewLabel_1, BorderLayout.WEST);
final JLabel lblStatus = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/status1.png")));
frame.getContentPane().add(lblStatus, BorderLayout.EAST);
The most simple way to diagnose this issue is to apply simple System.out.println() like here
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(;
System.our.println("Jar path is "+path); <- you will see the actual path content here
File logo = new File(path + "logo.png");
Check the result and adjust concatenate path as needed. I guess that path is either pointing to different directory than you think it is, or it is simply missing a File.separator at the end. Try out and share the results!
It looks like you are missing a '/' at the end of path. Do it this way:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(new File(path).getParentFile(), "logo.png");
...
The catch is to first creating a File for the containing directory and then using the constructor File(File dir, String name) instead of string concatenation.
Furthermore, you should check folder and file permissions in advance, providing proper logging output for error diagnosis. For this, use canRead() instead of exists() (assuming log is available as some logging facility - replace with the logging mechanism of your choice):
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File sourceLocation = new File(path);
// go up in the hierarchy until there is a directory
while (sourceLocation != null && !sourceLocation.isDirectory()) {
sourceLocation = sourceLocation.getParentFile();
if (sourceLocation == null) {
log.warn(path + " is not a directory but has no parent");
}
}
if (sourceLocation != null && sourceLocation.canRead()) {
File logo = new File(sourceLocation, "logo.png");
if (logo.canRead()) {
log.info("Using logo " + logo.getAbsolutePath());
lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
} else {
log.warn("can not read " + logo.getAbsolutePath());
}
}
if (lblNewLabel_1 == null) {
log.warn("logo location not accessible, using default logo: " + sourceLocation);
lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}
// ...
Related
I want to read Images from resource folder of eclipse without using image name. As of now I am reading it from current directory and taking Absolute Path (photoPath) so that I can reproduce the Image in other panel of a JFrame. However if I make executable jar its start taking images from current directory, my image folder is not coming. Here is my Image choosing code
imageChooser = new JButton("ImageChooser");
panel1.add(imageChooser);
fc = new JFileChooser();
imageLabel = new JLabel();
imageChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setCurrentDirectory(new File("."));
int result = fc.showOpenDialog(imageChooser);
if (result == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
imageLabel.setIcon(new ImageIcon(currentFile.toString()));
panel1.add(imageLabel);
panel1.validate();
photoName=fc.getSelectedFile().getName();
photoPath = currentFile.getAbsolutePath();
}
}
});
Here is my structure
use .getResource()
Example:
new ImageIcon(getClass().getResource("/images/button.png"))
This will work for JAR as well.
I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path.
Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
You can use new File("folder", newFileName.getText() + ".properties") which will create a file reference to the specified file in the folder directory relative to the current working directory
You should make sure that the directory exists before calling createNewFile, as it won't do this for you
For example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Trivially I missed that new File(".").getAbsolutePath() returns the project's absolute path with the . at the end so my folder whould be called as .folder. Next time I'll check twice.
So i'm working on a simple Windows Explorer replacement. I want to add the ability to create Folders and Files. For some reason, it only works when i'm in my root or c:/ folder, but as soon as it's somewhere else (for example C:\Program Files (x86)) it doesn't work. I either get a java.io.IOException: Access Denied when i create a File and when i try to create a folder, no Exception comes up, but no folder is created.
This is my code for a new file:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new file. \nDon't forget to add file type (.txt, .pdf).", null);
if(name == null){
}
else {
File newFile = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFile.createNewFile();
} catch (IOException Io) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "File creation failed with the following reason: \n" + Io);
}
}
This is my code for a new Folder:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new folder.", null);
if(name == null){
}
else {
File newFolder = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFolder.mkdir();
} catch (SecurityException Se) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "Folder creation failed with the following reason: \n" + Se);
}
}
I'm stuck right now and i have no idea what i'm doing wrong to get rid of the access denied error.
Short explenation of how this program works:
My program shows a list of all folders and files from a selected File.
That File is a field in the class JXploreFile called "currentFile", which behaves almost the same as a File.
When browsing through the folders, the currentFile is set to a new JXploreFile, containing the new folder you are in as File.
When creating a new folder/file, my program ask the path the user is currently browsing in with the method getPath().
Thanks for the help!
Image of my program:
Before you try to make any I/O operation just check if you have the permission
go to the parent directory (your case location)
then do something like
File f = new File(location);
if(f.canWrite()) {
/*your full folder creation code here */
} else {
}
try to put
String location ="c:\\user\<<youruser>>\\my documents"
or a folder with full perission to write
I am trying to open a javafx FileChooser in the user directory according to an example I found here.
Here is a fragment of the simple code I am using:
FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);
However, I keep obtaining this warning (complete file paths have been truncated):
Invalid URL passed to an open/save panel: '/Users/my_user'. Using 'file://localhost/Users/my_user/<etc>/' instead.
I verified that the file object is an existing directory adding these lines:
System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true
Then I do not have idea why I am obtaining the warning message.
UPDATE:
This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.
This is what I ended up doing and it worked like a charm.
Also, make sure your folder is accessible when trying to read it (good practice). You could create the file and then check if you can read it. Full code would then look like this, defaulting to c: drive if you can't access user directory.
FileChooser fileChooser = new FileChooser();
//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);
//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);
//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
path = chosenFile.getPath();
} else {
//default return value
path = null;
}
This works on Windows and Linux, but might be different on other operating systems (not tested)
Try:
String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
#FXML private Label label1; //total file path print
#FXML private Label labelFirst; //file dir path print
private String firstPath; //dir path save
public void method() {
FileChooser fileChooser = new FileChooser();
if (firstPath != null) {
File path = new File(firstPath);
fileChooser.initialDirectoryProperty().set(path);
}
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new ExtensionFilter("All Files", "*.*") );
File selectFile = fileChooser.showOpenDialog(OwnStage);
if (selectFile != null){
String path = selectFile.getPath();
int len = path.lastIndexOf("/"); //no detec return -1
if (len == -1) {
len = path.lastIndexOf("\\");
}
firstPath = path.substring(0, len);
labelFirst.setText("file path : " + firstPath);
label1.setText("First File Select: " + path);
}
}
I am trying to display an image in my application...
picture = new JLabel("No file selected");
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
scrollPane.setViewportView(picture);
ImageIcon icon = new ImageIcon("map.jpg");
picture.setIcon(icon);
if (picture.getIcon() != null) // to see if the label picture has Icon
picture.setText("HERE IS ICON");
When I run that code, only the "HERE IS ICON" text displayed.
Sorry if this question sounds so dumb, but I really have no clue of why the image icon is not displayed :(
You need to make sure map.jpg exists as a file. If you want to be sure (for testing purposes only), try to use the full path. The way you have it, the path is relative to the application's start directory.
You can double check if it exists with this:
System.out.println(new java.io.File("map.jpg").exists());
You can do that:
ImageIcon icon = createImageIcon("map.jpg", "My ImageIcon");
if (icon != null) {
JLabel picture = new JLabel("HERE IS ICON", icon, JLabel.CENTER);
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
scrollPane.setViewportView(picture);
}
The createImageIcon method (used in the preceding snippet) finds the specified file and returns an ImageIcon for that file, or null if that file couldn't be found. Here is a typical implementation:
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
The file map.jpg might not be in the same package(folder) as the java file. Check it.