Sunday, 15 May 2011

java - opening a file on a button click -



java - opening a file on a button click -

i have java project in button opens pdf file when project exported runnable jar file don't open !!

that's button listener

public void (event event){ if (desktop.isdesktopsupported()) { seek { file myfile = new file("src/application/documenation.pdf"); desktop.getdesktop().open(myfile); } grab (ioexception ex) { // no application registered pdfs } } }

never reference content within src directory, when project built, src directory not exist.

content contained within application context (particularly included within jar file) can't accessed file (like file system), become entry within applications jar file.

in case, need extract file before can open it.

what can is, utilize class#getresourceasstream , re-create resulting inputstream disk

for example...

try (inputstream = getclass().getresourceasstream("/application/documenation.pdf")) { file file = file.createtempfile("documentation", ".pdf"); file.deleteonexit(); seek (outputstream os = new fileoutputstream(file)) { byte[] buffer = new byte[1024]; int bytesread = -1; while ((bytesread = is.read(buffer)) != -1) { os.write(buffer, 0, bytesread); } } desktop.getdesktop().open(file); } grab (ioexception exp) { exp.printstacktrace(); }

java file

No comments:

Post a Comment