HTML file not opening in executable jar - java

I have a program I have written in Eclipse and it runs fine -- the HTML file opens when I run the program through Eclipse. But when I create a jar file of the program, everything else runs fine except this HTML file won't open in the browser (or anywhere):
operation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File htmlFile = new File("help/operation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (MalformedURLException MURLe) {
MURLe.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
The rest of the program runs fine, and my images and sounds work fine and are opened, but this HTML file will not open in the menu or with the Ctrl+key shortcut. Your help is appreciated. Thanks.

When you have a file inside your jar, you cannot access it like you are doing now.
You need to read it as a stream, that's the only way.

Suppose your project is foo. Then help/operation.html will refer to
..\abc\help\operation.html
But the deployed jar file will not contain it.
You have include this operation.html file in your source code (where you write code).
Then eclipse (or any IDE) will add it into your jar file when you deploy it.
And now you can use your file as follows.
Suppose your file is present in as shown in figure.
Now you can refer your html file from any class. In this example referring it from
Accesser class.
File resFile = new File(Accesser.class.getResource("operation.html").toURI());
If you want to open your file in browser you will have to copy this file into the
user's System.
File htmlFile = new File("operation.html");
if(!htmlFile.exists) {
Files.copy(resFile.toPath(), htmlFile.toPath());
}
Desktop.getDesktop().browse(htmlFile.toURI());
Files is present in java.nio.file package

Related

File gets a full path of local source file as its name when uploaded using Java FTPClient

So i have a basic GUI application, where there is an option to upload image files to an ftp server. Everything works fine except one thing: the files are getting renamed during the upload. The new name of the file will be the full path of the directory, which contained the file.
So in my case, i have an image on the desktop: C:\Users\Bob\Desktop\image.png. When I select the file in the JfileChooser, the name is still just image.png. But when I click upload to FTP server, the file will be renamed to C:\Users\Bob\Desktop\image.png. So if I want to download that file, I have to use this path: /home/user/users/xy/images/C:\Users\Bob\Desktop\image.png in order to download it. Idk what causing this problem. I use FTPClient.putFileToPath(file,path) to upload the files, and it works fine, the files will be uploaded. I tried to copy a file from my machine to the ftp server with total commander, and this problem never occurred. I provided some code snippet, which does the uploading job.
uploadmenu.getUploadBtn().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!uploadMenuValidate()){
for(File f : img_container){
try {
//This still gives me the normal file name
System.out.println(f.getName());
ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
popup.setVisible(false);
}
}
});
I have all the files in the img_container array that I selected in the JFileChooser.
The File.toString() returns:
Returns the pathname string of this abstract pathname
You want to use File.getName():
ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f.getName());

Java - How to open a file located in a jar file

I'm using eclipse. I put a .pdf file in my src folder, i want to open it with the default OS program. The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this :
File memo=new File("src/chap.pdf");
try {
Desktop.getDesktop().open(memo);
} catch (IOException e) {
e.printStackTrace();
}
However, after exporting the project to a jar file, this isn't working anymore. So is there a problem in my code or is there another way to get the file to open when it's in the jar file ?
The src path will not be available after you have exported your program and you should never reference it in any way.
You need to extract the resource from the Jar file and write it to the local disk...
try (InputStream is = getClass().getResourceAsStrea("/chap.pdf")) {
try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(...)) {
// Write contents like you would any file
}
} catch (IOException exp) {
exp.printStackTrace();
}
Then you can use the extracted file with Desktop

Create file with java applet

please, i've been struggling for days to get my applet to work, but i can't solve this
my goal is to write a file with the content of my html form
i'm able to reach the applet method, but it doesn't create the file
it's probably some issue with the certificate but i've tried several ways of using jarsigner found on tutorials, stackoverflow and videos, but none of them did the trick.
here is the process I'm following:
1 - create the applet
public class Rappan extends Applet{
public String formResult;
public String generateFile(){
java.io.File file = new java.io.File(System.getProperty("user.home")+"/jsonResponse.txt");
try {
file.createNewFile();
FileWriter f = new FileWriter(file);
f.write(formResult);
f.close();
return "succeess!";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error!";
}
}
}
2 - set my applet tag in html and my script to send the data:
function getForm(str){
appletRappan.formResult = str;
var x = appletRappan.generateFile();
alert(x);
}
$('form').submit(function(){
var str = JSON.stringify($(this).serializeArray());
getForm(str);
});
3 - compile the class, css folder and the html page into Rappan.jar file using:
jar -cvfm Rappan.jar conf.txt Rappan.class css index.html
conf.txt content is
Permissions: all-permissions
Codebase: *
Application-Name: Rappan
4 - generate a second and signed jar file using:
jarsigner -signedjar SignedRappan.jar Rappan.jar rappankeytool
5 - run html in browser, fill the form, choose to run the application when popped up..
nothing happens after that.
I tried some other ways, like having a different folder with the html and css in my desktop, then i would compile only the class, copy both class and jar files into this folder and run the html.. Same result as before
I also changed generateFile() to init() method and ran in eclipse. In this case, the file was created.
just for the record, the appelt is supposed to be used to collect data from different users in different computers offline through a form and generate a file for each one..
I appreciate any help.

working with files in dynamic web project

I am working on a dynamic web project.
On submit button click (present on my form)I want to create a new file and put some data inside.
I have written only these two lines and I am getting failure to create file
try{
File file = new File("C:/database.txt");
file.createNewFile();
}catch(Exception e){
return "error in creating file";
}
If I run the enire code in normal java class everything works fine. Why so?
Your web project is working on application server. The web application can manage files, which are on that server. Other files are not accessible. (of course localhost server is on your computer, but that it's path is not "C:/", so you can't write there). You can find the path of your server running this code (it also create a test file):
String pathWhereYouFindYourFile = new File("").getAbsolutePath();
System.out.println(pathWhereYouFindYourFile);
File f = new File("test.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

File is not opening in java which is inside jar file

I tried to open file form my java application. Using following code from
Open PDF file on fly from Java application
Code:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
When I use path like :
"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf"
it opens. But my file is inside my package
files/test.pdf
and I used
files\\test.pdf
it shows following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.
Why? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants.
Thanks...
getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.
Unfortunately, you cannot load a file through Desktop that is contained in the jar.
However, you are not out of options. A great workaround is to create a temporary file and then open it as detailed here.
Good luck!
Assuming test.pdf is in the package files, try this:
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
This code is working properly please use this to open pdf file within jar file
try {
// TODO add your handling code here:
String path = jTextField1.getText();
System.out.println(path);
Path tempOutput = null;
String tempFile = "myFile";
tempOutput = Files.createTempFile(tempFile, ".pdf");
tempOutput.toFile().deleteOnExit();
InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
if(Desktop.isDesktopSupported())
{
Desktop dTop = Desktop.getDesktop();
if(dTop.isSupported(Desktop.Action.OPEN))
{
dTop.open(tempOutput.toFile());
}
}
} catch (IOException ex) {}

Categories

Resources