Runtime.getRuntime()。exec无法使用xclip

时间:2014-11-17 03:03:44

标签: java shell

当我在终端中使用xclip如下并点击ctrl + shift + v时,cliboard将写入当前日期,我得到以下

roroco@roroco ~/Dropbox/jvs/ro-idea $ echo -n $(date)|xclip -selection clipboard
roroco@roroco ~/Dropbox/jvs/ro-idea $ Mon Nov 17 10:54:21 HKT 2014

但是当我尝试使用代码时:

class Ex {
    public static void main(String[] args) {
        try {
            Runtime.getRuntime().exec("echo -n $(date)|xclip -selection clipboard");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

剪贴板未更改,**我的问题是**如何让 Runtime.getRuntime().exec像终端一样工作

我也试试java剪贴板:

package ro.ex;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

public class Ex {

    public static void main(String[] args) {
        String myString = "This text will be copied into clipboard when running this code!";
        StringSelection stringSelection = new StringSelection(myString);
        Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
        clpbrd.setContents(stringSelection, null);
    }
}

它也不起作用

这是我的操作系统:

No LSB modules are available.
Distributor ID: LinuxMint
Description:    Linux Mint 17 Qiana
Release:    17
Codename:   qiana

更新以下代码工作(只需添加System.in.read())但它必须保持java进程运行

package ro.ex;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;

/**
 * Created by roroco on 11/17/14.
 */
public class Ex2 {
    public static void main(String[] args) throws IOException {
        String myString = "This text will be copied into clipboard when running this code!";
        StringSelection stringSelection = new StringSelection(myString);
        Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
        clpbrd.setContents(stringSelection, stringSelection);
        System.in.read();
    }
}

更新最简单的方法是,将内容保存到tmp文件,并使用xclip来读取它

public class Util {
    public static void toClip(Object o) {
        String f = "/tmp/clipboard";
        File.write(f, o.toString());
        bash("xclip -selection clipboard", f);
    }
}

0 个答案:

没有答案