I want to delete some files from a specific folder when I start tomcat from eclipse. Is there any way to do such a thing and NOT manually go there to delete the files? In visual studio you have the ability to do that.
I have 3 options:
You can make a script that delete these files and then start your Eclipse. Use that function to delete the file:
rm -rf [path_to_the_file]/your_file
After, you can use use whatever method you want to run Eclipse from the script.
Note: You can replace your_file by * to target all the files in the folder.
You can use the same command in the script which is launched when you launch your server
If there is a Java class related to your action, you can add a delete method in it which be executed before launching your server.
Add this code before launching your server:
final File file_to_delete = new File("[path_to_the_file]/your_file");
if (file_to_delete.exists()) {
try {
delete(file_to_delete);
} catch (IOException e) {
throw new IOException(e);
}
}
Add the following method in your class:
public static void delete(File file) throws IOException {
if (file.isDirectory()) {
if (file.list().length == 0) {
file.delete();
} else {
final String[] files = file.list();
for (String temp : files) {
final File fileDelete = new File(file, temp);
delete(fileDelete);
}
if (file.list().length == 0) {
file.delete();
}
}
} else {
file.delete();
}
}
Related
I have to code a java method public void public void copyTo(Path rSource, Path rDest) that copies all files from existing directory rSource to a new directory rDest with the same name. rSource must exist and rDest must not exist, runtime exception if not true. I can't seem to make it work, help!
What I tried :
public void copyTo(Path rSource, Path rDest){
if(!(Files.exists(rSource) && Files.isDirectory(rSource)) || (Files.exists(rDest))){
throw new RuntimeException();
}
try {
Files.createDirectory(rDest);
if(Files.exists(rDest)){
try(DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
for(Path p : stream) {
System.out.println(p.toString());
Files.copy(p, rDest);
}
} catch( IOException ex) {
}
}
} catch (IOException e) {
}
}
Files.copy() at least takes two parameters, source and destination files path or stream. The problem in your case is that you are passing rDest folder Path, not the actual file Path. Just modify the code inside your for loop to append the files name from the source to the destination folder Path:
Path newFile = Paths.get(rDest.toString() + "/" + p.getFileName());
Files.copy(p, newFile);
Correct me if I'm wrong
I am building a game in java and everything works just fine when I run it in intellij idea with no error .
The problem start when i build my project as jar file.
I have this method :
public void addImageOfObject(String add, String dir, ArrayList<ImageIcon> linkedList, Dimension size) {
Image image;
String dirc;
File file = null;
try {
file = new File(classLoader.getResource(dir).getFile());
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
}
try {
for (int i = 0; file.listFiles().length > i; i++) {
try {
dirc = dir + i + ".png";
image = loadImage(dirc);
linkedList.add(new ImageIcon(image.getScaledInstance(size.width, size.height, 4)));
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
e.printStackTrace();
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
JOptionPane.showMessageDialog(StaticVariables.mainClass, "file not found ");
}
}
This is the class loader :
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
I can't get the right path of the file ..when i run it in jar file its give an error file not found on :
file = new File(classLoader.getResource(dir).getFile());
I call to method with this line :
imageLoader.addImageOfObject("src/main/java/","ImageHandel/Photos/character/male/attack/down/",aMale,new Dimension(500,400));
This is the path of files
The number of files I want to get file.listFiles()
In the male folder there is 44 files .. that's the number I want to get in order to run on the loop 44 time and i just can't find the right way to do it! I tried a lot of thing but nothing help me ..
Have any idea what is the problem ?
Simply you can create folder on location where your running jar file,
ImageHandel/Photos/character/male/attack/down/
Run it in jar file by considering that location.
use to add static folder for serving images e.g In spring boot we can configure static folder as follows:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/ImageHandel/**")
.addResourceLocations("file:ImageHandel/")
.setCachePeriod(0);
}
I am creating a rollback feature and here is what I have and wanna achieve:
a tmp folder is created in the same location as the data folder;
before doing any operation I copy all the contents from data folder to tmp folder (small amount of data).
On rollback I want to delete the data folder and rename tmp folder to data folder.
This is what I tried
String contentPath = "c:\\temp\\data";
String tmpContentPath = "c:\\temp\\data.TMP";
if (Files.exists(Paths.get(tmpContentPath)) && Files.list(Paths.get(tmpContentPath)).count() > 0) {
FileUtils.deleteDirectory(new File(contentPath));
Files.move(Paths.get(tmpContentPath), Paths.get(contentPath), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
but this throws FileAlreadyExistsException even though I deleted the target directory in the same method.
Once the program exits I don't see the c:\temp\data directory, so the directory is actually deleted.
Now if I try StandardCopyOption.ATOMIC_MOVE it throws an java.nio.file.AccessDeniedException.
What is the best way to move tmp dir to data dir in these kind of situations?
Actually in java 7 or above you can just use the Files to achieve the folder moving even there is a conflict, which means the target folder already exists.
private static void moveFolder(Path thePath, Path targetPath) {
if (Files.exists(targetPath)) { // if the target folder exists, delete it first;
deleteFolder(targetPath);
}
try {
Files.move(thePath, targetPath);
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
private static void deleteFolder(Path path) {
try {
if (Files.isRegularFile(path)) { // delete regular file directly;
Files.delete(path);
return;
}
try (Stream<Path> paths = Files.walk(path)) {
paths.filter(p -> p.compareTo(path) != 0).forEach(p -> deleteFolder(p)); // delete all the children folders or files;
Files.delete(path); // delete the folder itself;
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
Try This
public class MoveFolder
{
public static void main(String[] args) throws IOException
{
File sourceFolder = new File("c:\\temp\\data.TMP");
File destinationFolder = new File("c:\\temp\\data");
if (destinationFolder.exists())
{
destinationFolder.delete();
}
copyAllData(sourceFolder, destinationFolder);
}
private static void copyAllData(File sourceFolder, File destinationFolder)
throws IOException
{
destinationFolder.mkdir();
String files[] = sourceFolder.list();
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
copyAllData(srcFile, destFile); //call recursive
}
}
}
Figured out the issue. In my code before doing a rollback, I am doing a backup, in that method I am using this section to do the copy
if (Files.exists(Paths.get(contentPath)) && Files.list(Paths.get(contentPath)).count() > 0) {
copyPath(Paths.get(contentPath), Paths.get(tmpContentPath));
}
Changed it to
try (Stream<Path> fileList = Files.list(Paths.get(contentPath))) {
if (Files.exists(Paths.get(contentPath)) && fileList.count() > 0) {
copyPath(Paths.get(contentPath), Paths.get(tmpContentPath));
}
}
to fix the issue
I need to delete files from within a java program and have written this code. It fails to delete the file and I can't figure why. The File is not in use and not write protected.
public static void delfile(String filetodel) {
try {
File file = new File("filetodel");
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed." + filetodel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I guess the issue is this:
File file = new File("filetodel");
This should possibly be (inferred from the parameter filetodel passed in the method):
File file = new File(filetodel);
Everything else seems fine, and is working on my machine.
If you just want to delete the file, there is no need for loading it.
java.nio.file.Files.deleteIfExists(filetodel); (where filetodel contains the path to the file)
Returns true if the file was deleted, so you can even put it in your if-clause.
hey buddy you should use a path as parameter in delete
static void delete(Path path)
Deletes a file.
static boolean deleteIfExists(Path path)
Deletes a file if it exists.
search here: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
so in your case
File file = new File("c://user//filetodel");
file.delete();
or use getAbsolutePath(filename) and use it in file path
Here is my code to delete file.
public class deletef
{
public static void main(String[] args)
{
try{
File file = new File("/home/rahul/Downloads/ou.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
your code is also right but you have to put extension also in your file
File file = new File("filetodel");
here add extension also of file other wise your code will not delete file
How can I introduce automatic updates and restart feature in Java Swing applications.
Also I needed to roll back to previous versions.
I have made a application jar file and launcher jar file, which launches the application jar file.
This attempt was successful. But I can not integrate these two jar files, when creating a installer for MacOSX.
The Launcher class as follows:
public class Launcher {
private final Logger logger = Logger.getLogger(Launcher.class.getName());
private String getVersionNumber() throws IOException {
try {
JarFile runningJarFile = new JarFile(new File("Application.jar"));
String versionNumber = runningJarFile.getManifest()
.getMainAttributes().getValue("Bundle-Version");
runningJarFile.close();
logger.log(
Level.SEVERE,
new StringBuilder()
.append("The version number of existing Application.jar file is ")
.append(versionNumber).toString());
return versionNumber;
} catch (IOException e) {
logger.log(
Level.SEVERE,
new StringBuilder()
.append("Could not read the version number from existing Application.jar")
.append(Arrays.toString(e.getStackTrace()))
.toString());
throw new IOException(e);
}
}
private void updateApplication() {
try {
File updateDirectory = new File("Update");
if (updateDirectory.isDirectory()) {
if (updateDirectory.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("\\.");
}
}).length > 0) {
String versionNumber = getVersionNumber();
logger.log(
Level.SEVERE,
new StringBuilder()
.append("A new update is available. Rename the existing Application.jar to ")
.append(versionNumber)
.append(".jar")
.append(" and rename the new_Application.jar to Application.jar")
.toString());
File Application = new File("Application.jar");
Application.renameTo(new File(new StringBuilder()
.append(versionNumber).append(".jar").toString()));
File newApplication = new File("Update/new_Application.jar");
newApplication.renameTo(new File("Application.jar"));
newApplication.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE,
new StringBuilder().append("Could not update Application")
.append(Arrays.toString(e.getStackTrace()))
.toString());
}
}
private void launchApplication() {
try {
logger.log(Level.SEVERE, "Lauching Application.jar");
ProcessBuilder pb = new ProcessBuilder("Java", "-jar", "Application.jar");
pb.start();
} catch (IOException e) {
logger.log(Level.SEVERE,
new StringBuilder().append("Could not launch Application.jar ")
.append(Arrays.toString(e.getStackTrace()))
.toString());
}
}
private void quitLauncher() {
logger.log(Level.SEVERE, "Launcher is exiting");
System.exit(0);
}
private void startApplication() {
updateApplication();
launchApplication();
quitLauncher();
}
public static void main(String[] args) {
Launcher launcher = new Launcher();
launcher.startApplication();
}
}
Thanks
First of all, are you creating a standard installer package (mpkg or pkg)?
You should make the launcher download the update, and then execute it (with /usr/sbin/installer ). After that, the installer should have a postflight/postinstall/postprocessing script that kills any app with the name of yours (this can be as tricky as looking for a process with a given name..), and then launches the recently installed app.
This makes that your app will be launched even, after the first install (you may avoid this making it check if it is an update or not -saving a marker file from the Launcher "updating.txt" may suffice- )
Here is a full guide of how to create installer packages (almost form scratch): Making OS X Installer Packages like a Pro - Xcode Developer ID ready pkg
Or well, you may use this cool tool: http://s.sudre.free.fr/Software/Packages/about.html
I expect this all is not an overkill for what are you looking for.