當前位置:首頁 » 編程語言 » 粘貼Java

粘貼Java

發布時間: 2024-07-19 03:55:13

⑴ 在java中如何實現復制,粘貼,剪切

要用到java.awt.datatransfer包中的Clipboard類
import java.awt.*;import java.awt.event.*;
import java.awt.datatransfer.*;
public class Test extends Frame implements ActionListener
{ MenuBar menubar; Menu menu;
MenuItem ,cut,paste;
TextArea text1,text2;
Clipboard clipboard=null;
Test()
{ clipboard=getToolkit().getSystemClipboard();//獲取系統剪貼板。
menubar=new MenuBar();
menu=new Menu("Edit"); =new MenuItem("");
cut=new MenuItem ("cut"); paste=new MenuItem ("paste");
text1=new TextArea(20,20); text2=new TextArea(20,20);
.addActionListener(this); cut.addActionListener(this);
paste.addActionListener(this);
setLayout(new FlowLayout());
menubar.add(menu);
menu.add(); menu.add(cut); menu.add(paste);
setMenuBar(menubar);
add(text1);add(text2);
setBounds(100,100,200,250); setVisible(true);pack();
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);
}
}) ;
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==) //拷貝到剪貼板。
{ String temp=text1.getSelectedText(); //拖動滑鼠選取文本。
StringSelection text=new StringSelection(temp);
clipboard.setContents(text,null);
}
else if(e.getSource()==cut) //剪貼到剪貼板。
{ String temp=text1.getSelectedText(); //拖動滑鼠選取文本。
StringSelection text=new StringSelection(temp);
clipboard.setContents(text,null);
int start=text1.getSelectionStart();
int end =text1.getSelectionEnd();
text1.replaceRange("",start,end) ; //從Text1中刪除被選取的文本。
}
else if(e.getSource()==paste) //從剪貼板粘貼數據。
{ Transferable contents=clipboard.getContents(this);
DataFlavor flavor= DataFlavor.stringFlavor;
if( contents.isDataFlavorSupported(flavor))
try{ String str;
str=(String)contents.getTransferData(flavor);
text2.append(str);
}
catch(Exception ee){}
}
}
public static void main(String args[])
{ Test win=new Test();
}
}

⑵ java文件復制粘貼

復制粘貼實際上是文件的流讀取和寫入可以通過如下方法實現:
讀寫是兩個不同的分支,通常都是分開單獨使用的。
可以通過BufferedReader 流的形式進行流緩存,之後通過readLine方法獲取到緩存的內容。
BufferedReader bre = null;
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此時獲取到的bre就是整個文件的緩存流
while ((str = bre.readLine())!= null) // 判斷最後一行不存在,為空結束循環
{
System.out.println(str);//原樣輸出讀到的內容
};
備註: 流用完之後必須close掉,如上面的就應該是:bre.close(),否則bre流會一直存在,直到程序運行結束。
可以通過「FileOutputStream」創建文件實例,之後過「OutputStreamWriter」流的形式進行存儲,舉例:
OutputStreamWriter pw = null;//定義一個流
pw = new OutputStreamWriter(new FileOutputStream(「D:/test.txt」),"GBK");//確認流的輸出文件和編碼格式,此過程創建了「test.txt」實例
pw.write("我是要寫入到記事本文件的內容");//將要寫入文件的內容,可以多次write
pw.close();//關閉流
備註:文件流用完之後必須及時通過close方法關閉,否則會一直處於打開狀態,直至程序停止,增加系統負擔。

熱點內容
小米4清除緩存 發布:2025-07-16 03:03:17 瀏覽:562
如何緩解壓力英語作文 發布:2025-07-16 03:03:15 瀏覽:14
手機視頻怎麼緩存 發布:2025-07-16 02:59:05 瀏覽:932
安卓手機設備在哪裡找 發布:2025-07-16 02:49:28 瀏覽:356
php建立數組 發布:2025-07-16 02:34:30 瀏覽:284
oracle存儲過程同步 發布:2025-07-16 02:29:18 瀏覽:941
歐諾s買哪個配置的好 發布:2025-07-16 02:26:22 瀏覽:559
熱點可以建立ftp嗎 發布:2025-07-16 02:26:21 瀏覽:304
如何選擇最佳配置 發布:2025-07-16 01:56:44 瀏覽:604
mad加密 發布:2025-07-16 01:52:12 瀏覽:425