Cannot delete file because it is open due to merger class (pdf) - java

I am getting the following error while running this code. I found that it happens because of the merger.mergesPagesFromPdfFiles() function. How can i prevent this to happen? I tried several things but nothing worked.
java.nio.file.FileSystemException: C:\Users\Ben\Desktop\Post\Klanten\10817 - TEST TEST\Factuur TEST TEST.pdf: (Translated) The process does not have access because the file is used by another process
Merger merger = new Merger();
merger.mergesPagesFromPdfFiles(filesToSend, getPathPostTS().toString() + "\\"
+ CustomFunctions.generatePersonalFileName("Documenten", client) + ".pdf");
//Runtime.getRuntime().gc();
//merger = null;
for (String file : filesToSend) {
File fileEntry = new File(file);
try {
fileEntry.setWritable(true);
java.nio.file.Files.deleteIfExists(fileEntry.toPath());
//Another way of trying to delete it
if (fileEntry.delete()) {
System.out.println(fileEntry.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(folder.list());
if (folder.list().length > 0) {
folder.delete();
} else {
JOptionPane.showMessageDialog(null, "FOLDER IS NIET LEEG, KIJK NA");
}
And here is the merger class creating the conflict.
public Merger() {
}
public void mergesPagesFromPdfFiles(List<String> pdfFiles, String outputFileLocation) {
try {
Document document = new Document();
FileOutputStream fos = new FileOutputStream(outputFileLocation);
PdfCopy writer = new PdfCopy(document,fos );
writer.setMergeFields();
document.open();
for (String pdf : pdfFiles) {
int index = pdf.lastIndexOf("\\");
String pdfName = pdf.substring(index + 1, pdf.indexOf(".pdf"));
PdfReader reader = new PdfReader(pdf);
// if(reader.getNumberOfPages() < mergePageNr){
// System.err.println("'" + pdfName + "' has not enough pages to
// merge. Skipped to next pdf!");
// continue;
// }
writer.addDocument(reader);
}
System.out.println("Files merged!");
document.close();
writer.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks for helping out!
edit: complete error plus changed code to close fos
Files merged!
java.nio.file.FileSystemException: C:\Users\Ben\Desktop\Post\Klanten\10817 - TEST TEST\Factuur TEST TEST.pdf: Het proces heeft geen toegang tot het bestand omdat het door een ander proces wordt gebruikt.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(Unknown Source)
at java.nio.file.Files.deleteIfExists(Unknown Source)
at generalClasses.Generator.sendAllFilesWithPost(Generator.java:243)
at factuurGen.FactuurGenerator.(FactuurGenerator.java:63)
at factuurGen.FactuurOptionPanel.generate(FactuurOptionPanel.java:31)
at view.MainView.generateAllDocuments(MainView.java:368)
at view.MainView.lambda$1(MainView.java:309)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Related

Save Word-file with Java (runnable JAR)

I´m trying to build an application which can read information from Excel files and place the data into a document. The document is a form of a template with columns in. Everything works just fine until the saving part.
It work, almost, like it should when I run the program directly in IntelliJ. However, when I install the application to an runnable JAR with Maven - the JAR won't work.
The file is saved as desired... But the new file contains nothing if I run the application from JAR. When i run directly in IntelliJ, the new file is been created and opened, but of 3 columns / row, only 2 has data in it.
What can I do?
Link to template document
http://www.labelmedia.de/englisch/doc/70%20x%2032%20mm%20-%20Art.%2088%2010%2027%2070%2032.doc
Thank you in advanced
package utils;
import model.Customers;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class WriteToDocument {
String TARGET_FILE = "src\\main\\java\\utils\\template\\template.doc";
private int postInList = 0;
public WriteToDocument() {}
public WriteToDocument(ArrayList<Customers> list) throws IOException {
list.remove(0);
HWPFDocument doc = null;
try {
doc = openDocument(TARGET_FILE);
Range range = doc.getRange();
TableIterator itr = new TableIterator(range);
while (itr.hasNext()) {
Table table = itr.next();
for (int rowIndex = 0; rowIndex < table.numRows(); rowIndex++) {
TableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.numCells(); colIndex++) {
TableCell cell = row.getCell(colIndex);
//WRITE IN TABLE //
if (postInList < list.size()) {
cell.getParagraph(0).replaceText(list.get(postInList).getName() + "\n\r" +
"\n\r" + list.get(postInList).getAddress() + "\n\r" +
list.get(postInList).getPostcode() + " " + list.get(postInList).getCity(), false);
postInList++;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
saveDocument(doc);
}
}
private HWPFDocument openDocument(String file) throws Exception {
System.out.println("OPEN");
return new HWPFDocument(new POIFSFileSystem(new FileInputStream(file)));
}
private static void saveDocument(HWPFDocument doc) throws IOException {
System.out.println("SAVE");
try (FileOutputStream out = new FileOutputStream(new File("test.doc"))) {
doc.write(out);
out.flush();
System.out.println("File saved");
doc.close();
out.close();
Desktop dt = Desktop.getDesktop();
dt.open(new File("test.doc"));
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
Stacktrace
java.io.FileNotFoundException: src\main\java\utils\template\template.doc (Det går inte att hitta sökvägen)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at utils.WriteToDocument.openDocument(WriteToDocument.java:56)
at utils.WriteToDocument.<init>(WriteToDocument.java:25)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
SAVE
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at utils.WriteToDocument.saveDocument(WriteToDocument.java:62)
at utils.WriteToDocument.<init>(WriteToDocument.java:49)
at utils.ReadExcel.writeToDocument(ReadExcel.java:64)
at utils.ReadExcel.<init>(ReadExcel.java:57)
at MainFrameController$1.actionPerformed(MainFrameController.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Most probably you are missing libraries when it is exported as a JAR. You are using Apache POI as external libraries. Inside the IDE all the libraries were applied but when exported, they seems to be missing. Just run the jar file from command prompt to be 100% clear about the issue. In IDEs like NetBeans the libraries are exported into a separate folder called lib have a look for similar related to your IDE as well.

Move a file to a specific folder

I'm trying to move a file to a specified folder but I can't.
This is the code:
public static void moveToRightDirectory(File song, String album) throws IOException {
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
String pathDirectory = selectedDir + "\\" + album;
File dir = new File(pathDirectory);
System.out.println("dir.exists(): " + dir.exists());
if(dir.exists()) {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
}
else {
boolean success = (new File(pathDirectory)).mkdirs();
if(!success) {
System.out.println("Error creating directory.");
}
else {
Files.move(song.toPath(), dir.toPath(), StandardCopyOption.REPLACE_EXISTING );
//System.out.println(song.renameTo(dir));
//FileUtils.moveFile(song, dir);
}
}
}
I know there are other message about this (from these I was inspired) but I wasn't able to solve so I would ask for your help.
I would like to move the song file in the folder dir. To do this I have tried several methods:
Files.move -> The following errors are generated:
Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Trailing char < > at index 55: C:\Users...\dir
at sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at java.io.File.toPath(Unknown Source)
at createDir.CreateDirectory.moveToRightDirectory(CreateDirectory.java:73)
at createDir.CreateDirectory.createDirectory(CreateDirectory.java:40)
at gui.DirChooser.actionPerformed(DirChooser.java:54)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
song.renameTo(dir) -> It does nothing.
FileUtils.moveFile(song, dir); -> Eclipse does not find FileUtils. I did the import of java.lang.Object.org.apache.commons.io.FileUtils but the error becomes "The import java.lang.Object.org can not be resolved."
How can I fix?
Thanks a lot.
Not an answer to the actual question, but, based on the error message
java.nio.file.InvalidPathException: Trailing char < > at index 55:
I'm guessing your code isn't getting rid of the trailling whitespaces properly.
Try
album = album.trim();
Instead of
if(album.endsWith(" ")) {
album = album.substring(0, album.length() - 1);
}
http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
Maybe this will be of assistance
Step 1 : Rename File
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Step 2: Copy and delete
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}

Serialize and Saving an ArrayList of double [] in Java

I want to serialize and save an arraylist that contains a double [] arraylist in java. Here is my code.
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
public void writeArrayListToFile(ArrayList<ArrayList<double []>> arraylist, String outputFilePath){
System.out.println("Start saving the file at : " + outputFilePath);
try {
fileOutputStream = new FileOutputStream(outputFilePath , true);
objectOutputStream = new ObjectOutputStream(objectOutputStream);
objectOutputStream.writeObject(arraylist);
System.out.println("Arraylist Saved Successfully...");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But I get an error and following is the stack trace.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
at java.io.ObjectOutputStream.(Unknown Source)
at com.fyp.imur2.SaveArrayListToFile.writeArrayListToFile(SaveArrayListToFile.java:24)
at com.fyp.imur2.JPanelJFreeChart.btnSaveGestureCollectionActionPerformed(JPanelJFreeChart.java:380)
at com.fyp.imur2.JPanelJFreeChart.access$5(JPanelJFreeChart.java:375)
at com.fyp.imur2.JPanelJFreeChart$6.actionPerformed(JPanelJFreeChart.java:166)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Can someone help me to solve this issue? Any help would be appreciated. Thanks in advance.
Need to pass fileOutputStream while constructing the instance of ObjectOutputStream
objectOutputStream = new ObjectOutputStream(fileOutputStream);
on the line
objectOutputStream = new ObjectOutputStream(objectOutputStream);
You try to call the constructor with the objectOutputStream object, which is null. Looks like you meant to call it with fileOutputStream, like this:
objectOutputStream = new ObjectOutputStream(fileOutputStream);

File copy access denied

Here I am trying to copy a file one location to another. I am having the source address as
F:\C#\Studies\OS\ch4.ppt
where I want to copy ch3.ppt to another location where user chooses .ie., fetching the destination address from the JFilechooser(Where ever the user wants to copy). Here I am getting access denied error
{
//Getting the value of fileLocationSourceDrive from table.
//fileLocationSourceDrive contains F:\C#\Studies\OS\ch4.ppt
JFileChooser location = new JFileChooser();
location.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
location.showSaveDialog(null);
String fileLocationDestination = location.getSelectedFile().getAbsolutePath().toString();
copyFile(fileLocationSourceDrive, fileLocationDestination);
}
public static void copyFile(String sourceFileName, String destionFileName) {
try {
System.out.println("Reading..." + sourceFileName);
File sourceFile = new File(sourceFileName);
File destinationFile = new File(destionFileName);
InputStream in = new FileInputStream(sourceFile);
JOptionPane.showMessageDialog(null, destinationFile);
OutputStream out = new FileOutputStream(destinationFile);
//OutputStream out = new FileOutputStream("C:\\Users\\Sagar Ch\\Documents\\New folder");
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("Copied: " + sourceFileName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here the error block(Getting access denied)
Reading...F:\C#\Studies\OS\ch4.ppt
java.io.FileNotFoundException: C:\Users\Sagar Ch\Documents\New folder (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at main.copyFile(main.java:1277)
at main$22.actionPerformed(main.java:1127)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I believe that the problem is that you are trying to write the file (copy it, rather) onto the path of C:\Users\Sagar Ch\Documents\New folder, and that is not a "file", that's an existing folder. You should copy ch4.ppt to C:\Users\Sagar Ch\Documents\New folder\ch4.ppt.

How to choose file and then submit in Java swing?

The UI has two buttons, browse and submit. I want the user to hit browse to find a file, and then submit to copy it to a different location. However whenever I attempt it, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at me.trevor1134.modinjector.ModInjector$3.actionPerformed(ModInjector.java:154)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
"Submit" button actionPerformed :
#Override
public void actionPerformed(ActionEvent arg0) {
if (mod.exists()) { //line 154 mod is a file object
OS = System.getProperty("os.name").toLowerCase();
detectOS();
modLocation = new File(fullPath);
if (modLocation.exists() && modLocation.isDirectory()) {
Path newP = modLocation.toPath();
Path oldP = mod.toPath();
try {
Files.copy(oldP, newP);
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(frame, "Mod successfully copied to: "
+ fullPath);
System.out.println("Mod successfully copied to: " + fullPath);
}
}
}
Browse button code:
#Override
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser(homePath + "\\Downloads");
FileNameExtensionFilter filter = new FileNameExtensionFilter("ZIP & JAR Files",
"zip", "jar");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File mod = fc.getSelectedFile();
textField.setText(mod.getAbsolutePath());
System.out.println("File: " + mod.getName());
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
I basically want the variable mod to carry on to the Submit area, but because of where it is set, I am unable to do so.
In your "browse" button code you are initializing a local variable mod like this:
final File mod = fc.getSelectedFile();
In the "Submit" button code you are using a class variable mod. Same name, different variables with different scopes.
Try changing:
final File mod = fc.getSelectedFile();
to
mod = fc.getSelectedFile();
with mod being a private class variable.
Also add null check in the "Submit" button code.

Categories