Opening file when hyperlink is clicked - Java FX - java

I have hyperlink created in a textflow container in Java FX. The code provided below only opens the last hyperlinked file even when the preceding links are clicked. I think the problem is in the iteration. Kindly bear with me as I am still fresh on Java. `
String[] splits = lessonResources.split("\\s+");
for(String s: splits){
link = new Hyperlink(s);
lessonResourcesTextFlow.getChildren().add(link);
linked = new File(s);
link.setOnAction((ActionEvent e) -> {
try {
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().open(linked);
} catch (IOException ex) {
Logger.getLogger(LessonPlanController.class.getName ()).log(Level.SEVERE, null, ex);
}
}
} catch (Exception e) {
System.out.println(e);
}
});
}

Including the file constructor within the link event handler solved my problem.
String[] splits = lessonResources.split("\\s+");
for(String s: splits){
link = new Hyperlink(s);
lessonResourcesTextFlow.getChildren().add(link);
link.setOnAction((ActionEvent e) -> {
linked = new File(s);
try {
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().open(linked);
} catch (IOException ex) {
Logger.getLogger(LessonPlanController.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (Exception e) {
System.out.println(e);
}
});
}

Related

Merge pdf files and loss of information

doing the merge of 2 or + pdf I lose some information that imposed in the upload phase of the files (ALT tags on the images). This is the method:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
PDFMergerUtility ut = new PDFMergerUtility();
try {
for (int i = 0; i < filesTBM.length; i++) {
ut.addSource(filesTBM[i]);
}
ut.setDestinationFileName(mergedFileLocation);
ut.mergeDocuments();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}
}
If the PDF with the ALT tags were in the list of files to be merged, the result is correct, otherwise not. So far I've tried max with 3 PDFs including 1 with ALT tags.
The questions:
How can I not lose the alt tag after the merge of the files?
Thanks to those who want to help me
Daniele
N.b. I have also tried iText pdf:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
Document document = new Document();
PdfCopy copy = null;
try {
copy = new PdfCopy(document, new FileOutputStream(mergedFileLocation));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
PdfReader[] reader = new PdfReader[filesTBM.length];
for (int i = 0; i < filesTBM.length; i++) {
try {
reader[i] = new PdfReader(filesTBM[i]);
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.addDocument(reader[i]);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.freeReader(reader[i]);
} catch (IOException e) {
e.printStackTrace();
}
reader[i].close();
}
document.close();
}

Java Serialization not working, appears broken because of IDE

EDIT: The error was caused by Netbeans not the code. Post has been edited to show all the code since the Git files are being removed.
I have a group project at school to design a tower defense game and I have been attempting to add Serialization.
Here is the code:
public class Serialization implements Serializable {
private static FileOutputStream file;
private static ObjectOutputStream write;
public static boolean checkFile(String name){
boolean check = false;
check = new File("log",name+".ser").isFile();
return check;
}
public static void createFile(String name) {
try {
file = new FileOutputStream("log/"+name+".ser");
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ObjectOutputStream openFile(String name) {
try {
file = new FileOutputStream("log/"+name+".ser");
write = new ObjectOutputStream(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
return write;
}
public static void addLine(ObjectOutputStream con,Object data) {
try {
con.writeObject(data);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void readLine(String name){
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream("log/"+name+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.readObject());
in.close();
fileIn.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileIn.close();
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void closeFile(ObjectOutputStream con){
try {
con.close();
} catch (IOException ex) {
Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I eventually abandoned it for two reasons. One it was overkill (trying to have a central class that handles multiple serialization files) and two I could not get it to work with what I am about to talk about.
What I really wanted was to serialize the enemyArray. This holds every living enemy in the game and all their information (stats). If you scroll down to line 192 that is what is left of my serialization attempts:
public void serialize(){
if (Serialization.checkFile("test")==false){
Serialization.createFile("test");
}
ObjectOutputStream connection = Serialization.openFile("test");
for (int x=0;x<enemyArray.length;x++){
if (enemyArray[x]!=null){
Serialization.addLine(connection,enemyArray[x]);
}
}
//Serialization.addLine(connection,enemyArray);
Serialization.closeFile(connection);
enemyArray = null;
Serialization.readLine("test");
//System.out.println(enemyArray[0].id);
// try {
// FileOutputStream fileOut = new FileOutputStream("log/test.ser");
// ObjectOutputStream out = new ObjectOutputStream(fileOut);
// out.writeObject(enemyArray);
// out.writeUTF(t);
// // Do work here
// for (int x=0;x<enemyArray.length;x++){
// if (enemyArray[x]!=null){
// Enemy tmp = enemyArray[x];
// System.out.println(tmp+" >>> "+enemyArray[x]);
// out.writeObject(tmp);
// }
// }
// out.close();
// fileOut.close();
// } catch (FileNotFoundException ex) {
// Logger.getLogger(EnemyController.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(EnemyController.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
It will create the file but will not save anything to it. What is wrong with the code? from what I studied enemyArray shouldn't be static so I removed that and still no change.
Try doing a out.flush(); brefore you close thre output stream.
I found the error after some troubleshooting in the computer lab with my group. Hopefully this can help anyone who finds themselves in my situation or in a similar Java file read/ write issue.
My IDE, Netbeans, shows the file in the files and project list once it is dynamically created, but because it was filled with serialized data and was created after the project was opened and run it would only display an empty file when in reality there is actually data inside the file. String data is fine so it may only be certain data types (like serialized objects) that trigger this error.
Several different versions of my code were correct but they all seemed broken because an empty file was returned to the IDE. The solution is two fold:
Manually check it through your file explorer. It will show a size and can be opened in another editor but may still be buggy in the IDE you ran the program in.
Close down your IDE and on reopening, at least in Netbeans case, the file should be updated correctly.
On a similar note Netbeans may just all together keep showing the empty file instead of offering you the option to select the files encoding. Just view the file in your explorer in this case and if the size is greater than 0 you know your code is ok. This is purely an IDE error.

Jackcess DatabaseBuilder.open fails

I am using Jackcess API in my Eclipse plugin project. I added jackcess-2.1.0.jar file under resources/lib. I included the jar under my Binary build and in build.properties. I successfully make a connection using connection string but my DatabaseBuilder.open() call is not executing. My code is
public void run() {
try {
File tempTarget = File.createTempFile("eap-mirror", "eap");
try {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
try {
FileUtils.copyFile(new File(templateFileString), tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
// Changes
try {
this.target = DatabaseBuilder.open(tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
Collection<String> tables = selectTables(source);
long time = System.currentTimeMillis();
for (String tableName : tables) {
long tTime = System.currentTimeMillis();
Table table = target.getTable(tableName);
System.out.print("Mirroring table " + tableName + "...");
table.setOverrideAutonumber(true);
copyTable(table, source, target);
System.out.println(" took "+ (System.currentTimeMillis() - tTime));
}
System.out.println("Done. Overall time: "+ (System.currentTimeMillis() - time));
System.out.println("done");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// More Code here
} catch (IOException e1) {
}
}
When I run the class in debug mode and I reach DatabaseBuilder.open call it fails.
Here is my project structure:
Can anyone tell me the possible reason for it ?
The .open method of DatabaseBuilder expects to open an existing well-formed Access database file. The .createTempFile method of java.io.File creates a 0-byte file. So, the code
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", "eap");
try (Database db = DatabaseBuilder.open(dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
will cause Jackcess to throw
java.io.IOException: Empty database file
when it tries to do DatabaseBuilder.open(dbFile).
Instead, you should DatabaseBuilder.create to convert the 0-byte file into a real Access database file like this
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", ".accdb");
dbFile.deleteOnExit();
try (Database db = DatabaseBuilder.create(Database.FileFormat.V2010, dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}

PrintWriter: File not found exception?

String path=this.getClass().getResource("info.txt").toString();
void writeinfo()
{
PrintWriter writer = null;
try {
writer = new PrintWriter(path);
writer.println(highscore);
for(int i=1;i<=30;i++)
{
for(int j=1;j<=30;j++)
{
writer.println(v[i][j]);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
writer.close();
}
}
i just pasted the relevant part of the code. It says "java.io.FileNotFoundException", but the file does exist! I searched online but i find no solution to this.

Printing to multiple output files in java

I have two arrays that I want to print to separate files. Here's my code:
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Edges.txt"));
for (i = 0; i < bcount; i++) {
out.println(b[i][0] + " " + b[i][1]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Nodes.txt"));
for (i = 0; i < bigbIter; i++) {
out.println(bigb[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
If I only use the first set of try / catch / catch, it works perfectly. But when I use both it doesn't work, giving me the errors "illegal start of type ... } catch" and "error: class, interface, or enum expected". What am I doing wrong?
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
You have an extra }, which throws off the parser and gives you lots of errors.
You should write a method to write to the file. Just pass the file name and data. You should see that you have too many closing brackets, get your IDE to highlight brackets.
Lesson is just don't copy/paste and then edit the catch block when you want it again!
Edit: Also in java 7 you can have multiple catches in one block, it is better to do this:
catch (FileNotFoundException | IOException e)
{
}

Categories