I am trying to save contents in file but first I want to search either file does exist or not. But the code I have written, every time it is returning true.
String fileName=FNameTextField.getText();
File file=new File(fileName);
if(file.exists()&& !file.isDirectory()) {
// It returns true if File or directory does exist
System.out.println("the file or directory you are searching does exist : " );
}else{
// It returns true if File or directory not exists
System.out.println("the file or directory you are searching does not exist : " );
}
Thanks.
Your logic seems to be all screwy, or at least I can't make heads or tails of it
if (file.exists()) {
if (file.isDirectory) {
System.out.println("Directory already exists");
} else {
System.out.println("File exists");
}
} else {
System.out.println("Could not find a file or directory matching your request");
}
Try using method...
file.isFile()
The javadoc says
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
Your logic checks if to see only if it is a file. It will NOT return true if a directory with the name exists as you imply in your print statements.
Make use of this examples which is adopt for you :
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
(or)
import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}
(or)
import java.io.*;
public class FileOrDirectoryExists{
public static void main(String args[]){
File file=new File("Any file name or
directory whether exists or not");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
System.out.println("the file or directory
you are searching does not exist : " + exists);
}else{
// It returns true if File or directory exists
System.out.println("the file or
directory you are searching does exist : " + exists);
}
}
}
1. First get all the files in the folder, and store it in an ArrayList.
Eg:
File f = new File("d:\\MyFolder);
File[] fArr = f.listFiles();
ArrayList<File> fList = new ArrayList<File>();
for ( File file : fArr){
if (file.isFile()){
fList.add(file);
}else{
continue;
}
}
2. Now use getName() method to check the file exists or not....
Assume you are looking for a file named "vivek.txt"
Eg:
boolean b = false;
for (File i : fList){
if ((i.getName).equals("vivek.txt")){
b = true;
break;
}
else{
continue;
}
}
Related
I'm writing a quick Java recursion method that, given a root folder and filename, searches your files for said file name.
import Java.io.File;
public static String searchForFile(File currentFolder, String filename)
{
try
{
File[] path = currentFolder.listFiles();
for (int i = 0; i < path.length; i++)
{
if (path[i].isDirectory())
{
System.out.println("Directory: " + path[i].toString());
searchForFile(path[i], filename);
}
else
{
System.out.println("File: " + path[i].toString());
if(path[i].getName().equals(filename))
{
System.out.println("Your file has been found!";
return path[i].toString();
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null; // Omitting this line yields compiling errors, not sure why?
}
public static void main(String[] args)
{
System.out.println("Hello, enter the root folder and file name.");
String rootFolder = "Desktop";
String fileName = "Hello.txt";
File f = new File("C:\\Users\\Me\\" + rootFolder);
searchForFile(f, fileName);
}
The program itself technically works, however searchForFile() keeps iterating even after the requested file is found. For example, I'd get an output such as:
File: C:\Users\Me\Desktop\My Stuff\NotHello.txt
**File: C:\Users\Me\Desktop\My Stuff\Hello.txt**
Your file has been found!
File: C:\Users\Me\Desktop\My Stuff\AlsoNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\StillNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\WhyIsThisMethodStillRunning.txt
I've been scratching my head at this for awhile now. I thought return always exits the method, so why does the recursion continue even after it returns a value? I haven't found any similar questions asked, so any help would be much appreciated!
(Also, how could I edit the method so that it returns a blank "" string if the requested file is not found?)
You are returning from the innermost call, when you've found the file. But when you are scanning a directory, you are not using the return value.
Change this:
searchForFile(path[i], filename);
to:
String result = searchForFile(path[i], filename);
if (result != null) {
return result;
}
The return null; in the bottom of your method is there because all methods needs to return a value. No matter if the file is found or not. If the file is not found within the current directory (or one of its subdirectories), you can return null; to indicate that it wasn't found.
Side suggestion: Use Optional in Java 8 instead of null.
I am programming a basic notepad program and I want it to be able to rename files from the command line. If the user writes "rename" to scanner, the program changes the note's file name according to input, like -rename stack. But if user enter two new note names. Program will error like Invalid note name for renaming. It contains ' '. Enter one word.. If a proposed name is used by an existing file, the program will print File already exists.
How can i do this:
-rename stack
Enter new note name?
stack over
Invalid note name for renaming. It contains 'over'. Enter one word
-rename stack
Enter new note name?
over
File already exists
This is what I've written so far:
...
else if (noteNameSplited[0].equals("rename")) {
File file = new File(noteNameSplited[1]+".ncat");
if(!file.exists()) {
System.out.println("File does not exist !");
}
else {
System.out.println("Enter the new note name");
String data=scan.nextLine();
File file2 = new File(data+".ncat");
file.renameTo(file2);
}
}
This may help you:
https://github.com/openstreetmap/osmosis/blob/master/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/util/AtomicFileCreator.java#L50
if (!tmpFile.exists()) {
throw new OsmosisRuntimeException("Can't rename non-existent file " + tmpFile + ".");
}
// Delete the existing file if it exists.
if (file.exists()) {
if (!file.delete()) {
throw new OsmosisRuntimeException("Unable to delete file " + file + ".");
}
}
// Rename the new file to the existing file.
if (!tmpFile.renameTo(file)) {
throw new OsmosisRuntimeException(
"Unable to rename file " + tmpFile + " to " + file + ".");
}
You can try the following:
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
return fs.rename(this, dest);
}
I am trying to output a list of files within a directory recursively (not including the name of the name of the directory that I am starting with (just the contents of it and all files recursing down the tree after that)
here is what I have at the minute. It Might have errors here and there, but the idea is that it will print all the names of every file in the tree recursively. My problem is that I don't want it to print the name of the directory in which they live.
I think my problem is that I am using System.out.println at the start of the recursive method, which means it gets used every time. Which is desirable behavior for every directory BELOW the first one. Its an annoying little problem that I could use some help on. Thanks in advance.
public static void listFiles(String path)
{
File basedir = new File(path);
System.out.println(path.getName());
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath());
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
public static void listFiles(String path, boolean firstCall)
{
File basedir = new File(path);
if(!firstCall)
{
System.out.println(path.getName());
}
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath(), false); //false here because it is not the first call
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Add a boolean parameter that specifies if it is the first call. When you call the method pass true to the parameter. Also path.getName() is not valid String doesn't have a function getName() maybe you meant basedir.getName()...also remove try catch block IOException can't occur there.
I want to delete file located in local machine, comparing to server machine.
My example :
import java.io.*;
public static void main(String[] args) throws Exception {
Set<String > lmd5 = new HashSet<String>();
lmd5.add("4be1babb2f8cac64d96f8052c0942130");
lmd5.add("a7514d56f233a434c7066176933d708d");
lmd5.add("d41d8cd98f00b204e9800998ecf8427e");
lmd5.add("674e3b94be9ed5db8bafe75808385de1");
Set<String > dmd5 = new HashSet<String>();
dmd5.add("4be1babb2f8cac64d96f8052c0942130");
dmd5.add("a7514d56f233a434c7066176933d708d");
dmd5.add("d41d8cd98f00b204e9800998ecf8427e");
if(lmd5.equals(dmd5)){
System.out.println("OK");
}
else{
lmd5.removeAll(dmd5);
System.out.println("Obsoletes Files To Delete : " + lmd5);
File[] paths = baseModDirectoryFile.listFiles();
for(File path:paths){
FileInputStream fis = new FileInputStream(path);
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
if(lmd5.contains(md5) ){
File foundFile = path;
System.out.println("Obsolete File Found !");
try{
if(foundFile.delete()){
System.out.println("Obsolete File Deleted !");
}
else{
System.out.println("Obsolete File Not Deleted : Error !");
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
continue;
}
}
}
}
In my output console, I have the message "Obsoletes Files Found" which appears, but after that I have the message : "Obsolete File Not Deleted". I believe I arrive too late in the function to delete the file, as all files have already been checked.
Maybe I have to review this position but I would like to get some advise.
Thank you !
What is the value of foundFile.delete()?
Do you have enough permission to delete file?
May be your file is being locked by your FileInputStream?
I have this section of code:
public static void delete(File f) throws IOException
{
if (f.isDirectory())
{
for (File c : f.listFiles())
{
delete(c);
}
}
else if (!f.delete())
{
throw new FileNotFoundException("Failed to delete file: " + f);
}
}
public static void traverseDelete(File directory) throws FileNotFoundException, InterruptedException
{
//Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
if (file.getName().equalsIgnoreCase("word"))
{
boolean containsMedia = false;
File[] filesInWordFolder = file.listFiles();
for ( File file2 : filesInWordFolder )
{
if ( file2.getName().contains("media"))
{
containsMedia = true;
break;
}
}
if (containsMedia == false)
{
try
{
delete(file.getParentFile());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else if (file.isDirectory())
{
traverseDelete(file);
}
}
}
Sorry for the lack of commenting, but it's pretty self-explanatory, I think. Essentially what the code is supposed to do is traverses a set of files in a given directory, if it encounters a directory named "word", then it should list out the contents of word, and then if a directory called "media" does NOT exist, recursively delete everything within the parent directory of "word" down.
My main concern comes from this conditional:
if(!filesInWordFolder.toString().contains("media"))
Is that the correct way to say if the files in that array does not contain an instance of "image", go ahead and delete?
That won't work.
File[] filesInWordFolder = file.listFiles();
if(!filesInWordFolder.toString().contains("media"))
will give you a string representation of a File array -- which will typically have a reference.
You have to iterate through the files to find out if there's any in there that contain the word media.
boolean containsMedia = false;
for ( File file : filesInWordFolder ) {
if ( file.getName().contains("media") ){
containsMedia = true;
break;
}
// now check your boolean
if ( !containsMedia ) {
Well using toString() will give you a String representation of the file (in this case the files). The String representation should contain the file name. If your set purpose is to check for any instance of a file containing the word "media" in the directory, you are fine.
In the example you are printing the String representation of the File array. Instead you should iterate through the File array and check the String representation of each individual File as so:
for (int i = 0; i < file_array.length; i++) {
if ((File)file_array[i]).toString().equals("your_search_term")) {
// The file contains your search term
} else {
// Doesn't contain the search term.
}
}