CNK 2
CNK 2

Reputation: 11

File scan and file move in java

I'm trying to make a program in java that scans each file and then if it ends with a certain extension ( for example .class) moves it in a different folder. I have a certain error that bothers me for a week now. Any help would be appreciated :)

import java.io.*; 
import java.nio.file.Files; 
import java.nio.file.*;
import java.io.File; 



public class file_transfer_alpha_build { 
    public static void main(String[] args) throws IOException {

      File baseDir = new File("C:/Users/gp/Desktop/Java") ;
      File destDir = new File("C:/Users/gp/Desktop/Java/test") ;

      File[] files = baseDir.listFiles();
      for (int i=0; i<files.length; i++){
        if (files[i].endsWith(".class")){
            files[i].renameTo(new File(destDir, files[i].getName()));
        }
      }

    }
} 

The error :

file_transfer_alpha_build.java:14: error: cannot find symbol
        if (files[i].endsWith(".class")){
                    ^
  symbol:   method endsWith(String)
  location: class File
1 error

Upvotes: 1

Views: 72

Answers (1)

Amongalen
Amongalen

Reputation: 3131

The error tells you exactly what is wrong with the code. There is no endsWith() method in the File class. You need to use getName there to get the file's name:

if (files[i].getName().endsWith(".class")){
    files[i].renameTo(new File(destDir, files[i].getName()));
}

Upvotes: 5

Related Questions