I'm trying to delete files but it isn't working or I'm missing something.
Here is a little test I'm doing:
private void deleteFromDir(String filename) {
String path = "./test/pacientes/" + filename + ".tds";
File f = new File(path);
System.out.println("Abs path " + f.getAbsolutePath());
System.out.println("Exist " + f.exists());
System.out.println("Filename " + f.getName());
System.out.println("Delete " + f.delete());
}
And the system prints:
Abs path C:\Users\XXXX\Documents\PAI\TSoft.\test\pacientes\John Smith.tds
Exist true
Filename John Smith.tds
Delete false
And of course isn't deleting the file, why? How can I make it work?
Perhaps, you do not have the permission to delete this file. You can use the Files.delete() method, which throws an IOException, in case something goes wrong, to see what the real problem is.
Related
I am trying to move one folder from c:\root to a different place, let's say, directly to the project folder by using the code below. The variable newFolder is declared as class variable and it has been used in another method where user can rename folder to a different name and it holds the name of the folder that I want to move. The variable fileManager is for a new folder where I want to move my folder. When I run this code I always get "Folder " + fileManager.getName() + " is not moved.". So for some reason it skips if condition and goes to else without moving the folder where I want. Can some one show me how to modify my code in order to move one folder from one place to another one?
File fileManager = new File(newFolder.getName());
try{
if(fileManager.renameTo(new File(fileManager.getName()))){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
You need to call renameTo() on the existing file.
Your code currently is trying to rename the new folder (fileManager) to something, but the new folder (probably) does not exist on your filesystem so it returns false because there is nothing to rename.
Actually, I can't see anything that looks like the original file handle anywhere in this code, but you are going to need the original file in order to rename it.
Your code actually does nothing since it just renames a file to itself:
fileManager.renameTo(new File(fileManager.getName())
I am not sure whether this would return true or false if the file exists already on the OS. Does it count as a "successful rename" if you rename a file to itself?
You probably want something that looks more like this (guessing variable names):
oldFileOrFolder.renameTo(fileManager)
I also got rid of the new File constructor since your object already is of type File.
I would use the Files.move method instead, I had no issues with it. Below is an example using a file instead of a folder.
static File fileManager = new File("C:\\template.xls");
public static void main(String[] args) throws IOException {
Path originalPath = Paths.get(fileManager.getPath());
Path newPath = Paths.get(System.getProperty("user.dir")+ "\\template.xls");
if(Files.move(originalPath, newPath , StandardCopyOption.REPLACE_EXISTING) != null){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}
As suggested by gnomed, you can also fix your issue with the renameTo method by calling it on the original folder/file, which in this case might be 'newFolder' (confusing name) since it looks to be an actual reference to a file. Below is code with the revision.
static File newFolder = new File("C:\\template.xls");
public static void main(String[] args) {
File fileManager = new File(newFolder.getName());
try{
if(newFolder.renameTo(fileManager)){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
}
I have a program which reads a file every time and now I want to read the event log file of windows ,how can I get the location and read its contents.
The logs are stored in the %SystemRoot%\System32\Config directory with a .evt extension. Within the Computer Manager you can also export them to a .txt or .csv file.
Windows Vista/7/Server2008 location, here it is: %SystemRoot%\system32\winevt\logs
My Code is:
String fileSeperator = File.separator;
String filePath = "C:" + fileSeperator + "WINDOWS" + fileSeperator + "system32" + fileSeperator + "winevent" + fileSeperator + "logs";
System.out.println("FilePath :" + filePath);
File f = new File(filePath);
System.out.println("Is Directory :" + f.isDirectory());
The Output:
FilePath : C:\WINDOWS\system32\winevent\logs
Is Directory :false
Why does it return it is not a directory?
Because the file doesn't exist. You said yourself that the location was %SystemRoot%\system32\winevt\logs. Yet you use C:\WINDOWS\system32\winevent\logs.
winevt != winevent.
This is the code I tried. But this returns false even if the file exists. The variables FilePath and FileName is obtained from the UI.
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
boolean exists = exportFile.exists();
if (!exists) {
System.out.println("File does not exists");
}
else{
System.out.println( "File exists.");
}
What is the proper way to do this? And BTW, How can I prompt the user to replace or rename the FileName?
replace
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
with
File exportFile = new File(FilePath + "\\" + FileName);
There is no need for quoting the file name. Even if it contains spaces.
I think the problem might be caused by the way you get the file path, since you are getting it from UI, i should point out that you don't have to construct the path, you can either use getAbsolutePath() or getPath() methods provided in the java.io.File class.
My upload servlet keeps throwing me an exception saying that the file that I'm trying to replace (near the end of my code) could not be deleted at (seemingly) random. I don't know what's causing this since I'm not using any streams and the file isn't open in my browser. Does anyone know what could be causing this? I'm completely clueless on this one as the code seems correct to me. This is the first time I've used DiskFileItem so I'm not sure if there are any nuances to handle there.
Keep in mind that it sometimes works, sometimes doesn't. I'm lost on that.
Problem Area:
File destination = new File(wellnessDir + File.separator + fileName + ".pdf");
System.out.println("destination file exists: " + destination.exists());
System.out.println("file to be moved exists: " + uploadedFile.exists());
if(destination.exists()){
boolean deleted = destination.delete();
if(!deleted)
throw new Exception("Could not delete file at " + destination);
}
My System outs always say that both file and destination exist. I'm trying to get the upload to overwrite the existing file.
Full code: (& pastebin)
private void uploadRequestHandler(ServletFileUpload upload, HttpServletRequest request)
{
// Handle the request
String fileName = "blank";
try{
List items = upload.parseRequest(request);
//Process the uploaded items
Iterator iter = items.iterator();
File uploadedFile = new File(getHome() + File.separator + "temp");
if(uploadedFile.exists()){
boolean tempDeleted = uploadedFile.delete();
if(!tempDeleted)
throw new Exception("Existing temp file could not be deleted.");
}
//write the file
while (iter.hasNext()) {
DiskFileItem item = (DiskFileItem) iter.next();
if(item.isFormField()){
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if(fieldName.equals("fileName"))
fileName = fieldValue;
//other form values would need to be handled here, right now only need for fileName
}else{
item.write(uploadedFile);
}
}
if(fileName.equals("blank"))
throw new Exception("File name could not be parsed.");
//move file
File wellnessDir = new File(getHome() + File.separator + "medcottage" + File.separator + "wellness");
File destination = new File(wellnessDir + File.separator + fileName + ".pdf");
System.out.println("destination file exists: " + destination.exists());
System.out.println("file to be moved exists: " + uploadedFile.exists());
if(destination.exists()){
boolean deleted = destination.delete();
if(!deleted)
throw new Exception("Could not delete file at " + destination);
}
FileUtil.move(uploadedFile, new File(wellnessDir + File.separator + fileName + ".pdf"));
writeResponse();
} catch (Exception e) {
System.out.println("Error handling upload request.");
e.printStackTrace();
}
}
edit: to add, getHome() and "home" aren't really in the code, that's just to protect my home path
After much testing and aggravation, finally tried it on a different machine, same code, worked great. Has something to do with me transferring domains on my work machine and it messing with permissions.
I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid.
It seems, however, that tDir.mkdir(); is not doing anything, and therefore the success variable is always false. I cannot understand why. Thank you in advance.
System.out.println("experimentDir: " + experimentDir);
System.out.println("item.getName(): " + item.getName());
System.out.println("dirName: " + dirName);
String tDirStr = experimentDir + "/" + item.getName() + "All/"
+ dirName + "DataAll";
System.out.println("tDirStr: " + tDirStr);
File tDir = new File(tDirStr);
if (tDir.exists()) {
System.out.println("EXISTS!!!");
} else {
boolean success = tDir.mkdir();
if(success) {
System.out.println("Dir created");
} else {
System.out.println("No dir created!");
}
Output:
experimentDir: /home/Documents/datasets/test-experiments
item.getName(): PosNegReviews
dirName: test
tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll
No dir created!
If you want to create multiple (nested) directories you should use mkdirs() (note the s).
you may be needing to create any parent directory that dont exist. try File.mkdirs().
public class Test1{
public static void main(String[] args)
{
String path="c:\\dir1\\dir2\\dir3\\dir4";
File dir=new File(path);
if(!dir.exists()){
dir.mkdirs();
}
}
}
above code will create dir4 inside C:\dir1\dir2\dir3. If parent folder does not exist, then it will also create.