我想从剪贴板中获取数据并将其存储在.txt文件中。
如何创建.txt文件?我已经阅读了很多关于从文件中获取数据但不是相反的方法。
这是我的代码:
public void CallClipboard (){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard();
System.out.println(grabbed);
}
public String ReadClipboard () {
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
答案 0 :(得分:2)
我已经使用当前代码thanx解决了它的提示
public static void CallClipboard (String file){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard(file);
System.out.println(grabbed);
}
public static String ReadClipboard (String file) {
File testFile = new File(file);
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
try {
setContents(testFile, returnText);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
}
答案 1 :(得分:1)
请查看FileWriter和BufferedWriter,将字符串写入文件。