我发现,Java无法使用Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), owner)
等功能将非常大的内容保存到系统剪贴板。最大尺寸的确切值取决于计算机。对于Windows PC的示例,它大约为20 MB。
我的想法是将大内容存储到文件中。 Transferable对象本身应该只管理临时文件名和其他元数据。
我正在为此任务搜索工作示例代码。
我的示例代码很少。它仅显示如何执行"复制操作"。在开始示例之后,用户可以使用"粘贴"在某些应用中。 UTF-8编码的文件内容" bigfile.txt"被粘贴到应用程序中。
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class SimpleClipboardWithFile extends JDialog
implements ClipboardOwner
{
public SimpleClipboardWithFile(Frame parent, boolean modal)
{
super(parent, modal);
initComponents();
DataFlavor df = new DataFlavor("text/plain; class=java.io.InputStream; "
+ "charset=UTF-8", "text/plain");
Clipboard clipboard = Toolkit.getDefaultToolkit().
getSystemClipboard();
Transferable trans = new Transferable() {
@Override
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[]{df};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return df.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
Clipboard clipboard = Toolkit.getDefaultToolkit().
getSystemClipboard();
Transferable contents = clipboard.getContents(this);
// TODO: take filename from Transferable object
FileInputStream input = new FileInputStream("bigfile.txt");
return input;
}
};
clipboard.setContents(trans, this);
}
private void initComponents()
{
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Do \"paste\" in an application");
pack();
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable() {
public void run() {
SimpleClipboardWithFile dialog = new SimpleClipboardWithFile(new JFrame(), true);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents)
{
//
}
}