I'm trying to get file (readme.txt) from my project folder. Don't know how to get location of project. When I say project, I mean location where my application code is written and not runtime application. I've tried getting absolute path, relative path... and it always gives me folder of runtime application. Also tried something like this.getClass() and tried to extract path or System.getProperty("user.dir"). These two also gives me path of my eclipse.../.../...runtime app. I'm making eclipse plugin, and this file is suppose to be part of my plugin, so that when user click's on button, this file opens (it's some help txt file). This is my code for opening file, problem is path.
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File helpFile = new File("\\readme.txt");
helpFile.setReadOnly();
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(helpFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
It depends on where exactly the file is in your project. A clean point to put it might be ${project.root}/resources, so create a folder and put the file there. Mark it as a "source folder" in Eclipse (project properties -> build path -> source folders). Your current setup isn't a good idea because the file will not be included in your distribution by Eclipse's compile.
Now, when you compile the code, this gets copied into the target directors (bin per default); you can check by opening it in your file browser.
So to check the file is there, you can do
Path filePath = Paths.get("resources", "readme.txt");
System.out.println(Files.exists(filePath));
If you need it as a File, you can do
File readmeFile = filePath.toFile();
This reads the file from the source project folder, so it won't be much use after you run the program somewhere else.
For that, you can use the ClassLoader:
URL readmeUrl = ClassLoader.getSystemClassLoader().getResource("resources/readme.txt"));
File readmeFile = new File(readmeUrl.getFile());
I found answer, this works for me:
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File file = null;
Bundle bundle = Platform.getBundle("TestProject");
IPath path = new Path("resources/readme.txt");
URL url = FileLocator.find(bundle, path, null);
/*
* After FileLocator, I get also this, like I commented before:
* D:\\eclipse-rcp-oxygen\\eclipse\\..\\..\\..\\eclipse_oxygen_workspace\\
* TestProject\\resources\\readme.txt and before it didn't work but if
* you add these lines:
* url = FileLocator.toFileURL(url);
* file = URIUtil.toFile(URIUtil.toURI(url));
* Like in my try bracket, it works. I guess it needs to be
* converted using URIUtil.
* Now it finds file, and it can be opened, also works for .html files.
*/
Desktop desktop = Desktop.getDesktop();
try {
url = FileLocator.toFileURL(url);
file = URIUtil.toFile(URIUtil.toURI(url));
// file.setReadOnly();
desktop.open(file);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
}
Related
I have created an auto-updater for my java program. but at the end of the download it downloads the file to desktop. I can to get where is the program file and update it?
this is my code:
#Override
public void run() {
if(!Debug) {
try {
FileUtils.copyURLToFile(new URL("fileurl"), new File(System.getenv("APPDATA") + "\\file.zip"));
UnzipUtility unzip = new UnzipUtility();
File deskfile = new File(System.getProperty("user.home") + "/Desktop/file.jar");
if(deskfile.exists()) {
deskfile.delete();
}
unzip.unzip(System.getenv("APPDATA") + "\\file.zip", System.getProperty("user.home") + "/Desktop");
File file = new File(System.getenv("APPDATA") + "\\file.zip");
file.delete();
Successfull = true;
} catch (IOException e) {
Successfull = false;
}
try {
Updater.sleep(0L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
this is the code present in my external updater jar and I need to find the main program directory what can I do?
For example, if the main program is in any other directory except the Desktop, the update will always download it to the desktop ... I need it to change the file that executes the command to start the updater
If your external updater is in the same directory as your mail application you can use:
System.getProperty("user.dir");
This will give you the current folder. You can find more details here: https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
If this is not the case i see the following options:
ask the user before updating for the installation folder
store the installation folder in property file inOS user data // update jar folder.
regards, WiPu
I did this small Java project that in it's turn opens different MP3 files. For that I downloaded the JLayer 1.0.1 library and added it to my project. I also added the MP3 files to a package on my project -as well as some JPG images- so as to obtain them from there, and I'm using a hashmap (mapa) and this method to get them:
public static String consiguePath (int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i)).getPath();
}
so as to avoid absolute paths.
When I open an MP3 file I do this:
try {
File archivo = new File(AppUtils.consiguePath(12));
FileInputStream fis = new FileInputStream(archivo);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
Player player = new Player(bis);
player.play();
} catch (JavaLayerException jle) {
}
} catch (IOException e) {
}
The whole thing runs perfectly in NetBeans, but when I build a .jar file and execute it it runs well but it won't open the MP3 files. What called my attention is that it doesn't have trouble in opening the JPG files that are on the same package.
After generating the .jar I checked the MyProject/build/classes/Movimiento folder and all of the MP3 files were actually there, so I don't know what may be happening.
I've seen others had this problem before but I haven't seen any satisfactory answer yet.
Thanks!
Change the consiguePath to return the resulting URL from getResource
public static URL consiguePath(int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i));
}
And then use it's InputStream to pass to the Player
try {
URL url = AppUtils.consiguePath(12);
Player player = new Player(url.openStream());
player.play();
} catch (JavaLayerException | IOException e) {
e.printStackTrace();
}
Equally, you could just use Class#getResourceAsStream
Resources are packaged into your Jar file and can no longer be treated as Files
I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));
I have made a button, but I don't now how to make it open a specific directory like %appdata% when the button is clicked on.
Here is the code ->
//---- button4 ----
button4.setText("Texture Packs");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser=new JFileChooser("%appdata%");
int status = fileChooser.showOpenDialog(this);
fileChooser.setMultiSelectionEnabled(false);
if(status == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// do something on the selected file.
}
}
And I want to make something like this ->
private void button4MouseClicked(MouseEvent e) throws IOException {
open folder %appdata%
// Open the folder in the file explorer not in Java.
// When I click on the button, the folder is viewed with the file explorer on the screen
}
import java.awt.Desktop;
import java.io.File;
public class OpenAppData {
public static void main(String[] args) throws Exception {
// Horribly platform specific.
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData);
// Get a sub-directory named 'texture'
File textureDir = new File(appDataDir, "texture");
Desktop.getDesktop().open(textureDir);
}
}
Execute a command using Runtime.exec(..). However, not every OS has the same file explorer, so you need to handle the OS.
Windows: Explorer /select, file
Mac: open -R file
Linux: xdg-open file
I wrote a FileExplorer class for the purpose of revealing files in the native file explorer, but you'll need to edit it to detect operating system.
http://textu.be/6
NOTE: This is if you wish to reveal individual files. To reveal directories, Desktop#open(File) is far simpler, as posted by Andrew Thompson.
If you are using Windows Vista and higher, System.getenv("APPDATA"); will return you C:\Users\(username}\AppData\Roaming, so you should go one time up, and use this path for filechooser,
Just a simple modified Andrew's example,
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData); // TODO: this path should be changed!
JFileChooser fileChooser = new JFileChooser(appData);
fileChooser.showOpenDialog(new JFrame());
More about windows xp, and windows vista/7/8
I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
Pls refer to this question, which might provide additional information.
Try out this:
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});