对我之前的问题的跟进 - Java:如何读取目录文件夹,计算和显示文件数量并复制到另一个文件夹?,我要读取一个文件夹,统计文件夹中的文件(任何文件类型),显示文件数量,然后将其复制到新文件夹。但是,我收到以下异常:
线程“主”java.io.FileNotFoundException 中的异常:C:\project\curFolder(访问被拒绝)C:\project\newFolder 已经存在:继续处理!在 java.io.FileInputStream.open(Native Method) 在 java.io.FileInputStream.(FileInputStream.java:120) 在 filetransfer.FileTransfer.copyFiles(FileTransfer.java:54) 在 filetransfer.FileTransfer.checkDir(FileTransfer.java: 44) 在 filetransfer.FileTransfer.readDirectory(FileTransfer.java:29) 在 filetransfer.FileTransfer.main(FileTransfer.java:12) Java 结果:1 BUILD SUCCESSFUL(总时间:0 秒)
请记住我是学生。这是我到目前为止所做的:
public class FileTransfer {
public static void main(String[] args) throws FileNotFoundException, IOException {
readDirectory();
}
public static void readDirectory() throws FileNotFoundException, IOException {
//create new file object with location of folder
File curFolder = new File("C:/project/curFolder/");
int totalFiles = 0;
//for loop to count the files in the directory using listfiles method
for (File file : curFolder.listFiles()) {
//determine if the file object is a file
if (file.isFile()) {
//count files ++
totalFiles++;
}
}
//display number of files in directory
System.out.println("Number of files: " + totalFiles);
checkDir();
}
public static void checkDir() throws FileNotFoundException, IOException {
//check if destination directory exist, if not create directory
//create new file object with copy folder destination
File newFolder = new File("C:/project/newFolder/");
//Check if folder exist: True: Println with message(true and continuing)
if (newFolder.exists()) {
System.out.println(newFolder + " already exist: Continuing with process!");
} else {
//False: Create Dir
newFolder.mkdir();
System.out.println(newFolder + " created!");
}
copyFiles();
}
public static void copyFiles() throws FileNotFoundException, IOException {
//copy files from specified directory to new directory
File fromCur = new File("C:/project/curFolder/");
File toNew = new File("C:/project/newFolder/");
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream(fromCur);
to = new FileOutputStream(toNew);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
} finally {
if (from != null) {
try {
from.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
if (to != null) {
try {
to.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}