Java file deletion fails - java

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

Related

Copy all files from Source to Destination Java

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

How to get the path of file when make a jar file in Java

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);
}

File is not Deleting

Am trying to deleting particular file in a folder starting with name TRTHIndicative_.
But files are not deleting,am using below code
testMethod(inputDir);
testMethod(outputFile);
private static void testMethod(String dirName){
File directory = new File(dirName);
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().startsWith("Indicative_")) {
// Delete each file
if(file.exists()){
System.out.println("File is there!");
}
if (file.delete()) {
// Failed to delete file
System.out.println("Failed to delete " + file);
} else {
System.out.println("Deleted file succsfully");
}
}
}
please check and let me know if anything wrong.
You have your if and else confused - File#delete() returns true if the file is successfully deleted. So, the condition should be reversed:
if (file.delete()) {
System.out.println("Deleted file succesfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
Mureinik is right.
I just tried your peace of code. It works fine. Just do the changes as follows:
public class Main {
public static void main(String[] args) {
File directory = new File("C:/temp");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().startsWith("blub")) {
// Delete each file
if (file.exists()) {
System.out.println("File is there!");
}
if (file.delete()) {
System.out.println("Deleted file succsfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
}
}
}
}
Note the toLowerCase() I added. It will make your snippet easier to use.
I think you have permission error in the file you try to delete.
elToro`s answer is working fine with me as well.
Try to give read/write permission to every user
how to change file permissions in windows

Declare actions before run tomcat inside eclipse

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();
}
}

Simulate touch command with Java

I want to change modification timestamp of a binary file. What is the best way for doing this?
Would opening and closing the file be a good option? (I require a solution where the modification of the timestamp will be changed on every platform and JVM).
The File class has a setLastModified method. That is what ANT does.
My 2 cents, based on #Joe.M answer
public static void touch(File file) throws IOException{
long timestamp = System.currentTimeMillis();
touch(file, timestamp);
}
public static void touch(File file, long timestamp) throws IOException{
if (!file.exists()) {
new FileOutputStream(file).close();
}
file.setLastModified(timestamp);
}
Since File is a bad abstraction, it is better to use Files and Path:
public static void touch(final Path path) throws IOException {
Objects.requireNonNull(path, "path is null");
if (Files.exists(path)) {
Files.setLastModifiedTime(path, FileTime.from(Instant.now()));
} else {
Files.createFile(path);
}
}
Here's a simple snippet:
void touch(File file, long timestamp)
{
try
{
if (!file.exists())
new FileOutputStream(file).close();
file.setLastModified(timestamp);
}
catch (IOException e)
{
}
}
I know Apache Ant has a Task which does just that.
See the source code of Touch (which can show you how they do it)
They use FILE_UTILS.setFileLastModified(file, modTime);, which uses ResourceUtils.setLastModified(new FileResource(file), time);, which uses a org.apache.tools.ant.types.resources.Touchable, implemented by org.apache.tools.ant.types.resources.FileResource...
Basically, it is a call to File.setLastModified(modTime).
This question only mentions updating the timestamp, but I thought I'd put this in here anyways. I was looking for touch like in Unix which will also create a file if it doesn't exist.
For anyone using Apache Commons, there's FileUtils.touch(File file) that does just that.
Here's the source from (inlined openInputStream(File f)):
public static void touch(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
final File parent = file.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent + "' could not be created");
}
}
final OutputStream out = new FileOutputStream(file);
IOUtils.closeQuietly(out);
}
final boolean success = file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unable to set the last modification time for " + file);
}
}
If you are already using Guava:
com.google.common.io.Files.touch(file)

Categories