Dhruv Patil
Dhruv Patil

Reputation: 184

How to get absolute path of a file in clipboard in JAVA and get the location where it is pasted

I am fairly newbie to java. How can i get File Path i copied in clipboard and also get the location where it is pasted. So there will be two strings one

I don't want it in real time, but a way by which it can detect my click?

Upvotes: 1

Views: 995

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

After little investigation, I have found, that in general you cannot get an absolute path of the source file from Clipboard.

When you select a small file and copy it; clipboard contains file content and all you can to do is just read from clipboard as InputStream. In this situation, you cannot get a path of source file.

When you select a big file (I've tried it with a 17Gb mkv), then clipboard contains path to this file. In this case you can read clipboard and get a file path instead of it content. Once again, it depend on the file size and I do not know at what file size Windows stops copying file content and start put file path to clipboard.

Below a code snippet, when I get a Clipboard instance and detect two possible situations when it is possible to get source file path: when clipboard contains either plaint string or list of strings.

public static void main(String... args) throws IOException, UnsupportedFlavorException {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    String path = readAsString(clipboard);
    path = path == null ? readAsFileList(clipboard) : path;
}

private static String readAsFileList(Clipboard clipboard) {
    try {
        List<String> paths = (List<String>)clipboard.getData(DataFlavor.javaFileListFlavor);
        return paths.isEmpty() ? null : paths.iterator().next();
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}

private static String readAsString(Clipboard clipboard) {
    try {
        return (String)clipboard.getData(DataFlavor.stringFlavor);
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}

Upvotes: 1

Related Questions