I came across this question on SO.
Java application runs properly in Eclipse, but not as .jar
I don't have any images in my code.I created a runnable jar file in the following way,
Right click on project,
Click Export,
select "Runnable JAR File",
Extract required libraries into generated JAR
When I run the .jar file on my desktop, the PDF file is being created.
But it shows the following error
Adobe Reader could not open 'Result-itext.pdf' because it is either
not a supported file type or because the file has been damaged
My Code:
try {
PdfWriter w = new PdfWriter("Result-itext.pdf");
PdfDocument d = new PdfDocument(w);
Document doc = new Document(d);
/** Added **/
Image img = new Image(ImageDataFactory.create(logo));
img.setHorizontalAlignment(HorizontalAlignment.CENTER);
doc.add(img);
/** Added **/
doc.add(new Paragraph("Test Name : Hello World").setTextAlignment(TextAlignment.CENTER));
doc.add(new Paragraph("Maximum Marks : 20").setTextAlignment(TextAlignment.CENTER));
doc.add(new Paragraph("RESULTS").setBold().setTextAlignment(TextAlignment.CENTER));
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE);
Table t = new Table(3);
t.setWidthPercent(70);
t.setHorizontalAlignment(HorizontalAlignment.CENTER);
t.setFont(font);
Cell cell = new Cell().add("User-ID").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
cell = new Cell().add("User-Name").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
cell = new Cell().add("Marks").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
PdfFont font1 = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
t.setFont(font1);
ArrayList<String> a = new ArrayList<String>();
for(int i=0;i<3;i++){
a.add(String.valueOf(i));a.add("jack");a.add(String.valueOf(i+10));
}
for(int i=0;i<9;i++){
cell = new Cell().add(a.get(i)).setTextAlignment(TextAlignment.CENTER);
t.addCell(cell);
}
doc.add(t);
doc.close();
JOptionPane.showMessageDialog(null, "Created file");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Couple pointers to help with your problem
Compare the two PDF file size, first one generated from eclipse, second generated from the jar file. Is there a size difference, if there is then it means that the generated jar is missing something that the eclipse project has.
Are you running the generated jar by double-clicking it? If 'yes' then even if there is any error thrown by any program in jar file, it won't appear as the window closes immediately (assuming that this is no Swing/AWT GUI application).
So I suggest to run it from command prompt like:
java -jar xyz.jar
Hopefully these two should resolve your issue.
Related
So i was making a maven plugin, which main goal would be to generate extra resource inside of the final jar file, but i couldnt find how to actually put the file inside of the jar.
The closest i got was saving the file in the output directory, which doesnt really help my case, and most of the google search results gave me either documentation on how to use "Apache maven resource plugin" or "how to create maven plugins", neither of them having the information i seek =\
Update 1:
Tried saving the file to the target/classes, but the resulting file is empty (no idea why) and isnt copied to the final jar either way
File dir = new File(project.getBuild().getDirectory(),"classes");
if(dir.exists()){
File result = new File(dir,"AzimDP.json");
try {
getLog().info(gson.toJson(toSave));
gson.toJson(toSave, new FileWriter(result));
} catch (Exception e) {
getLog().warn(e);
}
}else{
getLog().warn("Unable to save file since target/classes doesnt exist");
}
Update 2 and working solution:
turns out i forgot to flush and close the FileWriter, and thus the file was empty. After i fixed that, everything works:
File dir = new File(project.getBuild().getDirectory(),"classes");
if(!dir.exists()) {
dir.mkdirs();
}
File result = new File(dir,"AzimDP.json");
try {
FileWriter writer = new FileWriter(result);
gson.toJson(toSave, writer);
writer.flush();
writer.close();
} catch (Exception e) {
getLog().warn(e);
}
In the end, the working solution based off #GyroGearless comment:
Gson gson = new Gson();
File dir = new File(project.getBuild().getDirectory(), "classes");
if(!dir.exists()) {
dir.mkdirs();
}
File result = new File(dir, "AzimDP.json");
try {
FileWriter writer = new FileWriter(result);
gson.toJson(toSave, writer);
writer.flush();
writer.close();
} catch (Exception e) {
getLog().warn(e);
}
where project is MavenProject and toSave is JsonArray.
Used in Maven 3 at LifecyclePhase "generate resources"
I'm using Apache libraries to edit DOCX file and I want user to choose dir where to save his file. It doesnt matter what folder to select it always thows an excetion and says "path (Access denied)", however, if I choose the directory in my code it works perfectly. Here's some of my code:
XWPFDocument doc = null;
try {
doc = new XWPFDocument(new ByteArrayInputStream(byteData));
} catch (IOException e) {
e.printStackTrace();
}
/* editing docx file somehow (a lot of useless code) */
Alert alert = new Alert(Alert.AlertType.INFORMATION);
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle("Choose folder");
Stage stage = (Stage) (((Node) event.getSource()).getScene().getWindow());
File file = dirChooser.showDialog(stage);
if (file != null) {
try {
doc.write(new FileOutputStream(file.getAbsoluteFile()));
alert.setContentText("Saved to folder " + file.getAbsolutePath());
} catch (IOException e) {
alert.setContentText(e.getLocalizedMessage());
}
} else {
try {
doc.write(new FileOutputStream("C://output.docx"));
alert.setContentText("Saved to folder C:\\");
} catch (IOException e) {
alert.setContentText(e.getLocalizedMessage());
}
}
alert.showAndWait();
Please help me to figure out what I'm doing wrong :(
DirectoryChooser returns a File object which is either a directory or a null (if you did not choose one by pressing cancel or exit the dialog). So in order to save your file, you need to also append the file name to the absolute path of the directory you choose. You can do that by :
doc.write(new FileOutputStream(file.getAbsoluteFile()+"\\doc.docx"));
But this is platform dependent cause for windows it’s ‘\’ and for unix it’s ‘/’ so better use File.separator like :
doc.write(new FileOutputStream(file.getAbsoluteFile()+File.separator+"doc.docx"));
You can read more about the above here
Edit: As Fabian mentioned in the comments below you can use the File constructor, passing the folder ( the file you got from them DirectoryChooser ) and the new file name as parameters which makes the code far more readable :
new FileOutputStream(new File(file, "doc.docx"))
I'm fairly new to programming and I've been trying to use PDFBox for a personal project that I have. I'm basically trying to verify if the PDF has specific keywords in it, if YES I want to transfer the file to a "approved" folder.
I know the code below is poor written, but I'm not able to transfer nor delete the file correctly:
try (Stream<Path> filePathStream = Files.walk(Paths.get("C://pdfbox_teste"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
String arquivo = filePath.toString();
File file = new File(arquivo);
try {
// Loading an existing document
PDDocument document = PDDocument.load(file);
// Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(document);
String[] words = text.split("\\.|,|\\s");
for (String word : words) {
// System.out.println(word);
if (word.equals("Revisão") || word.equals("Desenvolvimento")) {
// System.out.println(word);
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
document.close();
System.out.println("Arquivo transferido corretamente");
file.delete();
};
}
}
System.out.println("Fim do documento: " + arquivo);
System.out.println("----------------------------");
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I wanted to have the files transferred into the new folder. Instead, sometimes they only get deleted and sometimes nothing happens. I imagine the error is probably on the foreach, but I can't seem to find a way to fix it.
You try to rename the file while it is still open, and only close it afterwards:
// your code, does not work
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
document.close();
System.out.println("Arquivo transferido corretamente");
file.delete();
};
Try to close the document first, so the file is no longer accessed by your process, and then it should be possible to rename it:
// fixed code:
document.close();
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
System.out.println("Arquivo transferido corretamente");
};
And as Mahesh K pointed out, you don't have to delete the (original) file after you renamed it. Rename does not make a duplicate where the original file would need to be deleted, it just renames it.
After calling renameTo, you shouldn't be using delete.. as per my understanding renameTo works like move command. Pls see this
I am trying to open a PDF file that is packaged into the jar file during runtime. The basic idea is that the user clicks the help option and then it displays a help file that is a PDF. Right now I have this in LineFit.class in the linefit package to try and open the help PDF:
try {
File test = new File(LineFit.class.getClass().getResource("/linefit/helpTest.pdf").toURI());
try {
Desktop.getDesktop().open(test);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (URISyntaxException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
It works in eclipse when I run it but if I try to export it to a runnable JAR file it does not open the PDF file and when I look into the JAR, the PDF is in the same folder as when it was in eclipse.
new File(URI) only works for file: URIs. When a classloader finds a resource in a jar, it returns a jar URI, for example jar:file:/C:/Program%20Files/test.jar!/foo/bar.
Fundamentally, the File class is for files on the filesystem. You can't use it to represent a file within a JAR or another archive. You're going to have to copy the file out of the jar and into a regular file, then create a File referencing this new file. To read the file from the jar, you could use JarURLConnection.getInputStream with the URL you have, or you could call ClassLoader.getResourceAsStream.
Try this:
Make sure the path of pdf file is relative path when you use MethodHandles.lookup().lookupClass().getClassLoader()
InputStream is = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream("doc/example.pdf");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
so the problem is that I am having exception thrown each time I try to load the code below on NetBeans or Eclips, but when I try to run it thru TextMate everything works fine!
I tried to put the absolute address, changed the text file etc.. didn't help!
Can someone help me or tell why it won't run with IDE?
Thanks
void loadFile() {
try {
list = new LinkedList<Patient>();
FileReader read = new FileReader("a.txt");
Scanner scan = new Scanner(read);
while (scan.hasNextLine()) {
String Line = scan.nextLine();
String[] subArray = new String[5];
subArray = Line.split(",");
int a = Integer.parseInt(subArray[4]);
list.add(new Patient(Integer.parseInt(subArray[0]), subArray[1], subArray[2], subArray[3], a));
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
cap = list.size();
search_names = new int[cap];
for (int i = 0; i < list.size(); i++) {
search_names[i] = i;
}
setNames(search_names);
}//end loadFile
Debug log:
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar
Have no file for /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar
}
In netbeans the default working directory is always the root folder, i mean the folder which contains the folders which name "src", "build" etc. Place the file along with these folders and it will do the trick.
Here is step by Step procedure in NetBeans IDE 7.0.1
Click on File menu.
Click on Project Properties.
In the categories, select Run.
In main class you select your current java file.
In Arguments select the file you want to read for e.g. abc.txt or abc.java
And in Working Directory write down the path of folder in which this abc.txt or abc.java lies.
Click OK to close Project Properties.
While running your program don't forget to select your project as Main Project.
Then click F^ on keyboard. i.e. You have to raun your main project instead of just running your current java file.
That's it....enjoy!!!!
Finally found the solution
In eclipse you should put the target file in project folder. Guess same applies to NetBeans.
I had my target file in "src" folder (where the actual code files were). In fact i had to just change it to upper folder where the project folder is.
Easy and simple.
Probably you have different "working directories" in you different setups. You can check which directory you are in by printing it like this:
System.out.println(new File(".").getAbsoluteFile());
In eclipse you can set set up the working directory in the run configurations, arguments tab.
Try BufferedReader?
EDIT: Edited to show example more closely to your code. I got excepption when using File Reader. But was able to .println with BufferedReader. I did not use Scanner.
EDIT2: I was also able to get your code to work. With Scanner etc(When using full path) (Example: FileReader read = new FileReader(""C:\\myfolder\\folder\\a.txt". So hmmm.
try {
list = new LinkedList<Patient>();
BufferedReader scan = new BufferedReader(new FileReader("C:\\a.txt"));
String lines;
try {
// Scanner scan = new Scanner(read);
while ((lines = scan.readLine()) != null) {
//I just printed lines you will do your stuff here
System.out.println(lines);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
right click on your text file select properties and copy the path and paste it in the place where you have entered your file name
lets say you wanna add test.txt in netbeans
if your project in C:\myProject put the text file inside C:\myProject file directly not in the C:\myProject\src . then use:
File file = new File("test.txt");
Scanner in = new Scanner(file);
OR
Scanner input = new Scanner(new File("test.txt"));