jacon
com的線程回收不由java垃圾回收器進行處理,因此,每new一次jacob提供的類就要分配一定大小的內存給該操作,new出來的這個com對象在使用結束之后產生的垃圾java是無法回收的,new出來的對象越來越多,內存溢出就不可避免了,即使增加jvm內存也只是暫時的,遲早這些對象會把內存用完。既然java不能回收這些垃圾,那么com組件也應該提供了回收垃圾的方法,最后得知是ComThread.InitSTA()和ComThread.Release()方法,這兩個方法其實就是初始化一個線程和結束這個線程,在創建com對象的時候初始化一個線程來運行這個對象,這個對象使用結束之后再結束線程,
/** * @fileName MSWordManager.java
* @description 該類用于查找word文檔指定位置并將圖片插入
* @date 2011-10-21 * @time * @author wst */
public class MSWordManager {
private Logger log = Logger.getLogger(MSWordManager.class);
// word文檔
private Dispatch doc;
// word運行程序對象
private ActiveXComponent word;
// 所有word文檔集合
private Dispatch documents;
// 選定的范圍或插入點
private Dispatch selection;
public static int instanceSize=3;
//一個線程存放的MSWordManager數量
public MSWordManager(int index) {
if (word == null) {
word = new ActiveXComponent("Word.Application");
//為true表示word應用程序可見
word.setProperty("Visible", new Variant(false));
}
if (documents == null){
documents = word.getProperty("Documents").toDispatch();
}
if(index==0){
ComThread.InitSTA();
//初始化一個線程并放入內存中等待調用 } }
/** * 打開一個已經存在的文檔 * @param docPath 要打開的文檔
* @param key 文本框的內容,根據該key獲取文本框當前位置
* @date 2011-12-9 * @author wst */
public void openDocumentAndGetSelection(String docPath, String key) {
try{
closeDocument() // 打開文檔
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
// shapes集合
Dispatch shapes = Dispatch.get(doc, "Shapes").toDispatch();
// shape的個數
String Count = Dispatch.get(shapes, "Count").toString();
for (int i = 1; i <= Integer.parseInt(Count); i++) {
// 取得一個shape
Dispatch shape = Dispatch.call(shapes, "Item", new Variant(i)).toDispatch();
// 從一個shape里面獲取到文本框
Dispatch textframe = Dispatch.get(shape, "TextFrame").toDispatch();
boolean hasText = Dispatch.call(textframe, "HasText").toBoolean();
if (hasText) {
// 獲取該文本框對象
Dispatch TextRange = Dispatch.get(textframe, "TextRange").toDispatch();
// 獲取文本框中的字符串
String str = Dispatch.get(TextRange, "Text").toString();
//獲取指定字符key所在的文本框的位置
if (str != null && !str.equals("") && str.indexOf(key) > -1) {
//當前文本框的位置
selection = Dispatch.get(textframe, "TextRange").toDispatch();
// 情況文本框內容
Dispatch.put(selection, "Text", ""); break; } }
} }catch(Exception e){ log.error(e); return; }
}
/** * 在當前位置插入圖片
* @param imagePath 產生圖片的路徑
* @return 成功:true;失敗:false */
public boolean insertImage(String imagePath) {
try{
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),"AddPicture", imagePath);
}catch(Exception e){
log.error(e); return false;
}
return true; }
//關閉文檔 public void closeDocument()
{ if (doc != null) { Dispatch.call(doc, "Close"); doc = null; }
}
//關閉全部應用
public void close(int index) {
if (word != null) { Dispatch.call(word, "Quit"); word = null; }
selection = null; documents = null; if(index==instanceSize){
//釋放占用的內存空間,因為com的線程回收不由java的垃圾回收器處理
ComThread.Release(); }
}
}
浙公網安備 33010602011771號