How do I properly handle file copy/cut & paste in javafx? - java

I'm working on a program in which I want to add the possibility of copy-pasting (or cut-pasting) files. I could create it so it only works within the program, but it would be nicer if I could use the system-wide clipboard. That has one huge problem though: when pasting I don't know if files are copied or cut from the system explorer, I only get the file locations.
I am using Java and the javafx clipboard. Some sample code:
Clipboard clipboard = Clipboard.getSystemClipboard();
List<File> files = clipboard.getFiles();
// destDir is a File, the target directory.
for (File oldFile : files) {
if (oldFile.isDirectory()) {
FileUtils.copyDirectoryToDirectory(oldFile, destDir);
} else {
FileUtils.copyFileToDirectory(oldFile, destDir);
}
}
Here I simply copy the files, but how do I for example know when to use FileUtils.copyDirectoryToDirectory and when to use FileUtils.moveDirectoryToDirectory (aka copy or cut)?
Thanks,
Luca

Turns out, as pointed out by Fildor , that this is only possible when using drag and drop with the Dragboard. The Clipboard does not have such functionality.

Related

How to save files programmatically in Eclipse without using an editor?

I am developing an Eclipse plug-in that programmatically modifies C++ files from the workspace. I am now trying to save the changes made. I have taken a look at this solution : How can I call save method in eclipse plugin development programmatically but this includes having the files I want to save open in the editor. Since I have
5k+ files to modify and save, I cannot afford to open them all in an editor before saving.
While looking for a solution I found this topic on the official Eclipse forum : https://www.eclipse.org/forums/index.php/t/1070377/ . Unfortunately, no answer has been provided.
I have tried using :
PlatformUI.getWorkbench().getService(IHandlerService.class).executeCommand("org.eclipse.ui.file.saveAll", event)
or
IWorkspace.save(boolean, IProgressMonitor)
or
ITranslationUnit.save(IProgressMonitor, boolean)
or
ICProject.save(IProgressMonitor, boolean)
but none of these solution worked.
My question is therefore :
How to save files programmatically in Eclipse without using an editor ?
Thanks a lot in advance
EDIT :
example of what I'm trying to achieve
deleteAndSave(IFunction functionToDelete) {
boolean forceDeletion = true;
IProgressMonitor progressMonitor = new NullProgressMonitor();
//delete the portion of code
functionToDelete.delete(forceDeletion, progressMonitor);
//we get the file containing the function
IFile file = (IFile) functionToDelete.getUnderlyingResource();
//save the file to the disk (ideally 'file.save()' ?)
file.getWorkspace().save(true, progressMonitor);
}
At the end of this execution, I would expect the new version of the file to be saved on the disk. The function is correctly deleted and the modifications appear in the IDE if I open the file in the editor, but the file is marked as unsaved by Eclipse (showing a star before the file name).
EDIT :
While this doesn't answer the question (without using an editor), I got the correct behaviour with :
deleteAndSave(IFunction functionToDelete) {
IProgressMonitor progressMonitor = new NullProgressMonitor();
IWorkbenchPage activePage = PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage();
functionToDelete.delete(true, progressMonitor);
IFile file = (IFile) functionToDelete.getUnderlyingResource();
IEditorPart editorPart = IDE.openEditor(activePage, file);
editorPart.doSave(progressMonitor);
activePage.closeEditor(editorPart, false);
}
However this opens an editor page for each file and closes it immediately, so the performance are not satisfying for a large volume of files.
It sounds like the problem might be that your operation is modifying the working copy of a file, and not the underlying file itself.
Changes to the working copy can be synced to the underlying file by calling IWorkingCopy.commit().
Does the following help?
...
functionToDelete.delete(forceDeletion, progressMonitor);
ITranslationUnit tu = functionToDelete.getTranslationUnit();
if (tu.isWorkingCopy()) {
boolean forceCommit = true;
((IWorkingCopy) tu).commit(forceCommit, progressMonitor);
}

JavaFX-8 FileChooser Image (backend copy-paste)

This is only the second question I have ever posted here on Stack Overflow, so hey guys! (please be gentle).
The next step in the project I'm doing involves files and the FileChooser library. Say I got the FileChooser to work, and that on a button click, the FileChooser opens and you can select the image you want.
Now say that the image comes from a flash drive plugged in to the computer. After taking the image, the filepath is stored into the database for later retrieval. But the problem, is that the filepath will be rendered useless when the flashdrive is plugged out.
Is there any way that to do a behind the scenes copy-paste of the image to the program's directory, so that I only need to take the filename, and append that to the default varchar value (proper directory minus filename) of the filepath column in the database?
I may be wording this wrong. This is in JavaFX-8 by the way. Any help would be appreciated.
Use Files.copy
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
Note: source and destination are references of Path. Also, Files is located in the package java.nio.file
File source = new File("path//myimage.jpg");
File dest = new File("myimage.jpg");
try {
FileUtils.copyFile(source, dest);
} catch (IOException e) {
throw new IOException("DP Report Template File is not there");
}
This will copy the file to your program directory.

