正在尝试用指定的扩展名复制指定路径中的文件,并用新的扩展名替换它们



我已经记下了大部分内容,但当我尝试复制时,没有复制。它会像应该做的那样在指定的目录中找到文件,我认为复制函数会执行,但指定的目录下没有更多的文件。感谢您的帮助。我做了一个printf函数,这里没有显示。谢谢

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Stuff {
static String path, oldExtn, newExtn;
static Boolean delOrig = false;
private static void getPathStuff() {
    printf("Please enter the desired pathn");
    Scanner in = new Scanner(System.in);
    path = in.next();
    printf("Now enter the file extension to replacen");
    oldExtn = in.next();
    printf("Now enter the file extension to replace withn");
    newExtn = in.next();
    in.close();
}
public static void main(String[] args) {
    getPathStuff();
    File folder = new File(path);
    printf("folder = %sn", folder.getPath());
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.getName().endsWith(oldExtn)) {
            printf(fileEntry.getName() + "n");
            File newFile = new File(FilenameUtils.getBaseName(fileEntry
                    .getName() + newExtn));
            try {
                printf("fileEntry = %sn", fileEntry.toPath().toString());
                Files.copy(fileEntry.toPath(), newFile.toPath(),
                        REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.printf("Exception");
            }
        }
    }
}

}`

问题是创建的新文件没有完整路径(只有文件名)。所以你的新文件创建的-只是不是你期望的地方。。。

你可以看到,如果你更换,它会起作用

File newFile = new File(FilenameUtils.getBaseName(fileEntry
                    .getName() + newExtn));

带有:

File newFile = new File(fileEntry.getAbsolutePath()
       .substring(0,
                  fileEntry.getAbsolutePath()
                           .lastIndexOf(".")+1) + newExtn);

最新更新