0

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?

kneedhelp
  • 555
  • 4
  • 18

2 Answers2

2
        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

Smeeran
  • 129
  • 5
1

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

STaefi
  • 4,297
  • 1
  • 25
  • 43
  • I probably should have explained, I use a method to generate a file, and the method returns that file. If I use this approach will the return type generate a file? – kneedhelp Jan 29 '16 at 19:44
  • Yes it is a file. As you can see I stored it in a `File` variable. The only difference is it is temp file, and when your program ends, it will not be there. – STaefi Jan 29 '16 at 19:46
  • By the way, the second parameter should be ".txt" - without the dot, the file name is "file123456txt". – Klitos Kyriacou Jan 29 '16 at 19:47
  • @KlitosKyriacou: Thanks for the tip. Edited. – STaefi Jan 29 '16 at 19:48
  • 1
    Also, this creates a file in the TEMP directory - so it's still going to be on the disk. – Klitos Kyriacou Jan 29 '16 at 19:49