java和剪切板 实现多层目录的复制和删除

关于剪切板上一节已讲过,这节重点介绍文件的操作。


public class FileOperUtils {
    private static final String     FILE_COPY = "copy";
    private static final String FILE_CUT = "cut";
    private Clipboard clipboard = Toolkit.getDefaultToolkit()
            .getSystemClipboard();
    private List<MyFile> dir = new ArrayList<FileOperUtils.MyFile>();
    private String copyFilename;
    private static String  oper = "";
    // private List<String> paths = new ArrayList<String>();

    public FileOperUtils() {
        super();
    }

    /*
     * 文件的复制
     */
    public void fileCopy(String m_copyDir) {
        Transferable dir = new StringSelection(m_copyDir);
        clipboard.setContents(dir, null);
        oper = this.FILE_COPY;
    }

    /*
     * 文件的剪切
     */
    public void fileCut(String m_cutDir) {
        Transferable dir = new StringSelection(m_cutDir);
        clipboard.setContents(dir, null);
        oper = this.FILE_CUT;
        //deleteFileOrdirectory(m_cutDir);
    }

    /*
     * 文件的粘贴
     */
    public void filePaste(String to_pasteDir) {
        try {
            String path = this.getPathFromClipboard(clipboard);
            copyFilename = path.substring(path.lastIndexOf("/"), path.length());
            System.out.println("copyFilename     " + copyFilename);
            File file = new File(path);
            if (file != null && file.exists()) {
                if (file.isDirectory()) {
                    findAllFilePaths(file);
                    pasteDirToDir(file.getAbsolutePath(), to_pasteDir);
                } else {
                    pasteFileToDir(path, to_pasteDir);
                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    /*
     * 从剪切板获得路径
     */
    private String getPathFromClipboard(Clipboard clip) throws Exception,
            IOException {
        Transferable mclip = clip.getContents(null);
        if (mclip != null) {
            return (String) mclip.getTransferData(DataFlavor.stringFlavor);
        }
        return null;
    }

    /*
     * 将整个文件夹复制到指定路径下
     */
    private void pasteDirToDir(String dirPath, String to_pasteDir) {
        for (int i = dir.size()-1; i >=0; i--) {
            MyFile myfile = dir.get(i);
            String newpath  = to_pasteDir+myfile.path.substring(dir.get(0).path.length(),myfile.path.length());
            File file = new File(newpath);
            if (!file.exists()) {
                file.mkdir();
            }
            for (int j = 0; j < myfile.subFilePath.size(); j++) {
                String str_path = myfile.subFilePath.get(j);
                System.out.println(str_path+"--------------");
                pasteFileToDir(str_path, to_pasteDir);
            }
            if (this.FILE_CUT.equals(oper)) {
                File  mf = new File(dir.get(i).path);
                if (mf.isDirectory()) {
                    mf.delete();
                }
            }
        }
    }

    /*
     * 把文件复制到制定的路径
     */
    private void pasteFileToDir(String fromPath, String toPath) {
        int byteread = 0;
        File newFile = new File(toPath);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        File oldfile = new File(fromPath);
        String ss = toPath+fromPath.substring(dir.get(0).path.lastIndexOf("/"),fromPath.length());
        File c_file= new File(ss.substring(0,ss.lastIndexOf("/")));
        if (!c_file.exists()) {
            c_file.mkdirs();
        }
        System.out.println(ss+"======");
        if (oldfile.exists()) {
            InputStream is;
            try {
                is = new FileInputStream(oldfile);
                FileOutputStream fs = new FileOutputStream(new File(ss));
                byte[] buffer = new byte[2048];
                while ((byteread = is.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                is.close();
                if (this.FILE_CUT.equals(oper)) {
                    oldfile.delete();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /*
     * 找出当前文件夹下所有文件的路径,
     */
    private void findAllFilePaths(File m_file) {
        if (m_file != null) {
            MyFile myfile = new MyFile();
            myfile.path = m_file.getAbsolutePath();
            dir.add(myfile);
            File[] files = m_file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File newfile = files[i];
                if (newfile.isFile()) {
                    myfile.subFilePath.add(newfile.getAbsolutePath());
                } else if (newfile.isDirectory()) {
                    findAllFilePaths(newfile);
                }
            }
        }
    }

    /*
     * 删除指定路径下的文件
     */
    private void deleteFileOrdirectory(String dir) {
        File file = new File(dir);
        if (file.isFile() && file.exists()) {
            file.delete();
        } else if (file.isDirectory() && file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file_s = files[i];
                deleteFileOrdirectory(file_s.getAbsolutePath());
            }
        }
    }

    class MyFile {
        private String path;
        private List<String> subFilePath = new ArrayList<String>();

        public MyFile() {
            super();
        }

        public MyFile(String path, List<String> subFilePath) {
            super();
            this.path = path;
            this.subFilePath = subFilePath;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public List<String> getSubFilePath() {
            return subFilePath;
        }

        public void setSubFilePath(List<String> subFilePath) {
            this.subFilePath = subFilePath;
        }

    }
}


测试类:

public class FileTest {
    static String p = "/home/wangjia/test/test1/wj";
    static String path = "/home/wangjia/test";
    static String todir = "/home/wangjia/test1";
    static String dir = "/home/wangjia/qq";
    public static void main(String[] args) {
    //    System.out.println(path.substring(path.lastIndexOf("/"),path.length()));
        //System.out.println(path.indexOf(p.length()));
    //    System.out.println(path.substring(p.length(),path.length()));
        //System.out.println(dir+ path.substring(path.indexOf("/test1"), path.length()));

        FileOperUtils utils = new FileOperUtils();
        //utils.fileCopy(todir);
        utils.fileCut(todir);
        utils.filePaste(path);
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现截图功能并复制剪切板可以分为以下几个步骤: 1. 获取屏幕的宽度和高度 可以使用Toolkit类的getScreenSize方法获取屏幕的宽度和高度: ```java Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = screenSize.width; int height = screenSize.height; ``` 2. 创建一个Robot对象 可以使用Robot类来实现屏幕截图,需要创建一个Robot对象: ```java Robot robot = new Robot(); ``` 3. 截取屏幕图像 可以使用Robot类的createScreenCapture方法和Rectangle类来截取屏幕图像: ```java Rectangle screenRect = new Rectangle(0, 0, width, height); BufferedImage image = robot.createScreenCapture(screenRect); ``` 4. 复制图像到剪贴板 可以使用Toolkit类的getDefaultToolkit方法获取系统剪切板,并创建一个ImageSelection对象: ```java ImageSelection selection = new ImageSelection(image); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); ``` 完整的实现代码如下: ```java import java.awt.*; import java.awt.datatransfer.*; import java.awt.image.BufferedImage; import java.io.IOException; public class Screenshot { public static void main(String[] args) { try { // 获取屏幕的宽度和高度 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = screenSize.width; int height = screenSize.height; // 创建一个Robot对象 Robot robot = new Robot(); // 截取屏幕图像 Rectangle screenRect = new Rectangle(0, 0, width, height); BufferedImage image = robot.createScreenCapture(screenRect); // 复制图像到剪贴板 ImageSelection selection = new ImageSelection(image); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); System.out.println("屏幕截图已复制剪切板。"); } catch (AWTException e) { e.printStackTrace(); } } static class ImageSelection implements Transferable { private Image image; public ImageSelection(Image image) { this.image = image; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(DataFlavor.imageFlavor) && image != null) { return image; } throw new UnsupportedFlavorException(flavor); } public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{DataFlavor.imageFlavor}; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(DataFlavor.imageFlavor); } } } ``` 运行程序后,程序会将屏幕截图复制剪切板中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值