kneedhelp
kneedhelp

Reputation: 685

Can you create a file on the system clipboard but not in a directory?

When a user clicks a button I would like to generate and add the file to the system clipboard. I have been able to do this, but when the file is added to the system clipboard, it also generates the file in the project folder (I'm using Eclipse). Can I make it directly on the system clipboard and not have it show up in a directory?

When I make a file, here is the code I use:

File file = new File("file.txt");

should "file.txt" be replaced with a path to the system clipboard? Or is that not possible?

Upvotes: 0

Views: 91

Answers (2)

STaefi
STaefi

Reputation: 4377

Do not create a file in the path of your project. You know that when you create file using the following statement:

File file = new File("file.txt");

It is being created near the class file of your code.

Just create a temp file using the createTempFile static method of class File :

try {
        File f = File.createTempFile("file", ".txt");
        FileWriter wr = new FileWriter(f);
        wr.write("This is a Test!");
        wr.close();
        // Add it to clipboard here 
    } catch (IOException e) {
        e.printStackTrace();
    }

Good Luck

Upvotes: 1

Smeeran
Smeeran

Reputation: 129

        StringSelection sel = new StringSelection(<insert string here>);
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        clip.setContents(sel, sel);

You can view this for string selection http://docs.oracle.com/javase/8/docs/api/java/awt/datatransfer/StringSelection.html

Upvotes: 2

Related Questions