I am trying to remove a file in java, but it will not remove. Could someone explain why it won't remove?
Here is the code that I am using:
File bellFile = new File("config\\normbells.txt");
bellFile.delete();
File bellFileNew = new File("config\\normbells.txt");
bellFileNew.createNewFile();
System.out.println("Done!");
NOTE: I am trying to wipe the file, if that helps.
File deletion can fail under the following circumstances:
The file does not exist.
The file is a directory not a file.
You don't have access to delete the file.
You don't have access to the the file or any of its parent directory.
The file is being used currently by some another application.
Try avoiding all the above mentioned circumstances & you'll surely able to delete the file.
Also before deleting the file add this condition :
if (file.exists()) {
file.delete();
}
Java7 has new functionality for this.
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.delete(target);
Path newtarget = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
= PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
Files.createFile(newtarget, attr);
Take a look at the File class http://docs.oracle.com/javase/7/docs/api/java/io/File.html
File bellFile = new File("config\\normbells.txt");
if(bellFile.delete())
{
System.out.println("Done!");
}
Related
Program should check if the directory is exist?? And if not, tell the user that there is no such folder.
I found many examples in which is explained how to check whether there is a file, but I need to know whether there is a directory? All methods
boolean x = context.getExternalFilesDir("/nicknameOfUser/").exists();
Toast.makeText(context, "ExternalFilesDir : " + x, Toast.LENGTH_SHORT).show();
isAbsolute(), isDirectory(), isFile(), create a new path to the files folder - nicknameOfUser I do not want to they were created, I just need to receive there is a directory or not ... I don't need create new folders...
How to do it? I think it is a question from regular, but I can't understand ...
When i launch app first time - in my filemanager no any file! But after i check .exists(); it create a path to the folder that i need a check... I DON'T NEED IT
To check if there is directory you have to use two conditions
File file = new File(filePath);
boolean isPresent = file.exists() && file.isDirectory();
returns true only if file exists and is directory.
You can ask for isDirectory() as follows :
File f = new File(Environment.getExternalStorageDirectory()+"/nicknameOfUser/");
if(f.isDirectory()) {
}
File file = new File("your path");
file.exists();
But after i check .exists(); it create a path to the folder that i need a check... I DON'T NEED IT
The problem is not the File.exists() call. It is the getExternalFilesDir call that is creating the directory. As the documentation states:
Unlike Environment.getExternalStoragePublicDirectory(), the directory returned here will be automatically created for you.
Eventually i found a solution. I begin to think it is impossible but all is ok
String fileDir = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/nicknameOfUser/";
File file = new File(fileDir);
boolean x = file.exists();
This code work properly
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I want to check for the given folder path(local path,shared path) and credentials for the folder, whether user has access to this folder.
In windows, we can verify that by manually by right click on that folder and go to security tab.
I read some posts, but most of them are suggesting to create a file in that folder and then delete it to verify it. I am restricted to do that in my requirement.
please help me if we can do that it in java
Create a new file with the given path:
File testFile = new File("path");
If canRead:
if(file.canRead()) {
// do something
}
For a complete list of what you can do with java.io.File, please visit the API (you can try/catch to delete, write, etc):
http://docs.oracle.com/javase/6/docs/api/java/io/File.html
The File class has several useful methods to achieve what you want:
File file = new File("path-to-file");
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getParent());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isHidden());
For more info, try using the official docs: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
EDIT
As per OP's comment, here's a way to check a file's owner and the file's permissions:
Path path = FileSystems.getDefault().getPath("path");
UserPrincipal owner = null;
Set<PosixFilePermission> posixFilePermissions = null;
try {
owner = Files.getOwner(path);
posixFilePermissions = Files.getPosixFilePermissions(path);
} catch (IOException ex) {
Logger.getLogger(TestCenter.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(owner);
System.out.println(posixFilePermissions);
Output (the file has 664 permission on my Linux machine):
victor
[OWNER_WRITE, OWNER_READ, OTHERS_READ, GROUP_WRITE, GROUP_READ]
I am stuck up in a odd situation that is I am creating a file in a folder but I need to make sure that before the creation of a file if any file is there in the folder then it must be deleted only the current file which is process should be there.
since in my application every day a job runs which create the file in that folder so when ever presently job is running it should delete previous day file and no file should be there in afolder but the code that is shown below creates the file in that folder but the issue is that previous day file or if the job run multiple time on the same day also then those files are also thhere in the folder which should be deleted please advise how to achieve this..
File file = new File(FilePath + s); //path is c:\\abc folder & s is file name fgty.dat file
if (file.exists()) {
file.delete();
}
file.createNewFile();
Please advise
In your place I'd move the directory to a different name, say abc.OLD, recreate it and then create your file. If everything goes well, at the end you can remove the ols directory.
If different instances of your program could be running at the same time you need to implement some form of synchronization. A rather simplistic approach could be to check if the abc.OLD directory exists and abort execution if it does.
Without seeing more of your code, it sounds like you just need to empty the folder before opening a new file, since right now you're only deleting the file with the exact name that you're going to write. Use the list method of file objects.
File newFile = new File(FilePath + s);
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
f.delete();
}
newFile.createNewFile();
Note that this won't work if your folder contains other non-empty directories; you'll need a more robust solution. But the code above will at least delete all the files in the folder (barring Exceptions obviously) before creating the new file.
If, as you mentioned in the comments, you only want to delete *.dat files, it's as simple as putting a check in before you delete anything.
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
if (f.getName().endsWith(".dat")) { // Only delete .dat files
f.delete();
}
}
File file = new File(FilePath+"test.txt");
File folder = new File(FilePath);
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
listOfFiles[i].delete();
}
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
First I think you can have problems with the way you instanciate your Fileobject because if you don't have your path separator (\), you will try to create c:\abcfgty.dat instead of c:\abc\fgty.dat.
Use instead :
File file = new File(filePath, s);
Then you can delete the files ending by ".dat". As I understood, you don't need to delete sub directories. (Here is a link that tells you how. See also here)
for (File f : filePath.list()) { // For each file in the directory, delete it.
if(f.isFile() && file.getName().toLowerCase().endsWith(".dat");){
f.delete();
}
}
try {
file.createNewFile();
} catch (IOException ex) {
//Please do something here, at leat ex.printStackTrace()
}
Note that we can use a FileFilter to select the files to delete.
EDIT
As it was suggested in other answers, it might be preferable to move or rename the existing files instead of deleting them directly.
I am creating files with Java in Windows. This works:
String newFile = "c:/"+Utilities.timeFormat();
...
some code that creates a folder
This does not work:
String newFile = "c:/newDirectory/"+Utilities.timeFormat();
...
some code that creates a folder
You have to use File.mkdir() or File.mkdirs() method to create a folder.
EDIT:
String path="c:/newDirectory";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + Utilities.timeFormat());
if(file.createNewFile())
{
}
without knowing your actual code which is creating the directory:
use mkdirs() instead of mkdir()
Can you check that you have permissions to create a folder in c:/?
Can you show us the stacktrace too?
If "newDirectory" doesn't exist yet, you should use the method mkdirs() from the File class to create all the directories in between.
The fact that the directory doesn't exist is probably why it isn't working he first time through. As many have pointed out use mkdirs() will ensure if the file you want to write is in subfolders it will create them. Now here is what it might look like:
File file = new File( new File("c:/newDirectory"), Utilities.timeFormat() );
if( !file.getParentFile().exists() ) {
file.getParentFile().mkdirs();
}
OutputStream stream = new BufferedOutputStream( new FileOutputStream( file ) );
try {
// put your code here to write the file
} finally {
stream.close();
}
Notice I'm not using + to create a path. Instead I create a File object, and pass it the parent File and the name of the file. Also notice I'm not putting path separators in between the parent and filename. Using the File constructor takes care of a system independent way of creating paths.