java - 添加文件夹中的文件列表

标签 java

我正在开发一个应用程序,我需要将所有文件保存在每个用户的目录中。写了一半,但不知道如何向目录添加文件。

public boolean addFiles(String name,List<File> files){
    String path = "D:\\Server Repository\\UsersFiles\\";
    File folder = new File(path + name);

    if(!folder.exists()) 
          folder.mkdirs();

    for(File file:files){
        //my code 
        //if all ended with success return true
    }
    return false;
}

最佳答案

如果您不需要像 FileUtils 这样的第三方库,而只想要一个简单的代码来复制文件,您可以这样做:

public boolean addFiles(String name, List<File> files) {
    String path = "D:\\Server Repository\\UsersFiles\\";
    File folder = new File(path + name);

    if (!folder.exists()) {
        folder.mkdirs();
    }

    try {
        for (File file : files) {
            FileInputStream fisOrigin;
            FileOutputStream fosDestiny;
            //channels  
            FileChannel fcOrigin;
            FileChannel fcDestiny;

            fisOrigin = new FileInputStream(file);
            fosDestiny = new FileOutputStream(new File(folder.getAbsolutePath() + "/" + file.getName()));

            fcOrigin = fisOrigin.getChannel();
            fcDestiny = fosDestiny.getChannel();
            //Copy the file
            fcOrigin.transferTo(0, fcOrigin.size(), fcDestiny);

            fisOrigin.close();
            fosDestiny.close();
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

关于java - 添加文件夹中的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663055/

相关文章:

java - 如何获取Processing中草图的路径? (数据路径不起作用)

javascript - Jbutton(ActionListener)可以启动静态方法吗?

java - htmlunit knockout js 不起作用。单击提交按钮返回同一页面

java - 设置启动器而不离开当前 Activity

java - ConcurrentHashMap 锁增加

Java:将数字分成相等的部分或彼此近似

java - 在 netty 4.1 中如何在没有 channel 的情况下新建一个 promise

java - 在我的数组中找到的 URL 中使用 JSON 数据

java - 如何在 Eclipse 中快速实现/覆盖方法?

java - Android 设备之间的 wifi 文件传输速度更快?