0

I need to move all files ending with .txt to the archive folder.

I have the below code, but the if (sourcepath.endsWith(".txt")) doesn't validate the file extension.

      File directory = new File("Archive");
      System.out.println((System.getProperty("user.dir")));
      File directory1 = new File (System.getProperty("user.dir"));
      File[] files = directory1.listFiles();
      if (! directory.exists()) {
            directory.mkdir();
            for(File f : files ) {
                   Path sourcePath = Paths.get(f.getName());
                   System.out.println(sourcePath);
                   if (sourcePath.endsWith(".txt")){   // Not validating
                       System.out.println(sourcePath.endsWith(extension));
                       Files.move(sourcePath, Paths.get("Archive"));
                   }
            }
            System.out.println("Clearing Folder.....All Files moved to Archive Directory");
      }

Expected Output:

C:\Users\harsshah\workspace\FFPreBatchValidation
.classpath
.project
.settings
bin
kjnk.txt
src

kjnk.txt should be moved to Archive folder

JustAFellowCoder
  • 300
  • 2
  • 11
  • What's the name of the files in your folder ? – Maxouille Mar 25 '19 at 14:28
  • 1
    Did you have a look at the Javadoc on Path.endsWith(String)? I'll quote: `On UNIX for example, the path"foo/bar" ends with "foo/bar" and "bar". It does not end with "r" or "/bar"` - thus `whatever.txt` won't "end with" `.txt`. – Thomas Mar 25 '19 at 14:28

2 Answers2

6

Here is the doc about Path.endsWith(String)

Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method. On UNIX for example, the path "foo/bar" ends with "foo/bar" and "bar". It does not end with "r" or "/bar". Note that trailing separators are not taken into account, and so invoking this method on the Path"foo/bar" with the String "bar/" returns true.

The important part is : It does not end with "r" or "/bar"

You must convert the Path to a String and call String.endsWith(String) instead of Path.endsWith(String)

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
0

You can use this:

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

Assuming that you're dealing with simple Windows-like file names, not something like archive.tar.gz.

Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file), you can do

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));

if (i > p) {
    extension = fileName.substring(i+1);
}
Julian Solarte
  • 555
  • 6
  • 29