PDF File does not open in JAR - java

I am trying to open a PDF file when a button is clicked. However I can't seem to get this working when I run my program as a JAR.
Initially, I was using this code:
if(Desktop.isDesktopSupported())
{
try
{
File myFile = new File("src/1. Handel - And the Glory of the Lord.pdf");
Desktop.getDesktop().open(myFile);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
That worked on Netbeans, however it didn't work on the JAR. After research, I found out its because I need to open it using a stream. Meaning I had to make a copy of it as a stream, and open that copy as a File. After looking around on stack overflow, I am now using this code:
try {
String inputPdf = "src/1. Handel - And the Glory of the Lord.pdf";
InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf);
Path tempOutput = Files.createTempFile("1. Handel - And the Glory of the Lord", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File file = new File (tempOutput.toFile().getPath());
if (file.exists())
{
Desktop.getDesktop().open(file);
}
} catch (IOException ex) {
Logger.getLogger(HandelNotes.class.getName()).log(Level.SEVERE, null, ex);
}
This does not even work on Netbeans, whilst on another thread on Stack Exchange, the user said it worked for them.
I am getting a java.lang.NullPointerException error, on this line:
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
Does anyone know what's going wrong, and could someone please tell me how to correct my code?
Thanks,
Rohan

Related

Java -Executable JAR- Error when Creating FileWriter : FileNotFoundException access is denied

I have a program that have a file in which I write the progress I've done, so if the program is closed I can just re-read what I already did.
So if the file doesn't exist (first time I launch the program), I create it, and after that I write in it.
This work while I work with Eclipse. But since I exported to an Executable JAR, I have an error if the file already exists ! That is, I can create the file and write in it the first time, but not if I close and re-launch the program.
Here's the code :
String donePath = "./done.txt";
try {
File doneFile = new File(donePath);
doneFile.createNewFile();
allreadyDone = new ArrayList<String>(Arrays.asList(new String(
Files.readAllBytes(Paths.get(donePath))).split("\n")));
doneFileWriter = new FileWriter(donePath, true);
} catch (IOException e1) {
e1.printStackTrace();
}
and I'm getting :
java.io.FileNotFoundException: .\done.txt (Accès refusé)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:156)
at java.base/java.io.FileWriter.<init>(FileWriter.java:82)
at =============.Main.main(Main.java:51)
I run your program (on Windows 10) with the extension of
printing the work already done
writing something (current time)
a finally-block that flushes and closes the doneFileWriter.
With the finally block everything is OK.
Without the finally block nothing is actually written.
I would expect "Accès refusé" if the log file is already open (by a different running instance).
Or if you run your code first with one user that owns the log file. And then use a different user for the next run, that has not write access.
You use the rather modern java.nio.Paths. So I suggest some type changes and debugging output:
Path donePath = Paths.get("./done.txt");
try {
File doneFile = donePath.toFile();
UserPrincipal owner = Files.getOwner(donePath);
String permissions = PosixFilePermissions.toString(
Files.getPosixFilePermissions(donePath));
System.out.println(
String.format("abs path:%s, owner:%s, can write:%b, permissions:%s",
doneFile.getAbsolutePath(), owner.getName(),
doneFile.canWrite(), permissions));
allreadyDone = new ArrayList<String>(Arrays.asList(new String(
Files.readAllBytes(donePath)).split("\n")));
What operating system do you use?
Which Java implementation (vendor/version)?
And what is your debug output?
You need to put the createNewFile() among an if-statement, so that if it is successfully created it goes ahead, and if it does not it simply outputs "File already exists".
try {
File myObj = new File(filename);
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}

FileNotFoundException: Creates child folder instead of file

I just started to work with files today with Android and have been pulling my hair out all day. This throws a FileNotFoundException:
public void writeConfig(){
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "AppName", "TimetableConfiguration");
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getActivity().getSharedPreferences("periods", MODE_PRIVATE).getString("periods", null).getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
P.rint("Didn't find file");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I notice that instead of creating a file, it creates a child folder. Why is it doing this?
Thanks for any help :)
FileNotFoundException: Creates child folder instead of file
Yes. That is what you do.
You first create with mkdirs() a directory with a certain name.
After that you try to create a file with the same name which is impossible as there cannot be two files or directories with the same name.
So have a look and you will find that directory.
Well you had deduced most all yourself already. Now try to understand your code.
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
You will see that printed every time you repeat the code. You should have seen this too. And have told us.
You should only call mkdirs if the directory does not exist yet.

Web Service to Display a PDF, deleting the file once displayed

I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Java BufferedImage throwing NullPointerException

I am making a space shooter in Java, but when I try to load up the image resources, I get a null pointer exception. Everything works fine except the images. Am I coding the directory wrong? How can I fix it?
Here is my code:
BufferedReader highScoreReader;
BufferedWriter highScoreWriter;
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/enemy.png"));
highScoreReader = new BufferedReader(new FileReader("/files/HIGH_SCORE.txt"));
highScoreWriter = new BufferedWriter(new FileWriter("/files/HIGH_SCORE.txt"));
} catch (Exception e) {
e.printStackTrace();
}
Here is a screenshot of my file directories:
Most probably, you need to copy your images into the build directory of your project. If you want them treated as classpath resources, which it seems you do, make sure they're in a source folder in eclipse (or, if you use maven or similar, in the src/main/resources folder. The point is, they need to be copied to the place where the .class file lives when it's running.
Remember: class.getResourceAsStream(...) returns things from the classpath not from your source path.
I've never seen it done that way.
Try this
try {
playerImage = ImageIO.read(getClass().getClassLoader().getResourceAsStream("src/res/player.png"));
catch(IOException e) {
}
or
try {
playerImage = ImageIO.read(new File("src/res/player.png"));
catch (IOException e) {
}
Arnav Garg has discovered the problem.
When your code says something like:
file("src/res/player.png")
the file is not there, i.e.
file.exists()
will return false
Find out where java thinks the file is.
try using
file.getAbsolutePath()
and compare that to your directory structure.

Caused by: java.io.FileNotFoundException: /path/somthing.jar (Is a directory) when FileOutputStream object is created

this is a really basic one, but it got me scratch my hear for 4 hours, now i'm giving up.
to give as much as possible information , i can say it's a java webapp project with zk 5.0.8 as frontend+spring+hibernate+maven under ubuntu 11.04 with permission to the basedir set to 777.
tried the file upload everything seems to be ok and where i have confidence that my code is correct it's just not working.
here is the code
private boolean saveUploadledFile(Media uploadedMedia, String basedir) {
String code = codeGenerator.generateContentCode(15);
String FINAL_DIR_PATH = basedir + "/"+"Racing" + "/" + code;
String FINAL_FILE_PATH = FINAL_DIR_PATH + "/" + uploadedMedia.getName();
alert(FINAL_DIR_PATH);
try {
File finaldir = new File(FINAL_DIR_PATH);
//apache commons
FileUtils.forceMkdir(finaldir);
alert("Size equals" + uploadedMedia.getByteData().length);
fout = new FileOutputStream(new File(FINAL_DIR_PATH+"/"+addContentWindow1$txtName.getText()+".jar"));
//apache commons
IOUtils.copy(uploadedMedia.getStreamData(), fout);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fout);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return false;
}
new FileOutputStream always throws exceptions. so if i can't specify where i want to save how to save the files. any ideas? i intentionally output the size of the file to make sure there is a file. Can anyone shed some light? thanks for reading this
the actual exception is
Caused by: java.io.FileNotFoundException: /joseph/mbcs/Games/Racing/20314/somthing.jar (is a directory)
I may be wrong, but isn't this part of your code faulty?
if (!finaldir.exists()) {
if (!finaldir.canWrite())
finaldir.mkdirs(); // this creates no directory no error
else
alert("Cannot write to the directory" );
}
If the directory doesn't exist, you check if you can't write there and then create it, otherwise you output an error. I think that ! there is wrong.
Might be the reason for your problem but it just as well might not be.
Leave out:
if(finalfile.canWrite()) {
as you just created the file and are writing to it.
You will get a misnamed FileNotFoundException (I think renamed in Java 7) when the OutputStream constructor failed in writing.
Another tip, general work like copying may be done using apache-commons (IOUtils, FileUtils),
i.e.:
import org.apache.commons.fileupload.util.Streams;
Streams.copy(in, out, false);

Categories