Choose file using file chooser in java process builder - java

I have the following code
Process p = new ProcessBuilder("D:\\Encryption.exe", "D:\\Cat-hd-
wallpapers_remain_both2.jpg").start();
This code can run fine but instead of declaring "D:\Cat-hd-
wallpapers_remain_both2.jpg" this in my code I want to use file chooser for selecting file.
I use the following code but still not working.
imageUpload.setOnMouseClicked(event -> {
FileChooser fileChooser=new FileChooser();
fileChooser.setInitialDirectory(new File("c:\\"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG Images","*.jpg"),
new FileChooser.ExtensionFilter("JPEG Images","*.jpeg"),
new FileChooser.ExtensionFilter("PNG Images","*.png"));
File file=fileChooser.showOpenDialog(null);
if (file!=null){
try {
imageUpload.setImage(new Image(file.toURI().toURL().toString()));
Process p = new ProcessBuilder("D:\\Encryption.exe",file.getAbsoluteFile().getAbsolutePath()).start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(decriptImageController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
it throws the following error
CreateProcess error=2, The system cannot find the file specified
Can you please help me to find out the problem.Thanks in advanced.

The error "CreateProcess error=2, The system cannot find the file specified" refers to the executable, i.e. Encryption.exe, and has nothing to do with the JPEG file argument passed to it.
There must be something about your 2nd example that is different, but not shown in your question. Perhaps a subtle typo, e.g. Encyrption.exe etc...

Related

Specifying file path in java causes FileNotFoundException

This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.

access denied while saving file using DirectoryChooser

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"))

java.io.FileNotFoundException when creating FileInputStream

Getting an error when trying to open a FileInputStream to load Map from file with .ser extension.
Constructor where I create new File and invoke method that loads map from file:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("database.ser"); // oddly this does not create a file if one does not exist
loadDB();
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn);
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've tried to create file manually and put it in same package with class, but it does not help. What's going on?!
Thank You!
You provide a relative path for the file. That means program will look for the file relative to the working directory.
Depending on how you run the program it will be the directory you run it from (if run from Shell/Cmd) or whatever is configured in the project settings (if run from the IDE). For the latter, it depends on the IDE but usually it's the project root directory.
More info on working directory: https://en.wikipedia.org/wiki/Working_directory
More info on relative path: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
Regarding creation of the file, it would create non-existing file if you were to write to it. When you read it, it expects it to exist. That means you have to create empty file (if one does not exist) before reading or simply treat exception as empty content.
The path to the file you have given might be wrong for IDE it can take relative path but from the command line, it will take the absolute path.

How to Export an eclipse project with pdf generation code(itext)

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.

Exception in moving a file using moveFile method in common io using java

File source=new File(fname1);
System.out.println("souce name "+fname1);
File dest = new File("F:\\BackupFiles",source.getName());
try
{
FileUtils.moveFile(source, dest);
source.delete();
}
catch (IOException ex)
{
Logger.getLogger(FileCompare.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("file moved successfully...");
the above code throws exception
"java.io.IOException: Failed to delete original file 'C:\xampp\htdocs\eyeOS\eyeos\users\ajkani\files\html.txt' after copy to 'F:\BackupFiles\html.txt' "
and i tried to delete the file after copied it to the destination but unable to delete.
i tried deleteOnExit() method instead of delete() but nothing works.
i have used md5 algorithm to check the similarity of two files.
if the files are not same.i want to move the files to destination directory.
From above code, it seems that you want to move one file from one directory to another.
As per this assumption, you can use below code.
String sourcePath = "D:\\other\\new.xls";
File source = new File(sourcePath);
System.out.println("souce name " + sourcePath);
File destDirPath = new File("D:\\");
try {
FileUtils.moveFileToDirectory(source, destDirPath, false);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("file moved successfully...");
This will definitely help you.

Categories

Resources