1. java如何按行數讀取txt 比如我要讀第10行到第100行 或者第1000行 到 第1200 行
用LineNumberReader行號讀取器
FileReader f=new FileReader("test.txt");
LineNumberReader l=new LineNumberReader(f);
l.setLineNumber(10); //跳到第10行
for(int i=10;i<=100;i++){
System.out.println( l.readLine()); //顯示第10-100行
}
l.close();
f.close();
2. bson 是一種什麼數據格式java中常用嗎和json啥區別啊
java中沒有BSON,xml和json比較常用
BSON是由10gen開發的一個數據格式,目前主要用於MongoDB中,是MongoDB的數據存儲格式。BSON基於JSON格式,選擇JSON進行改造的原因主要是JSON的通用性及JSON的schemaless的特性。
BSON主要會實現以下三點目標:
1.更快的遍歷速度
對JSON格式來說,太大的JSON結構會導致數據遍歷非常慢。在JSON中,要跳過一個文檔進行數據讀取,需要對此文檔進行掃描才行,需要進行麻煩的數據結構匹配,比如括弧的匹配,而BSON對JSON的一大改進就是,它會將JSON的每一個元素的長度存在元素的頭部,這樣你只需要讀取到元素長度就能直接seek到指定的點上進行讀取了。
2.操作更簡易
對JSON來說,數據存儲是無類型的,比如你要修改基本一個值,從9到10,由於從一個字元變成了兩個,所以可能其後面的所有內容都需要往後移一位才可以。而使用BSON,你可以指定這個列為數字列,那麼無論數字從9長到10還是100,我們都只是在存儲數字的那一位上進行修改,不會導致數據總長變大。當然,在MongoDB中,如果數字從整形增大到長整型,還是會導致數據總長變大的。
3.增加了額外的數據類型
JSON是一個很方便的數據交換格式,但是其類型比較有限。BSON在其基礎上增加了「byte array」數據類型。這使得二進制的存儲不再需要先base64轉換後再存成JSON。大大減少了計算開銷和數據大小。
當然,在有的時候,BSON相對JSON來說也並沒有空間上的優勢,比如對{「field」:7},在JSON的存儲上7隻使用了一個位元組,而如果用BSON,那就是至少4個位元組(32位)
目前在10gen的努力下,BSON已經有了針對多種語言的編碼解碼包。並且都是Apache 2 license下開源的。並且還在隨著MongoDB進一步地發展。關於BSON,
3. Java如何將文本文檔中的字元串讀取到字元串數組
使用RandomAccessFile先讀取一次計算行數,seek重置到文件頭部,再讀取每行,賦值給a數組。
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.RandomAccessFile;
publicclassTest{
//此題目關鍵是根據文件內容確定二維數組的行數和列數
publicstaticvoidmain(String[]args){
RandomAccessFilereader=null;
try{
reader=newRandomAccessFile("test.txt","r");
intn=0;//行數
while(reader.readLine()!=null){//第一次按行讀取只為了計算行數
n++;
}
String[][]a=newString[n][];
reader.seek(0);//重置到文件頭部
intj;
Stringline;
String[]strs;
inti=0;
while((line=reader.readLine())!=null){//第二次按行讀取是真正的讀取數據
strs=line.split("");//把讀取到的一行數據以空格分割成子字元串數組
a[i]=newString[strs.length];//列數就是數組strs的大小,此句是逐行創建二維數組的列
for(j=0;j<strs.length;j++){
a[i][j]=strs[j];//逐行給二維數組的每一列賦值
}
i++;
}
for(i=0;i<n;i++){
for(j=0;j<a[i].length;j++){
System.out.println("a["+i+"]["+j+"]="+a[i][j]);
}
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
reader=null;
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
}
運行結果如圖
4. JAVA 的輸入輸出,讀取寫入文件
//將內容追加到文件尾部
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 將內容追加到文件尾部
*/
public class AppendToFile {
/**
* A方法追加文件:使用File
* @param fileName 文件名
* @param content 追加的內容
*/
public static void appendMethodA(String fileName, String content){
try {
// 打開一個隨機訪問文件流,按讀寫方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件長度,位元組數
long fileLength = randomFile.length();
//將寫文件指針移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e){
e.printStackTrace();
}
}
/**
* B方法追加文件:使用FileWriter
* @param fileName
* @param content
*/
public static void appendMethodB(String fileName, String content){
try {
//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. ");
//顯示文件內容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. ");
//顯示文件內容
ReadFromFile.readFileByLines(fileName);
}
}
本篇文章來源於:開發學院 http://e.codepub.com 原文鏈接:http://e.codepub.com/2010/0323/21269_2.php
5. 用JAVA編個簡單的記事本程序
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
class Editor extends Frame implements ActionListener,ItemListener
{
// Date date=new Date();
int n1;String str="";int k=0;String st1,st2;
JTextArea ta=new JTextArea(50,50);
Dialog dialog,dialog1;
Choice ce1,ce2,ce3;
Button btn1,btn2,btn3;Panel p1=new Panel();
Panel p2=new Panel();Panel p3=new Panel();Panel p4=new Panel();
public Editor (String s)
{
super ("記事本編輯板");
ImageIcon YouImg = new ImageIcon("iconimage.jpg");
setIconImage(YouImg.getImage());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
setBounds(50,35,700,500);
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu file=new Menu("文件(F)");Menu edit=new Menu("編輯(E)");Menu help=new Menu("幫助(H)");
Menu pattern=new Menu("格式(P)");Menu time=new Menu("時間(T)");
MenuItem exit=new MenuItem("退出",new MenuShortcut(KeyEvent.VK_Q));
MenuItem tdate=new MenuItem("日期/時間",new MenuShortcut(KeyEvent.VK_D));
MenuItem renew=new MenuItem("新建", new MenuShortcut(KeyEvent.VK_N));
MenuItem save=new MenuItem("保存", new MenuShortcut(KeyEvent.VK_S));
MenuItem open=new MenuItem("打開",new MenuShortcut(KeyEvent.VK_O));
MenuItem =new MenuItem("復制",new MenuShortcut(KeyEvent.VK_C));
MenuItem paste=new MenuItem("粘貼",new MenuShortcut(KeyEvent.VK_V));
MenuItem cut=new MenuItem("剪切",new MenuShortcut(KeyEvent.VK_X));
MenuItem helptopic=new MenuItem("主題",new MenuShortcut(KeyEvent.VK_T));
helptopic.addActionListener(this);
dialog=new Dialog(this, "字體設置");dialog.setSize(300,300);
dialog1=new Dialog(this, "幫助主題");dialog1.setBounds(250,100,300,400);
dialog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog.setVisible(false);}
});
dialog1.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog1.setVisible(false);}
});
//dialog.setBackground(Color.WHITE);
dialog.setLayout(null);dialog.setBounds(170,150,450,300);
Label L1=new Label("字體(F)");Label L2=new Label("字形(Y)");
Label L3=new Label("大小(S)");TextArea ta1=new TextArea(5,5);
ta1=new TextArea("至於記事本的主題嘛,因為本人的水平有限, 所有不能為大家作過多的指導,望大家見諒!"); //在這里我想加一個文本框用來放幫助信息。
ce1=new Choice();ce2=new Choice();
ce3=new Choice();
btn1=new Button("確定");btn2=new Button("取消");btn1.addActionListener(this);btn2.addActionListener(this);
btn3=new Button("顏色");
btn3.addActionListener(this);
ce1.add("華文行楷");ce1.add("華文中宋");ce1.add("華文新魏");ce1.add("華文細黑");ce1.add("宋體");ce1.add("方正姚體");
ce1.add("幼圓");ce1.add("隸書");ce1.add("楷體-GB2312");ce1.add("華文行楷");ce1.add("華文彩雲");ce1.add("仿宋-GB2312");
ce2.add("粗體");ce2.add("斜體");ce2.add("常規");
for(int n1=0;n1<=100;n1++)
{ce3.add(""+n1);}
dialog.add(p1);p1.setBounds(5,30,440,35);p1.setLayout( null);//p1.setBackground(Color.red);
dialog.add(p2);p2.setBounds(5,65,440,27);dialog.add(p3);p3.setBounds(5,90,440,40);//p4.setBounds(5,120,440,138);
p1.setLayout( null);
p1.add(L1);L1.setBounds(5,15,50,25);p1.add(L2);L2.setBounds(150,15,50,25);
p1.add(L3);L3.setBounds(250,15,50,25);p2.setLayout( null);//p2.setBackground(Color.yellow);
p2.add(ce1);ce1.setBounds(5,0,130,25);p2.add(ce2);ce2.setBounds(160,0,90,25);p2.add(ce3);ce3.setBounds(260,0,75,25);
p2.add(btn1);btn1.setBounds(360,0,75,25);
p3.setLayout( null);p3.add(btn2);btn2.setBounds(360,10,75,25);p3.add(btn3);btn3.setBounds(160,10,75,25);
dialog.add(p4);p4.setBackground(Color.yellow);p4.setBounds(5,120,440,138);
dialog1.add(ta1);
//設置字體的下拉情況
MenuItem Font=new MenuItem("字體");//給字體加監聽器
Font.addActionListener(this);
MenuItem Replace=new MenuItem("替換"); MenuItem Seek=new MenuItem("查找");
//首要添加組件的情況
mb.add(file);mb.add(edit);mb.add(pattern);mb.add(time);mb.add(help);
file.add(renew);file.addSeparator();file.add(open);time.add(tdate);
file.addSeparator(); file.add(exit);file.addSeparator();file.add(save);
edit.add(); edit.addSeparator();edit.add(paste);edit.addSeparator();edit.add(cut);
pattern.add(Font); pattern.add(Replace);
pattern.add(Seek);help.add(helptopic);
//給必要的組件加上監聽器
renew.addActionListener( this);tdate.addActionListener(this);
open.addActionListener(this); save.addActionListener(this);exit.addActionListener(this);
cut.addActionListener(this);.addActionListener(this);paste.addActionListener(this);
ce1.addItemListener(this);ce2.addItemListener(this);ce3.addItemListener(this);
//添加必要的組件
add(ta,"Center");ta.setBackground(new Color(249,255,234));
setSize(700,500);
setVisible(true);
this.validate() ;
}
public void itemStateChanged(ItemEvent e) {
if (ce2.getSelectedItem().equals("粗體"))
{ k=1;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("斜體"))
{ k=2;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("常規"))
{ k=3;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("新建"))
{System.out.println("new ");
ta.setText("");}
if(e.getActionCommand().equals("退出"))
{ System.exit(0);}
try
{
if(e.getActionCommand().equals("打開"))
openText();
if(e.getActionCommand().equals("保存"))
saveText();
}catch(IOException e1){}
if(e.getActionCommand().equals("復制"))
{ str=ta.getSelectedText();}
if(e.getActionCommand().equals("粘貼"))
{ ta.insert(str,ta.getCaretPosition());}
if(e.getActionCommand().equals("剪切"))
{str=ta.getSelectedText();ta.replaceRange("",ta.getSelectionStart(),ta.getSelectionEnd());
}
if(e.getActionCommand().equals("字體"))
{dialog.setVisible(true);}
if(e.getActionCommand().equals("主題"))
{dialog1.setVisible(true);}
if(e.getActionCommand().equals("顏色"))
{
Color clr=JColorChooser.showDialog(this,"顏色對話框",null);
ta.setForeground(clr);
}
if(e.getSource()==btn2)
dialog.setVisible(false);
if(e.getSource()==btn1)
{
if(k==1)
{ ta.setFont(new Font(st1,Font.BOLD,Integer.parseInt(st2)));}
if(k==2)
{ ta.setFont(new Font(st1,Font.ITALIC,Integer.parseInt(st2)));}
if(k==3)
{ ta.setFont(new Font(st1,Font.PLAIN,Integer.parseInt(st2)));}
dialog.setVisible(false);
}
//if (e.getActionCommand().equals("日期/時間"))
//ta.setText(ta.getText()+""+date);
if(e.getActionCommand().equals("日期/時間"))
{
Calendar c1 =Calendar.getInstance();
int y = c1.get(Calendar.YEAR);
int m = c1.get(Calendar.MONTH);
int d = c1.get(Calendar.DATE);
int h = c1.get(Calendar.HOUR);
int m1 = c1.get(Calendar.MINUTE);
int m2 = m+1;
ta.setText(ta.getText()+""+(y+"年"+m2+"月"+d+"日"+h+":"+m1));
}
}
public void openText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.LOAD);
fd.setVisible(true);FileInputStream fis=new FileInputStream(fd.getDirectory()+fd.getFile());
ta.setText("");
int n=0;
while((n=fis.read())!=-1)
ta.append(""+(char)n);
fis.close();
}
public void saveText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.SAVE);
fd.setVisible(true);
FileOutputStream out=new FileOutputStream(fd.getDirectory()+fd.getFile()+".txt");
String str=ta.getText();
String str1=ta.getText();
for(int n=0;n<str.length();n++)
out.write((byte)str.charAt(n));
out.close();
}
public static void main(String[] args)
{
Editor f=new Editor(" 記事本程序");
//添加時間代碼
Date date=new Date();
System.out.print(date);
/*Calendar now=Calendar.getInstance();
int year=now.get(Calendar.YEAR);
int month=now.get(Calendar.MONTH)+1;
int day=now.get(Calendar.DATE);
System.out.print(year+"年"+month+"月"+day+"日");
int week=now.get(Calendar.DAY_OF_WEEK);
String str="日一二三四五六";//星期1-7
int i=2*(week-1);
System.out.println("星期"+str.substring(i,i+2));//對應中文的下標*/
}
class dialog extends Dialog
{
public dialog()
{
super(dialog, "字體設置");
class Mycanvas extends Canvas
{
Toolkit tk;
Image img;
Mycanvas()
{
setSize(440,138);
tk=getToolkit();
img=tk.getImage("photo.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,5,120,440,138,this);
}
}
}
}
}
6. java生成word文檔的問題
Jacob解決Word文檔的讀寫問題收藏
Jacob 是Java-COM Bridge的縮寫,它在Java與微軟的COM組件之間構建一座橋梁。使用Jacob自帶的DLL動態鏈接庫,並通過JNI的方式實現了在Java平台上對COM程序的調用。Jacob下載的地址為:
http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368
配置:
(1)將解壓包中的jacob.dll(x86常用,x64)拷到jdk安裝目錄下的jre\bin文件夾或windows安裝路徑下的WINDOWS\system32文件夾下
(2)將jacob.jar文件拷到classpath下即可
常見問題解決:
對於」java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由於應用程序配置不正確,應用程序未能啟動。重新安裝應用程序可能會糾正」這個問題,可以通過
重新下載Jacob的jar及dll文件(最好版本比現在的低,如1.11)解決
實例製作(主要功能:標題製作,表格製作,合並表格,替換文本,頁眉頁腳,書簽處理):
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordOperate {
public static void main(String args[]) {
ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 啟動word
// Set the visible property as required.
Dispatch.put(wordApp, "Visible", new Variant(true));// //設置word可見
Dispatch docs = wordApp.getProperty("Documents").toDispatch();
// String inFile = "d:\\test.doc";
// Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
// new Object[] { inFile, new Variant(false), new Variant(false)},//參數3,false:可寫,true:只讀
// new int[1]).toDispatch();//打開文檔
Dispatch document = Dispatch.call(docs, "Add").toDispatch();// create new document
String userName = wordApp.getPropertyAsString("Username");// 顯示用戶信息
System.out.println("用戶名:" + userName);
// 文檔對齊,字體設置////////////////////////
Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();
Dispatch align = Dispatch.get(selection, "ParagraphFormat")
.toDispatch(); // 行列格式化需要的對象
Dispatch font = Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的對象
// 標題處理////////////////////////
Dispatch.put(align, "Alignment", "1"); // 1:置中 2:靠右 3:靠左
Dispatch.put(font, "Bold", "1"); // 字型租體
Dispatch.put(font, "Color", "1,0,0,0"); // 字型顏色紅色
Dispatch.call(selection, "TypeText", "Word文檔處理"); // 寫入標題內容
Dispatch.call(selection, "TypeParagraph"); // 空一行段落
Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
Dispatch.put(selection, "Text", " ");
Dispatch.call(selection, "MoveDown"); // 游標標往下一行
//表格處理////////////////////////
Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch table1 = Dispatch.call(tables, "Add", range, new Variant(3),
new Variant(2), new Variant(1)).toDispatch(); // 設置行數,列數,表格外框寬度
// 所有表格
Variant tableAmount = Dispatch.get(tables, "count");
System.out.println(tableAmount);
// 要填充的表格
Dispatch t1 = Dispatch.call(tables, "Item", new Variant(1))
.toDispatch();
Dispatch t1_row = Dispatch.get(t1, "rows").toDispatch();// 所有行
int t1_rowNum = Dispatch.get(t1_row, "count").getInt();
Dispatch.call(Dispatch.get(t1, "columns").toDispatch(), "AutoFit");// 自動調整
int t1_colNum = Dispatch.get(Dispatch.get(t1, "columns").toDispatch(),
"count").getInt();
System.out.println(t1_rowNum + " " + t1_colNum);
for (int i = 1; i <= t1_rowNum; i++) {
for (int j = 1; j <= t1_colNum; j++) {
Dispatch cell = Dispatch.call(t1, "Cell", new Variant(i),
new Variant(j)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(selection, "Text", "cell" + i + j); // 寫入word的內容
Dispatch.put(font, "Bold", "0"); // 字型租體(1:租體 0:取消租體)
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(font, "Italic", "1"); // 斜體 1:斜體 0:取消斜體
Dispatch.put(font, "Underline", "1"); // 下劃線
Dispatch Range = Dispatch.get(cell, "Range").toDispatch();
String cellContent = Dispatch.get(Range, "Text").toString();
System.out.println((cellContent.substring(0, cellContent
.length() - 1)).trim());
}
Dispatch.call(selection, "MoveDown"); // 游標往下一行(才不會輸入蓋過上一輸入位置)
}
//合並單元格////////////////////////
Dispatch.put(selection, "Text", " ");
Dispatch.call(selection, "MoveDown"); // 游標標往下一行
Dispatch range2 = Dispatch.get(selection, "Range").toDispatch();
Dispatch table2 = Dispatch.call(tables, "Add", range2, new Variant(8),
new Variant(4), new Variant(1)).toDispatch(); // 設置行數,列數,表格外框寬度
Dispatch t2 = Dispatch.call(tables, "Item", new Variant(2))
.toDispatch();
Dispatch beginCell = Dispatch.call(t2, "Cell", new Variant(1),
new Variant(1)).toDispatch();
Dispatch endCell = Dispatch.call(t2, "Cell", new Variant(4),
new Variant(4)).toDispatch();
Dispatch.call(beginCell, "Merge", endCell);
for (int row = 1; row <= Dispatch.get(
Dispatch.get(t2, "rows").toDispatch(), "count").getInt(); row++) {
for (int col = 1; col <= Dispatch.get(
Dispatch.get(t2, "columns").toDispatch(), "count").getInt(); col++) {
if (row == 1) {
Dispatch cell = Dispatch.call(t2, "Cell", new Variant(1),
new Variant(1)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(selection, "Text", "merge Cell!");
} else {
Dispatch cell = Dispatch.call(t2, "Cell", new Variant(row),
new Variant(col)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(selection, "Text", "cell" + row + col);
}
}
Dispatch.call(selection, "MoveDown");
}
//Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// 取消選擇
// Object content = Dispatch.get(doc,"Content").toDispatch();
// Word文檔內容查找及替換////////////////////////
Dispatch.call(selection, "TypeParagraph"); // 空一行段落
Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
Dispatch.put(font, "Color", 0);
Dispatch.put(selection, "Text", "歡迎,Hello,world!");
Dispatch.call(selection, "HomeKey", new Variant(6));// 移到開頭
Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 獲得Find組件
Dispatch.put(find, "Text", "hello"); // 查找字元串"hello"
Dispatch.put(find, "Forward", "True");// 向前查找
// Dispatch.put(find, "Format", "True");// 設置格式
Dispatch.put(find, "MatchCase", "false");// 大小寫匹配
Dispatch.put(find, "MatchWholeWord", "True"); // 全字匹配
Dispatch.call(find, "Execute"); // 執行查詢
Dispatch.put(selection, "Text", "你好");// 替換為"你好"
//使用方法傳入的參數parameter調用word文檔中的MyWordMacro宏//
//Dispatch.call(document,macroName,parameter);
//Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);
//頁眉,頁腳處理////////////////////////
Dispatch ActiveWindow = wordApp.getProperty("ActiveWindow")
.toDispatch();
Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane")
.toDispatch();
Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
Dispatch.put(View, "SeekView", "9"); //9是設置頁眉
Dispatch.put(align, "Alignment", "1"); // 置中
Dispatch.put(selection, "Text", "這里是頁眉"); // 初始化時間
Dispatch.put(View, "SeekView", "10"); // 10是設置頁腳
Dispatch.put(align, "Alignment", "2"); // 靠右
Dispatch.put(selection, "Text", "這里是頁腳"); // 初始化從1開始
//書簽處理(打開文檔時處理)////////////////////////
//Dispatch activeDocument = wordApp.getProperty("ActiveDocument").toDispatch();
Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
boolean isExist = Dispatch.call(bookMarks, "Exists", "bookMark1")
.getBoolean();
if (isExist == true) {
Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
.toDispatch();
Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
Dispatch.put(range1, "Text", new Variant("當前是書簽1的文本信息!"));
String bookMark1Value = Dispatch.get(range1, "Text").toString();
System.out.println(bookMark1Value);
} else {
System.out.println("當前書簽不存在,重新建立!");
Dispatch.call(bookMarks, "Add", "bookMark1", selection);
Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
.toDispatch();
Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
Dispatch.put(range1, "Text", new Variant("當前是書簽1的文本信息!"));
String bookMark1Value = Dispatch.get(range1, "Text").toString();
System.out.println(bookMark1Value);
}
//保存操作////////////////////////
Dispatch.call(document, "SaveAs", "D:/wordOperate.doc");
//Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]); //生成html文件
// 0 = wdDoNotSaveChanges
// -1 = wdSaveChanges
// -2 = wdPromptToSaveChanges
//Dispatch.call(document, "Close", new Variant(0));
// // worddoc.olefunction("protect",2,true,"");
// // Dispatch bookMarks = wordApp.call(docs,"Bookmarks").toDispatch();
// // System.out.println("bookmarks"+bookMarks.getProgramId());
// //Dispatch.call(doc, "Save"); //保存
// // Dispatch.call(doc, "Close", new Variant(true));
// //wordApp.invoke("Quit",new Variant[]{});
// wordApp.safeRelease();//Finalizers call this method
}
}
7. java利用jacob實現word文檔水印操作
http://www..com/s?wd=52070475597
package com.ymo.word;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class TestJacobWord {
private ActiveXComponent wrdCom = null;
private Dispatch doc = null;
private Dispatch activeDoc = null;
private Dispatch docSelect = null;
private Dispatch docs = null;
private static TestJacobWord instance = null;
private String docName = "";
public static TestJacobWord getInstance() {
if (instance == null) {
instance = new TestJacobWord();
}
return instance;
}
private boolean initWord() {
boolean flag = false;
ComThread.InitSTA();
wrdCom = new ActiveXComponent("word.Application");
try {
docs = wrdCom.getProperty("Documents").toDispatch();
wrdCom.setProperty("Visible", new Variant(false));
flag = true;
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
private void createNewDocument() {
doc = Dispatch.call(docs, "Add").toDispatch();
docSelect = Dispatch.get(wrdCom, "Selection").toDispatch();
}
private void getActiveDoc() {
activeDoc = wrdCom.getProperty("ActiveWindow").toDispatch();
System.out.println(activeDoc.getProgramId());
}
private void openDocument(String docPath) {
if (this.doc != null) {
closeDocument();
}
this.doc = Dispatch.call(docs, "Open", docPath, new Variant(false),
new Variant(false)).toDispatch();
docSelect = Dispatch.get(wrdCom, "Selection").toDispatch();
}
private void closeDocument() {
if (doc != null) {
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(true));
doc = null;
}
}
private void setImgWaterMark(String waterMarkPath) {
Dispatch activePan = Dispatch.get(activeDoc, "ActivePane").toDispatch();
Dispatch view = Dispatch.get(activePan, "View").toDispatch();
Dispatch.put(view, "SeekView", new Variant(9));
Dispatch headfooter = Dispatch.get(docSelect, "HeaderFooter")
.toDispatch();
// 取得圖形對象
Dispatch shapes = Dispatch.get(headfooter, "Shapes").toDispatch();
Dispatch pic = Dispatch.call(shapes, "AddPicture", waterMarkPath)
.toDispatch();
Dispatch.call(pic, "Select");
Dispatch.put(pic, "Left", new Variant(10));
Dispatch.put(pic, "Top", new Variant(200));
Dispatch.put(pic, "Width", new Variant(150));
Dispatch.put(pic, "Height", new Variant(80));
Dispatch.put(view, "SeekView", new Variant(0));
}
public void setTextWaterMark(String waterMarkStr) {
Dispatch activePan = Dispatch.get(activeDoc, "ActivePane").toDispatch();
Dispatch view = Dispatch.get(activePan, "View").toDispatch();
Dispatch.put(view, "SeekView", new Variant(9));
Dispatch headfooter = Dispatch.get(docSelect, "HeaderFooter")
.toDispatch();
Dispatch shapes = Dispatch.get(headfooter, "Shapes").toDispatch();
Dispatch selection = Dispatch.call(shapes, "AddTextEffect",
new Variant(9), waterMarkStr, "宋體", new Variant(1),
new Variant(false), new Variant(false), new Variant(0),
new Variant(0)).toDispatch();
Dispatch.call(selection, "Select");
Dispatch shapeRange = Dispatch.get(docSelect, "ShapeRange")
.toDispatch();
Dispatch.put(shapeRange, "Name", "PowerPlusWaterMarkObject
1");
Dispatch textEffect = Dispatch.get(shapeRange, "TextEffect")
.toDispatch();
Dispatch.put(textEffect, "NormalizedHeight", new Boolean(false));
Dispatch line = Dispatch.get(shapeRange, "Line").toDispatch();
Dispatch.put(line, "Visible", new Boolean(false));
Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch();
Dispatch.put(fill, "Visible", new Boolean(true));
// 設置水印透明度
Dispatch.put(fill, "Transparency", new Variant(0.5));
Dispatch foreColor = Dispatch.get(fill, "ForeColor").toDispatch();
Dispatch.put(foreColor, "RGB", new Variant(16711620));
Dispatch.call(fill, "Solid");
// 設置水印旋轉
Dispatch.put(shapeRange, "Rotation", new Variant(315));
Dispatch.put(shapeRange, "LockAspectRatio", new Boolean(true));
Dispatch.put(shapeRange, "Height", new Variant(117.0709));
Dispatch.put(shapeRange, "Width", new Variant(468.2835));
Dispatch.put(shapeRange, "Left", new Variant(-999995));
Dispatch.put(shapeRange, "Top", new Variant(-999995));
Dispatch wrapFormat = Dispatch.get(shapeRange, "WrapFormat")
.toDispatch();
// 是否允許交疊
Dispatch.put(wrapFormat, "AllowOverlap", new Variant(true));
Dispatch.put(wrapFormat, "Side", new Variant(3));
Dispatch.put(wrapFormat, "Type", new Variant(3));
Dispatch.put(shapeRange, "RelativeHorizontalPositi
on", new Variant(0));
Dispatch.put(shapeRange, "RelativeVerticalPosition
", new Variant(0));
Dispatch.put(view, "SeekView", new Variant(0));
}
private void closeWord() {
// 關閉word文件
wrdCom.invoke("Quit", new Variant[] {});
// 釋放com線程
ComThread.Release();
}
public String getDocName() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
private boolean addWaterMark(String wordPath, String waterMarkPath) {
boolean flag = false;
try {
if (initWord()) {
openDocument(wordPath);
getActiveDoc();
setImgWaterMark(waterMarkPath);
closeDocument();
closeWord();
flag = true;
} else {
flag = false;
}
} catch (Exception e) {
flag = false;
e.printStackTrace();
closeDocument();
closeWord();
}
return flag;
}
public static void main(String[] args) {
TestJacobWord jacob = TestJacobWord.getInstance();
// jacob.addWaterMark("F://test//test.doc", "F://test//ymo.jpg");
try {
if (jacob.initWord()) {
jacob.openDocument("F://test/test.doc");
jacob.getActiveDoc();
jacob.setTextWaterMark("重慶宇能科技有限公司");
jacob.closeDocument();
jacob.closeWord();
}
} catch (Exception e) {
e.printStackTrace();
jacob.closeDocument();
jacob.closeWord();
}
}
}