can I get the directory of another file? - java

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

Related

Not able to open application package directory of my Android application

I am trying to write a text file to internal storage of my android application. But it is not possible for me to see if the file is generated or not.
My text file is stored in the following path:
data/data/"MyApplcationPackageName"/files/MyFile.txt
Permission : drwxrwx-x
I have tried the following things -
1) Using device file explorer:
Device file explorer does not open my application package. it gives following error if I try to open it.
Device File Explorer
2) Terminal:
I have also tried opening it using adb in the terminal. But when I try to open files inside my application package it says permission denied.
adb terminal
Please let me know how I can open my text file for debugging. Thanks in advance.
public static void StoreDB() {
if(isExternalStorageWritable() && checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getFinalDir();
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("something".getBytes());
fos.close();
ToastUtil.showToast(Resource.getAppContext(),"File Saved");
} catch (IOException e) {
Log.e("StoreDB", "Exception");
e.printStackTrace();
}
}
}
public static boolean isExternalStorageWritable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Log.d("External storage", "Writable");
return true;
}
Log.d("External storage", "Not Writable");
return false;
}
public static boolean checkPermission(String Permission){
int check = ContextCompat.checkSelfPermission(Resource.getAppContext(),Permission);
boolean Perm = (check == PackageManager.PERMISSION_GRANTED);
Log.d("Check Permission", "Result: " + Perm);
return Perm;
}
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/Co_Ordinate.txt/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
Now I am trying to put the file in external storage. Above code always gives IO exception.
You need to root your phone to view those files. Or you can do it on an emulator by using the Device File Explorer.
EDIT: Or just use an unprotected file path. This will create the directory. After that you just need to save the .txt file to that directory.
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/MyAppName/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
You can do this with Emulator. Run your app in emulator and go to Android Device monitor
Choose device, go to File Explorer menu and search your text file in data folder

How to get file from my project (where code is written)

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();
}
}
}
});
}

My .jar file won't open MP3 files (I'm using Jlayer - JZoom library)

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

Exporting image in runnable jar doesn't work

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));

Accessing a PDF in Jar

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);
}
}
}
});

Categories