How to remove ICEpdf temporary files after application has finished working?

I use ICEpdf library for PDF displaying at my desktop java application. Application adds annotations to PDF at runtime, but without changing original files — changes are displayed only during one 'session'. I recently discovered that application creates a lot of temporary files which consume quite a lot of disk space.
Method org.icepdf.core.pobjects.Document.setInputStream has the following code:
// Delete temp file on exit
tempFile.deleteOnExit();
So I suppose it has to remove temporary files after it used them, but it does not:
How can I programmatically remove all files created by application on exit or make standard file removing work?
To get temp folder path:
FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"))
To remove files:
try (DirectoryStream<Path> paths = Files.newDirectoryStream(pathToDir, regex)){
paths.forEach(path -> path.toFile().delete());
} catch (IOException e) {
// handle io exception
}
where regex is filename pattern. In your case: "IcePdf*"

How to set up Eclipse project to load an image so that it also runs from the command line

I've built a Java application that loads an image at runtime. The location of the image is fixed relative to the project.
I would like to be able to run the program from both within Eclipse and the command line and for it to load the image correctly. However, I can only do one or the other but not both. This seems like such a trivial thing to want to do but I can't find out how to do it.
The project is set up so that it creates a bin directory for the output and puts the image in a resources sub-folder. This is fine when running from the command line as I can write my code to look in that sub folder for the file.
But when I run the program from within eclipse the current working directory is different.
What am I missing?
TIA
Update - adding some code
This is what I had originally:
BufferedImage awtImage = ImageIO.read(new File(System.getProperty("user.dir") + "/resources/image-name.png"));
Following the advice in the comments I am trying to use getResourceAsStream but I don't know what to pass to the File constructor.
InputStream temp = MyClass.class.getResourceAsStream("resources/image-name.png");
BufferedImage awtImage = ImageIO.read(new File(???));
The resource is being found because temp is not null.
I think there's 2 solutions.
1) you specify an absolute path
2) your image is in the classpath so you could load it via :
YouClass.class.getResourceAsStream("YourImg.png");
The working directory, if that's really what you mean, is not a great place to load an image from. It appears that you have an image that you would distribute with your finished program so that the program could use it. In that case, I suggest that you use Class.getResourceAsStream(), and put the image in the directory with (or near) that class.
EDIT:
Here is code I used in one of my programs for a similar purpose:
ImageIcon expandedIcon = null;
// ...
expandedIcon = new ImageIcon(TreeIcon.class.getResource("images/Expanded.png"));
The ImageIcon class is part of Swing; I don't know if you're using that, but this should serve to show you the idea. The getResource() method takes a URL; again, you might need something a little different. But this shows the pathname relative to the path of the class on which the method is called, so if TreeIcon is in x/y/z/icons, the PNG file needs to be in x/y/z/icons/images, wherever that is on that computer.
TreeIcon is a class of mine, and its internals will not help you, so I'm not posting them. All it's doing here is providing a location for the PNG file I'm loading into an ImageIcon instance.
In addition to working on a disk with a directory structure, this also works in a jar file (which is a common way to distribute a java program or library). The jar file is just a zip file, and each file in the jar/zip file has its directory associated with it, so the image can be in the jar in the correct directory just as the java classes are in their directories.
getResourceAsStream() returns a stream; if you want to use that byte stream to load as an image, find a class that converts an stream to something your image class can use as a constructor or in a load method and hook them up. This is a common thing to have to figure out with Java i/o, unfortunately there is no cookbook way to do it across all images and situations, so we can't just tell you what it is.
EDIT 2:
As from the comment, try:
ImageIO.read(new File(MyClass.class.getResource("resources/image-name.png");
I set up my Eclipse projects like this.
The input directory is added to the classpath (JavaBuildPath in Eclipse).
Finally, you access the image and / or text files like this.
private BufferedImage getIconImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

How to Move file in the same storage by changing path sytem level Android

How to move file not copy by just changing the path of file system level in android I have path like this
File f = new File(/storage/Folder1/Folder2/image.png);
File newfile = new File((/storage/Folder3/image.png);
I want to change the path of f to newfile without coping because it takes time and system give us support if we are in same mount point we can move file super fast just like if we move file in dextop windows in the same drive then speed is so fast I want to achieve same thing
Please give some sample code.
You can use Files.move, with options for retaining file attributes and detailed error reporting via several exceptions:
try {
Files.move( f.toPath(), newFile.toPath() );
} catch(...){
...
}
Possibly also the simpler method works for you, although this is more implementation dependent:
f.rename( newFile );

Categories