0

I want to do what is asked here:How to open a file without saving it to disk but with text.

I understand that is not possible opening a file without saving it somewhere on the disk, as a temporary file maybe.

I would like to ask if another approach is possible.

The other approach: 1. create the String, 2.Copy that to clipboard, 3. Open the text editor, 4. Paste the String into the editor.

Steps 1,2,3 are ok. Can step 4 be done?

A thought: In windows one could maybe run a bat file from the java application that will do the paste into notepad. But I would prefer something done only with java, and platform independent.

Community
  • 1
  • 1
geo
  • 517
  • 1
  • 9
  • 28
  • I don't understand your point. I asked if step 4 is possible. Not 1,2,3. What do you mean with that "other do my job" you say? – geo Sep 15 '14 at 18:05
  • It is possible (would only work on WIN32) if you make calls to Win32 API's from Java. Something that can help with that is JNA. See this [link](http://en.wikipedia.org/wiki/Java_Native_Access) . However once you have JNA it is non-trivial to do the paste, but you sure can do it. It is non-trivial because you need to understand how to send messages to other applications to mimic paste. – Michael Petch Sep 15 '14 at 18:06
  • Did you consider [this answer](http://stackoverflow.com/a/12964272/1392132) to the question you have linked to? If so, why did you rule it out? – 5gon12eder Sep 15 '14 at 18:08
  • Sorry he did ask for platform independent. My bad. It would likely have to be platform dependent to implement item 4 as a paste operation. – Michael Petch Sep 15 '14 at 18:11
  • [in reply to deleted comment of @geo] At least on my GNU/Linux + LXDE box with Leafpad as the text editor, this is exactly what happens. Note that the suggestion is not to *save* the data to disk put rather feed it to the editor process via it's standard input stream. The editor will therefore know that the file is not persisted on disk and prompt the user for saving it on exit. – 5gon12eder Sep 15 '14 at 18:21

1 Answers1

0

Step 4 can be done. One way would be to use Robot and mimic a CTRL+V command as shown below:

        Robot robot = new Robot();

        // For platform independence:
        int ctrlOrCmdKey = -1;
        if(System.getProperty("os.name").toLowerCase().contains("mac")) {
            ctrlOrCmdKey = KeyEvent.VK_META;
        } else {
            ctrlOrCmdKey = KeyEvent.CTRL_MASK;
        }

        robot.keyPress(ctrlOrCmdKey);
        Thread.sleep(10);
        robot.keyPress(KeyEvent.VK_V);
        Thread.sleep(10);
        robot.keyRelease(KeyEvent.VK_V);
        Thread.sleep(10);
        robot.keyRelease(KeyEvent.CTRL_MASK);

If you're trying to send data to another application that you're creating, you could also use PipedInputStream / PipedOutputStream or use the IP protocol by using local-host web-sockets (which is not as clean, but possible).

Roland
  • 612
  • 5
  • 17