Error unzipping a file with javaFX - java

I am trying to unzip files and it was recommended to me that I use codeJava.net's unzip utility however I cannot get it to work. The following is a snippet of my code that occurs when a button is pressed.
public void fileSelector(Stage primaryStage) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("ZIP FILES ONLY", "*.zip"));
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) {
System.out.println(selectedFile);
UnzipUtility unzipper = new UnzipUtility();
String destination = System.getProperty("user.dir");
String finalDestination = destination + "\\books";
System.out.println(finalDestination);
String initialDestination = selectedFile.getPath();
System.out.println(initialDestination);
try {
System.out.println("unzipping ... beep boop beep");
unzipper.unzip(initialDestination, destination);
}
catch (Exception e) {
e.printStackTrace();
}
}
It's meant to use the JavaFX file chooser to choose the file then turn the file path into strings before being used by the unzipper object. You can find the Unzip utility at http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java.
This is the error I get:
java.io.FileNotFoundException: F:\EbookReader\books\New folder\1.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
Thanks for any help.

So basically the unzipUtility I was using had a fatal error... it couldn't unzip folders. So I did a quick google search and found: http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/
Its not only works but its also easier to understand which is especially useful to a noob like me. Thx for all of you who commented, it really helped to steer me in the right direction :)

Related

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

Get the path of a file via file explorer

First of all I'm sorry if this question has been asked before or if there is documentation about the topic but i didn't found anything.
I want to make a windows app that open windows file explorer and you can browse for and then select a mp3 file, so you can play it (and replay it) in this program. I know how to open file explorer, this is my code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");
desktop.open(dirToOpen);
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
}
But i don't know how to select an mp3 file and then get the path of the file, so i can play it later.
I don't think you are approaching this right. You should use something like a FileDialog to choose a file:
FileDialog fd = new FileDialog(new JFrame());
fd.setVisible(true);
File[] f = fd.getFiles();
if(f.length > 0){
System.out.println(fd.getFiles()[0].getAbsolutePath());
}
Since you are only getting 1 MP3 file, you only need the first index of the File array returned from the getFiles() method. Since it is a modal dialog, the rest of your application will wait until after you choose a file. If you want to get multiple files at once, just loop through this aforementioned Files array.
See the documentation here: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

TrueZip unable to extract file from archive

I am creating a java app that will extract the embedded thumbnail inside of a Powerpoint (PPTX) document. Since pptx files are zip archives, I am trying to use TrueZip to get the thumbnail found inside of the archive. Unfortunately whenever I try running my application it throws an IOException stating that the file is missing C:\Users\test-user\Desktop\DocumentsTest\Hello.pptx\docProps\thumbnail.jpeg (missing file)
Below is the code I use to get the thumbnail:
public Boolean GetThumbPPTX(String inFile, String outFile)
{
try
{
TFile srcFile = new TFile(inFile, "docProps\\thumbnail.jpeg");
TFile dstFile = new TFile(outFile);
if(dstFile.exists())
dstFile.delete();
srcFile.toNonArchiveFile().cp_rp(dstFile);
return dstFile.exists();
} catch (IOException ex) {
Logger.getLogger(DocumentThumbGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
Where inFile is the absolute path of the pptx file and outFile is the path that the thumbnail will be copied to. I can verify that the archive does have a thumbnail inside of it at the same exact path.
Can someone help please?
I just found the answer. It seems I did not have the Zip driver configured correctly. I added this to my class constructor and it all works now:
TConfig.get().setArchiveDetector(new TArchiveDetector(
TArchiveDetector.NULL,
new Object[][] {
{ "zip|pptx", new ZipDriver(IOPoolLocator.SINGLETON)},
}));

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

Getting error when I attach an image to Classpath Resource in scheduler jobclass

protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Sending Birthday Wishes... ");
try
{
for(int i=0;i<maillist.length;i++)
{
Email email = new Email();
email.setFrom("spv_it#yahoo.com");
email.setSubject("Happy IndependenceDay");
email.setTo(maillist[i]);
email.setText("<font color=blue><h4>Dear Users,<br><br><br>Wish you a Happy Independence Day!<br><br><br>Regards,<br>Penna Cement Industries Limited</h4></font>");
byte[] data = null;
ClassPathResource img = new ClassPathResource("newLogo.gif");
InputStream inputStream = img.getInputStream();
data = new byte[inputStream.available()];
while((inputStream.read(data)!=-1));
Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);
email.addAttachment(attachment);
emailService.sendEmail(email);
}
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is the error I'm getting:
java.io.FileNotFoundException: class path resource [newLogo.gif] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:135)
at com.mail.schedular.BirthdayWisherJob.executeInternal(BirthdayWisherJob.java:55)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
The best practise is to read/write or to provide reference of any file is by mentioning the ABSOLUTE PATH of that file.
To your question, It shows the FileNotFoundException because, JVM failed to locate the file in your current directory which is by default your source path. So provide the absolute path in ClassPathResource or copy that image file to your current directory. It will solve your problem.
I think you need to put your file inside inside the src folder , if it's there then check whether it's under some directory which is inside the src directory.
Then give the correct location like given details below
src[dir]----->newLogo.gif
ClassPathResource img = new ClassPathResource("newLogo.gif");
or,
src[dir]----->images[dir]---->newLogo.gif
ClassPathResource img = new ClassPathResource("/images/newLogo.gif");
You got this error since the job is running in a separate quartz thread, I suggest that you locate your file newLogo.gif outside the jar and use the following to load it.
Thread.currentThread().getContextClassLoader().getResource("classpath:image/newLogo.gif");

Categories