Java文件操作源碼大全


Java文件操作源碼大全

1.創建文件夾 5
2.創建文件 5
3.刪除文件 5
4.刪除文件夾 6
5.刪除一個文件下夾所有的文件夾 7
6.清空文件夾 8
7.讀取文件 8
8.寫入文件 9
9.寫入隨機文件 9
10.讀取文件屬性 9
11.寫入屬性 10
12.枚舉一個文件夾中的所有文件 10
13.復制文件夾 11
14.復制一個目錄下所有的文件夾到另一個文件夾下 12
15.移動文件夾 13
16.移動一個目錄下所有的文件夾到另一個目錄下 15
17.以一個文件夾的框架在另一個目錄創建文件夾和空文件 16
18.復制文件 17
19.復制一個目錄下所有的文件到另一個目錄 17
20.提取擴展名 18
21.提取文件名 18
22.提取文件路徑 18
23.替換擴展名 18
24.追加路徑 18
25.移動文件 18
26.移動一個目錄下所有文件到另一個目錄 19
27.指定目錄下搜索文件 20
28.打開對話框 20
29.文件分割 20
30.文件合並 21
31.文件簡單加密 21
32.文件簡單解密 22
33.讀取ini文件屬性 23
34.合並一個目錄下所有的文件 25
35.寫入ini文件屬性 26
36.獲得當前路徑 27
37.讀取XML數據庫 27
38.寫入XML數據庫 28
39.ZIP壓縮文件 30
40.ZIP解壓縮 31
41.獲得應用程序完整路徑 32
42.遞歸刪除目錄中的文件 32
43.ZIP壓縮文件夾 32
44.驗證DTD 34
45.驗證Schema 34
46.Grep 35
47.直接創建多級目錄 35
48.批量重命名 35
49.文本查找替換 36
50.文件關聯 37
51.操作Excel文件 37
一, 建立Excel工作薄 39
二, 建立Excel工作表,每個工作表對應的是Excel界面左下角的一個標簽sheet1,sheet2 … 39
三, 在工作表中建立單元格 39
四, 向單元格插入日期值 40
五, 各種單元格樣式 40
六, 行高,列寬。 41
52.設置JDK環境變量 43
53.選擇文件夾對話框 44
54.刪除空文件夾 44
55.發送數據到剪貼板 45
56.從剪貼板中取數據 45
57.獲取文件路徑的父路徑 45
58.創建快捷方式 45
59.彈出快捷菜單 46
60.文件夾復制到整合操作 46
61.文件夾移動到整合操作 47
62.目錄下所有文件夾復制到整合操作 48
63.目錄下所有文件夾移動到整合操作 48
64.目錄下所有文件復制到整合操作 49
65.目錄下所有文件移動到整合操作 49
66.對目標壓縮文件解壓縮到指定文件夾 50
67.創建目錄副本整合操作 50
68.打開網頁 51
69.刪除空文件夾整合操作 51
73.FTP下載 54
74.寫圖像到剪切板 setClipboardImage 55
75.從剪貼板復制圖像到窗體 55
76.刪除文件夾下的所有文件且不刪除文件夾下的文件夾 55
78.拷貝文件名復制文件 56
79.開源程序庫Xercesc-C++代碼工程中內聯 57
80.提取包含頭文件列表 63
81.剪貼扳轉換成打印字符 64
82.把JButton或JTree組件寫到一個流中 65
83.注冊全局熱鍵 66
84.菜單勾選/取消完成后關閉計算機 69
85.菜單勾選/取消完成后重新啟動計算機 70
86.菜單勾選/取消完成后注銷計算機 71
87.菜單勾選/取消開機自啟動程序 72
88.菜單勾選/取消自動登錄系統 74
89.模擬鍵盤輸入字符串 74
91.操作內存映射文件 78
93.接受郵件 81
94.發送郵件 84
95.報表相關 89
96.全屏幕截取 89
97.區域截幕 90
98.計算文件MD5值 94
99.計算獲取文件夾中文件的MD5值

1.創建文件夾
//import  java.io.*;
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目錄操作出錯");
e.printStackTrace();
}

2.創建文件
//import java.io.*;
File myFilePath = new File(%%1);
try {
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(%%2);
myFile.flush();
resultFile.close();
}
catch (Exception e) {
System.out.println("新建文件操作出錯");
e.printStackTrace();
}

3.刪除文件
//import java.io.*;
File myDelFile = new File(%%1);
try {
myDelFile.delete();
}
catch (Exception e) {
System.out.println("刪除文件操作出錯");
e.printStackTrace();
}

4.刪除文件夾
/*
import java.io.*;
import java.util.*;
*/
LinkedList folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
ArrayList<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.getLast());
if (file.delete()) {
folderList.removeLast();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}

5.刪除一個文件下夾所有的文件夾
/*
import java.io.*;
private static LinkedList<String> folderList=null;
*/
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
if(!files[i].delete()){
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
ArrayList<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File(folderList.getLast());
if (file.delete()) {
folderList.removeLast();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
}
}

6.清空文件夾
//import java.io.*;
File delfilefolder=new File(%%1);
try {
if (!delfilefolder.exists() && !delfilefolder.delete()){
LinkedList folderList = new LinkedList<String>();
folderList.add(delfilefolder);
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
ArrayList<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
folderList = new LinkedList<String>();
folderList.add(delfilefolder);
while (folderList.size() > 0) {
File file = new File(folderList.getLast());
if (file.delete()) {
folderList.removeLast();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
delfilefolder.mkdir();
}
catch (Exception e) {
System.out.println("清空目錄操作出錯");
e.printStackTrace();
}

7.讀取文件
//import java.io.*;
// 逐行讀取數據
FileReader fr = new FileReader(%%1);
BufferedReader br = new BufferedReader(fr);
String %%2 = br.readLine();
while (%%2 != null) {
%%3
%%2 = br.readLine();
}
br.close();
fr.close();

8.寫入文件
//import java.io.*;
// 將數據寫入文件
try {
FileWriter fw = new FileWriter(%%1);
fw.write(%%2);
fw.flush();
fw.close(); 
} catch (IOException e) {
e.printStackTrace();
}

9.寫入隨機文件
//import java.io.*;
try {
RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");
long lg=logFile.length();
logFile.seek(%%2);
logFile.writeByte(%%3);
}catch(IOException ioe){
System.out.println("無法寫入文件:"+ioe.getMessage());
}

10.讀取文件屬性
//import java.io.*;
// 文件屬性的取得
File af = new File(%%1);
if (af.exists()) {
System.out.println(f.getName() + "的屬性如下: 文件長度為:" + f.length());
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目錄" : "不是目錄");
System.out.println(f.canRead() ? "可讀取" : "不");
System.out.println(f.canWrite() ? "是隱藏文件" : "");
System.out.println("文件夾的最后修改日期為:" + new Date(f.lastModified()));
} else {
System.out.println(f.getName() + "的屬性如下:");
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目錄" : "不是目錄");
System.out.println(f.canRead() ? "可讀取" : "不");
System.out.println(f.canWrite() ? "是隱藏文件" : "");
System.out.println("文件的最后修改日期為:" + new Date(f.lastModified()));
}
if(f.canRead()){
%%2
}
if(f.canWrite()){
%%3
}

11.寫入屬性
//import java.io.*;
File filereadonly=new File(%%1);
try {
boolean b=filereadonly.setReadOnly();
}
catch (Exception e) {
System.out.println("拒絕寫訪問:"+e.printStackTrace());
}

12.枚舉一個文件夾中的所有文件
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
List<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
%%2=f.getAbsoluteFile();
%%3
}
}

13.復制文件夾 
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String>folderList2 = new LinkedList<String>();
folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() + File.separator
+ file[i]);
} else {
temp = new File(folderList.peek() + File.separator
+ file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夾
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//System.out.println("復制整個文件夾內容操作出錯");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}

14.復制一個目錄下所有的文件夾到另一個文件夾下
/*
import java.io.*;
import java.util.*;
*/
File copyfolders=new File(%%1);
File[] copyfoldersList=copyfolders.listFiles();
for(int k=0;k<copyfoldersList.length;k++){
if(copyfoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(copyfoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+copyfoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator)){
temp=new File(folderList.get(j)+File.separator+file[i]);
}
else{
temp=new File(folderList.get(j)+File.separator+file[i]);
}
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileOutputStream output = new FileOutputStream(folderList2.get(j) + File.separator +
(temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夾
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("復制整個文件夾內容操作出錯");
e.printStackTrace();
}
}
}
}

15.移動文件夾
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String>folderList2 = new LinkedList<String>();
folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() + File.separator
+ file[i]);
} else {
temp = new File(folderList.peek() + File.separator
+ file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
if (!temp.delete())
//刪除單個文件操作出錯
}
if (temp.isDirectory()) {// 如果是子文件夾
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//復制整個文件夾內容操作出錯
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();

}
File f = new File(%%1);
if (!f.delete()) {
for (File file : f.listFiles()) {
if (file.list().length == 0) {
System.out.println(file.getPath());
file.delete();
}
}
}

16.移動一個目錄下所有的文件夾到另一個目錄下
/*
import java.io.*;
import java.util.*;
*/
File movefolders=new File(%%1);
File[] movefoldersList=movefolders.listFiles();
for(int k=0;k<movefoldersList.length;k++){
if(movefoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(movefoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+movefoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator)){
temp=new File(folderList.get(j)+File.separator+file[i]);
}
else{
temp=new File(folderList.get(j)+File.separator+file[i]);
}
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" +
(temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
temp.delete();
}
if(temp.isDirectory()){//如果是子文件夾
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
//復制整個文件夾內容操作出錯
e.printStackTrace();
}
}
movefoldersList[k].delete();
}
}

17.以一個文件夾的框架在另一個目錄創建文件夾和空文件
/*
import java.io.*;
import java.util.*;
*/
boolean b=false;//不創建空文件
List<String>folderList=new ArrayList<String>();
folderList.add(%%1);
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2);
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator)){
temp=new File(folderList.get(j)+File.separator+file[i]);
}
else{
temp=new File(folderList.get(j)+File.separator+file[i]);
}
if(temp.isFile()){
if (b) temp.createNewFile();
}
if(temp.isDirectory()){//如果是子文件夾
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
//復制整個文件夾內容操作出錯
e.printStackTrace();
}
}

18.復制文件
//import java.io.*;
int bytesum = 0;
int byteread = 0;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在時
FileInputStream inStream = new FileInputStream(oldfile); //讀入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[5120];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字節數 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
//復制單個文件操作出錯
e.printStackTrace();
}

19.復制一個目錄下所有的文件到另一個目錄
//import java.io.*;
File copyfiles=new File(%%1);
File[] files=copyfiles.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
int bytesum = 0;
int byteread = 0;
try {
InputStream inStream = new FileInputStream(files[i]); //讀入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName());
byte[] buffer = new byte[5120];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字節數 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
} catch (Exception e) {
//復制單個文件操作出錯
e.printStackTrace();
}
}
}

20.提取擴展名
String %%2=%%1.substring(%%1.lastIndexOf("."));

21.提取文件名
String %%2=%%1.substring(%%1.lastIndexOf("\\")+1);

22.提取文件路徑
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));

23.替換擴展名
//import java.io.*;
File replaceExt=new File(%%1);
replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);

24.追加路徑
final String path=%%1.endsWith("\\")?%%1:%%1+"\\";
%%3=path+%%2;

25.移動文件
//import java.io.*;
int bytesum = 0;
int byteread = 0;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在時
InputStream inStream = new FileInputStream(oldfile); //讀入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[5120];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字節數 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
oldfile.delete();
}
}
catch (Exception e) {
//復制單個文件操作出錯
e.printStackTrace();
}

26.移動一個目錄下所有文件到另一個目錄
//import java.io.*;
File movefile=new File(%%1);
File[] movefiles=movefile.listFiles();
for(int i=0;i<movefiles.length;i++){
if(movefiles[i].isFile()){
int bytesum = 0;
int byteread = 0;
File oldfile = new File(movefiles[i]);
try {
if (oldfile.exists()) { //文件存在時
InputStream inStream = new FileInputStream(oldfile); //讀入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[5120];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字節數 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
oldfile.delete();
}
}
catch (Exception e) {
//復制單個文件操作出錯
e.printStackTrace();
}
}
}

27.指定目錄下搜索文件
//import java.io.*;
private static final String filter=%%1; //"*.*"
private static void doSearch(String path){
File file = new File(path);
if(file.exists()) {
if(file.isDirectory()) {
File[] fileArray = file.listFiles();
for(File f:fileArray) {
if(f.isDirectory()) {
doSearch(f.getPath());
} else {
if(f.getName().indexOf(filter) >= 0) {
//f.getPath()
}
}
//f.getPath()
}
//"The numbers of files had been found:" + countFiles
} else {
//"Couldn't open the path!"
}
} else {
System.out.println("The path had been apointed was not Exist!");
}
}
doSearch(%%1);

28.打開對話框
/*
import java.io.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser(); //建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (Jfc.isFileSelectionEnabled()) {
File %%2 = Jfc.getSelectedFile();
}

29.文件分割
//import java.io.*;
try {
File f=new File(%%1);
FileInputStream fileInputStream = new FileInputStream(f);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
String strFileName = f.getName();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1"));
fileOutputStream.write(buffer,0,buffer.length/2);
fileOutputStream.close();
fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2"));
fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2);
fileOutputStream.close();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("using FileStreamDemo src des");
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

30.文件合並
//import java.io.*;
String strFileName = %%1.substring(%%1.LastIndexOf("\\") + 1);
try {
FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1"));
FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2"));
byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()];
FileInputStream.read(buffer, 0, fileInputStream1.available());
FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available());
fileInputStream.close();
fileInputStream2.close();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName));
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}

31.文件簡單加密
//import java.io.*;
try {
File f=new File((new File(%%1)).getPath()+"\\enc_"+(new File(%%1)).getName().split("//")[1]);
String strFileName = f.getName();
FileInputStream fileInputStream = new FileInputStream(%%2+"\\"+strFilename);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
for(int i=0;i<buffer.length;i++)
{
int ibt=buffer[i];
ibt+=100;
ibt%=256;
buffer[i]=(byte)ibt;
}
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(ArrayIndexOutOfBoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

32.文件簡單解密
//import java.io.*;
try {
File f=new File(%%1);
String strFileName = f.getName();
FileInputStream fileInputStream = new FileInputStream(%%2+"\\enc_"+strFilename);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
for(int i=0;i<buffer.length;i++)
{
int ibt=buffer[i];
ibt-=100;
ibt+=256;
ibt%=256;
buffer[i]=(byte)ibt;
}
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(ArrayIndexOutOfBoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

33.讀取ini文件屬性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*; 
private static HashMap configMap=null;
private static FileReader fileReader = null;
*/
private static boolean readIni() {
if (configMap == null) {
configMap = new HashMap<String, ArrayList>();
String strLine = null;
String currentNode = null;
String previousNode = null;
ArrayList<Properties>vec = new ArrayList<Properties>();
int row = 0;
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
while ((strLine = bufferedReader.readLine()) != null) {
String oneLine = strLine.trim();
if (oneLine.length() >= 1) {
Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
int nodelen = oneLine.split("[;]").length;
String[] strArray1 = new String[4];
if (nodelen == 1) {
oneLine = oneLine.split("[;]")[0].trim();
} else if (nodelen == 2) {
strArray1[3] = oneLine.split("[;]")[1].trim();
oneLine = oneLine.split("[;]")[0].trim();
}
Matcher m = p.matcher(oneLine);
if (m.matches()) {
strArray1[0] = "@Node";
strArray1[1] = oneLine;
strArray1[2] = "";
} else {
int keylen = oneLine.split("=").length;
if (keylen == 1) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = "";
} else if (keylen == 2) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = oneLine.split("=")[1];
} else {
strArray1[0] = "@ElementError";
strArray1[1] = "";
strArray1[2] = "";
strArray1[3] = "";
}
}
if (strArray1[0].equals("@Node")) {
previousNode = currentNode;
currentNode = strArray1[1];
if (row > 0) {
configMap.put(previousNode, (ArrayList)vec.clone());
vec.clear();
row = 0;
}
} else if (strArray1[0].equals("@Key") && row == 0) {
Properties ht = new Properties();
ht.setProperty(strArray1[1], strArray1[2]);
vec.add(ht);
row++;
} else if (strArray1[0].equals("@Key") && row > 0) {
Properties ht2 = new Properties();
ht2.put(strArray1[1], strArray1[2]);
vec.add(ht2);
row++;
}
}
}
configMap.put(currentNode, (ArrayList)vec.clone());
} catch (FileNotFoundException e) {
configMap = null;
e.printStackTrace();
return false;
} catch (IOException e) {
configMap = null;
e.printStackTrace();
return false;
}
}
return true;
}
try {
fileReader = new FileReader(%%1); //"Setup.ini"
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (readIni()) {
ArrayList<Properties>li = null;
li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
for (Properties pro : li) {
if(pro.containsKey(%%3))
%%4=pro.getProperty(%%3);
}
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}

34.合並一個目錄下所有的文件
//import java.io.*;
File combinefiles=new File(%%1);
File[] files=combinefiles.listFiles();
FileOutputStream fs;
try {
fs=new FileOutputStream(new File(%%2));
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
int bytesum=0;
int byteread=0;
try { 
FileInputStream inStream=new FileInputStream(files[i]);
byte[] buffer = new byte[5120];
while((byteread=inStream.read(buffer))!=-1){
bytesum+=byteread;
fs.write(buffer,0,byteread);
}
inStream.close();
}
catch(Exception e){
//復制文件出錯
e.printStackTrace();
}
}
}
try {
fs.close();
}
catch(IOException e){
e.printStackTrace();
}

35.寫入ini文件屬性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*; 
private static HashMap configMap=null;
*/
if (readIni()) {
ArrayList<Properties>li = null;
try {
FileWriter fw = new FileWriter("Setup.ini");
li = (ArrayList<Properties>) configMap.get("[DataSource]");
fw.write("[DataSource]\r\n");
for (Properties pro : li) {
if (pro.containsKey("ip"))
fw.write("ip=" + jt1.getText() + "\r\n");
else if (pro.containsKey("username"))
fw.write("username=" + username1 + "\r\n");
else if (pro.containsKey("password"))
fw.write("password=" + password1 + "\r\n");
else if (pro.containsKey("database"))
fw.write("database=" + database1 + "\r\n");
else if (pro.containsKey("table"))
fw.write("table=" + table1 + "\r\n");
}
li = (ArrayList<Properties>) configMap.get("[DataTarget]");
fw.write("\r\n[DataTarget]\r\n");
for (Properties pro : li) {
if (pro.containsKey("ip"))
fw.write("ip=" + jt2.getText() + "\r\n");
else if (pro.containsKey("username"))
fw.write("username=" + username2 + "\r\n");
else if (pro.containsKey("password"))
fw.write("password=" + password2 + "\r\n");
else if (pro.containsKey("database"))
fw.write("database=" + database2 + "\r\n");
else if (pro.containsKey("table"))
fw.write("table=" + table2 + "\r\n");
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

36.獲得當前路徑
String %%1=this.getClass().getResource("/").getPath();
//String %%1=System.getProperty("user.dir")

37.讀取XML數據庫
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
private static Document document;
private static Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
//%%2="Product" //%%4="id" //%%6="port"
//%%3="Name" //%%5="001"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = nlist.item(i);
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals(%%5)) {
nlist = node.getChildNodes();
String %%9=((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
break;
}
}

38.寫入XML數據庫
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
private Document document;
private Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
// %%2="Product" //%%4="pid" //%%6="author"
// %%3="Name" //%%5="price"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
String ss = null;
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = (Element) nlist.item(i);
//node.setAttribute(%%4, "0"+String.valueOf(i)); //ID格式化
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals("001")) {
nlist = node.getChildNodes();
ss = ((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().getNodeValue();
((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().setTextContent(%%7);
((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().setTextContent(%%8);
((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().setTextContent(%%9);
break;
}
}
if (ss == null) {
node = document.createElement(%%2);
node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1));
node.appendChild(document.createTextNode("\n"));
Element server = document.createElement(%%3);
server.appendChild(document.createTextNode(%%7));
node.appendChild(server);
Element ipNode = document.createElement(%%6);
ipNode.appendChild(document.createTextNode(%%8));
node.appendChild(ipNode);
node.appendChild(document.createTextNode("\n"));
Element port = document.createElement(%%5);
port.appendChild(document.createTextNode(%%9));
node.appendChild(port);
node.appendChild(document.createTextNode("\n"));
rootNode.appendChild(node);
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xml_file);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}

39.ZIP壓縮文件
/*
import java.io.*;
import java.util.zip.*;
*/
//創建文件輸入流對象
FileInputStream fis=new FileInputStream(%%1);
//創建文件輸出流對象
FileOutputStream fos=new FileOutputStream(%%2);
//創建ZIP數據輸出流對象
ZipOutputStream zipOut=new ZipOutputStream(fos);
//創建指向壓縮原始文件的入口
ZipEntry entry=new ZipEntry(args[0]);
zipOut.putNextEntry(entry);
//向壓縮文件中輸出數據
int nNumber;
byte[] buffer=new byte[1024];
while((nNumber=fis.read(buffer))!=-1)
zipOut.write(buffer,0,nNumber);
//關閉創建的流對象
zipOut.close();
fos.close();
fis.close();
}
catch(IOException e) 
{
System.out.println(e);
}

40.ZIP解壓縮
/*
import java.io.*;
import java.util.zip.*;
*/
try{
//創建文件輸入流對象實例
FileInputStream fis=new FileInputStream(%%1);
//創建ZIP壓縮格式輸入流對象實例
ZipInputStream zipin=new ZipInputStream(fis);
//創建文件輸出流對象實例
FileOutputStream fos=new FileOutputStream(%%2);
//獲取Entry對象實例
ZipEntry entry=zipin.getNextEntry();
byte[] buffer=new byte[1024];
int nNumber;
while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
fos.write(buffer,0,nNumber);
//關閉文件流對象
zipin.close();
fos.close();
fis.close();
}
catch(IOException e) {
System.out.println(e);
}

41.獲得應用程序完整路徑
String %%1=System.getProperty("user.dir");

42.遞歸刪除目錄中的文件
/*
import java.io.*;
import java.util.*;
*/
ArrayList<String>folderList = new ArrayList<String>();
folderList.add(%%1);
for (int j = 0; j < folderList.size(); j++) {
File file = new File(folderList.get(j));
File[] files = file.listFiles();
ArrayList<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}

43.ZIP壓縮文件夾
/*
import java.io.*;
import java.util.*;
import java.util.zip.*;
*/
public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {
ArrayList fileNames = new ArrayList();
ArrayList files = new ArrayList();
FileOutputStream fileOut = null;
ZipOutputStream outputStream = null;
FileInputStream fileIn = null;
StringBuffer sb = new StringBuffer(outputZipNameAndPath);
// FileInputStream fileIn =null;
try {
if (outputZipNameAndPath.indexOf(".zip") != -1) {
outputZipNameAndPath = outputZipNameAndPath;
} else {
sb.append(".zip");
outputZipNameAndPath = sb.toString();
}
fileOut = new FileOutputStream(outputZipNameAndPath);
outputStream = new ZipOutputStream(fileOut);
int outputZipFileNameListSize = 0;
if (outputZipFileNameList != null) {
outputZipFileNameListSize = outputZipFileNameList.size();
}
for (int i = 0; i < outputZipFileNameListSize; i++) {
File rootFile = new File(outputZipFileNameList.get(i).toString());
listFile(rootFile, fileNames, files, "");
}
for (int loop = 0; loop < files.size(); loop++) {
fileIn = new FileInputStream((File) files.get(loop));
outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
outputStream.write(buffer);
}
outputStream.closeEntry();
fileIn.close();
}
return outputZipNameAndPath;
} catch (IOException ioe) {
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
}
}
private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int loop = 0; loop < files.length; loop++) {
listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");
}
} else {
fileList.add(parentFile);
nameList.add(directoryName + parentFile.getName());
}
}
ArrayList outputZipFileName=new ArrayList();
String savePath="";
int argSize = 0;
savePath = %%1;
outputZipFileName.add(%%2);
ZipFileOther instance=new ZipFileOther();
instance.zipFileProcess(outputZipFileName,savePath);

44.驗證DTD
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
*/
File xml_dtd = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_dtd);
//進行dtd檢查 
factory.setValidating(true); 
} catch (Exception e) {
e.printStackTrace();
}

45.驗證Schema
/*
import javax.xml.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import org.xml.sax.*;
*/
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource ss = new StreamSource(%%1); //"mySchema.xsd"
try {
Schema schema = factory.newSchema(ss);
} catch (SAXException e) {
e.printStackTrace();
}

46.Grep
/*
import java.util.regex.*;
import java.io.*;
*/
throws Exception
Pattern pattern = Pattern.compile(%%1); // 第一個參數為需要匹配的字符串 
Matcher matcher = pattern.matcher("");
String file = %%2;
BufferedReader br = null; 
String line; 
try { 
br = new BufferedReader (new FileReader (file)); // 打開文件 
} catch (IOException e) { 
// 沒有打開文件,則產生異常 
System.err.println ("Cannot read '" + file 
+ "': " + e.getMessage());
}
while ((line = br.readLine()) != null) { // 讀入一行,直到文件結束 
matcher.reset (line); // 匹配字符串 
if (matcher.find()) { // 如果有匹配的字符串,則輸出 
System.out.println (file + ": " + line); 


br.close(); // 關閉文件

47.直接創建多級目錄
//import java.io.*; 
File f=new File(%%1);
f.mkdirs();

48.批量重命名
//import java.io.*;
File target = new File("%%1");
String[] files = target.list();
File f = null;
String filename = null;
for (String file : files) {
f = new File(target, file);
filename = f.getName();
if (filename.substring(filename.lastIndexOf(".")).equalsIgnoreCase(
"%%2")) {
f.renameTo(new File(target.getAbsolutePath(), filename.replace(
"%%2", "%%3")));
// 這里可以反復使用replace替換,當然也可以使用正則表達式來替換了 ".txt" ".bat"
}
}

49.文本查找替換
//import java.nio.*;
String s1=%%1;
String s2=%%2;
String s3=%%3;
int pos=%%4;
/*變量i和j分別表示主串和模式串中當前字符串的位置,k表示匹配次數*/
int i,j,k=0;
i = pos;
j = 0;
//將s1轉化成StringBuffer型進行操作
repStr = new StringBuffer(s1);
while(i<repStr.length()&&j<s2.length())
{
if(repStr.charAt(i) == s2.charAt(j))
{
++i; ++j;
if(j==s2.length())
{
/*j=s2.length()表示字符串匹配成功,匹配次數加1,此外對主串進行字符串替換*/
k = k+1;
repStr.replace(i-j,i,s3);
//將j進行重新賦值開始新的比較
j = 0;
}
}
else {i = i-j+1; j = 0;}
}
return k;

50.文件關聯
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]" 
} catch (IOException e) {
e.printStackTrace();
}

51.操作Excel文件
//http://sourceforge.net/projects/poi/
import java.io.*;
import org.apache.poi.hpsf.*;
import org.apache.poi.poifs.eventfilesystem.*;
static class MyPOIFSReaderListener
     implements POIFSReaderListener
{
public void processPOIFSReaderEvent(POIFSReaderEvent event)
{
SummaryInformation si = null;
try
{
si = (SummaryInformation)
PropertySetFactory.create(event.getStream());
}
catch (Exception ex)
{
throw new RuntimeException
("屬性集流\"" + event.getPath() +
event.getName() + "\": " + ex);
}

final String title = si.getTitle();

if (title != null)
System.out.println("標題: \"" + title + "\"");
else
System.out.println("該文檔沒有標題.");
}
}
String filename = %%1;
POIFSReader r = new POIFSReader();
r.registerListener(new MyPOIFSReaderListener(),
"\005SummaryInformation");
r.read(new FileInputStream(filename));

利用Servlet創建和返回一個工作簿。

package org.apache.poi.hssf.usermodel.examples;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.poi.hssf.usermodel.*;

public class HSSFCreate extends HttpServlet {
public void init(ServletConfig config)
   throws ServletException {
super.init(config); 
}

public void destroy() {
}

/** 處理HTTP GET 和POST請求
* @param request:請求
* @param response:應答
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
     throws ServletException, IOException {

response.setContentType("application/vnd.ms-excel");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");

// 創建一個新的行,添加幾個單元格。
// 行號從0開始計算
HSSFRow row = sheet.createRow((short)0);
// 創建一個單元格,設置單元格的值
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(1);

row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("一個字符串值");
row.createCell((short)3).setCellValue(true);
// 寫入輸出結果
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
}

/** 處理HTTP GET請求
* @param request:請求
* @param response:應答
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
     throws ServletException, IOException {
processRequest(request, response);
}

/** 處理HTTP POST請求
* @param request:請求
* @param response:應答
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
     throws ServletException, IOException {
processRequest(request, response);
}

/** 返回關於Servlet的簡單說明
*/
public String getServletInfo() {
return "示例:在Servlet中用HSSF創建Excel工作簿";
}
}


一, 建立Excel工作薄
HSSFWorkbook wb = new HSSFWorkbook();

二, 建立Excel工作表,每個工作表對應的是Excel界面左下角的一個標簽sheet1,sheet2 …
HSSFSheet sheet1 = wb.createSheet("new sheet");

三, 在工作表中建立單元格

//首先,建立行對像,行號作為參數傳給createRow方法,第一行由0開始計算。
HSSFRow row = sheet.createRow((short)0);

//建單元格
HSSFCell cell = row.createCell((short)0);

//給單元格賦值
cell.setCellValue(1);

//也可同一行內完成建立單元格和賦值
row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("This is a string");
row.createCell((short)3).setCellValue(true);

//數據格式可通過創建單元格值時默認如上面所視
//也可以創建單元格后調用setCellType指定
cell.setCellType(CELL_TYPE_NUMERIC);

四, 向單元格插入日期值
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");

// 可通過Sheet.setSheetName(sheetindex,"SheetName",encoding)設定工作表名

// 創建新行並向其加入單元格,行號由0開始。
HSSFRow row = sheet.createRow((short)0);

// 創建一個單元格並向其輸入一日期值,但這第一個單元格並非是日期格式。
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(new Date());

// 我們將這第二個單元格改成日期格式,這需要從工作薄創建一個新的單元格格式,這可// 以只影響當前建立的一個單元格。
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell = row.createCell((short)1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

五, 各種單元格樣式
HSSFCellStyle cellStyle = wb.createCellStyle();
//對齊
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

//帶邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

//顏色與填充樣式
cellStyle.setFillBackgroundColor(HSSFColor.AQUA.index);
cellStyle.setFillPattern(HSSFCellStyle.BIG_SPOTS);
cellStyle.setFillForegroundColor(HSSFColor.ORANGE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

六, 行高,列寬。
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);

//2是行高值
row.setRowHeight(2);

//3是列號,4是列寬值
sheet.setColumnWidth(3, 4);


//建工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//建名為example的工作表
HSSFSheet sheet = wb.createSheet("example");
//給工作表前8列定義列寬
sheet.setColumnWidth((short)0,(short)2500);
sheet.setColumnWidth((short)1,(short)6000);
sheet.setColumnWidth((short)2,(short)3500);
sheet.setColumnWidth((short)3,(short)9000);
sheet.setColumnWidth((short)4,(short)8000);
sheet.setColumnWidth((short)5,(short)8000);
sheet.setColumnWidth((short)6,(short)20000);
sheet.setColumnWidth((short)7,(short)8000);
//在表中建行
HSSFRow row = sheet.createRow(0);
//建立單元格 
HSSFCell cell[] = new HSSFCell[8];
for (short i = 0; i < 8; i++) {
cell = row.createCell(i);
//將單元格定義成UTF_16編碼,這樣才能使輸出數據不會亂碼
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
}
//寫單元格標題
cell[0].setCellValue("登記ID");
cell[1].setCellValue("登記號");
cell[2].setCellValue("所在地市ID");
cell[3].setCellValue("產品中文名");
cell[4].setCellValue("產品英文名");
cell[5].setCellValue("產品服務對象");
cell[6].setCellValue("產品功能描述");
cell[7].setCellValue("產品類別");
//查詢數據庫,取得數據列表的List實例
List list = new ArrayList();
ProductDataManager mgr = new ProductDataManager();
try {
list = mgr.listProductQuery("","", "", "", "", "1999-2-1", "2004-2-1");
} catch (SrrdException e) {
e.printStackTrace(); 
}
//從List中取出數據放入工作表中
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size() - 1; i++) {
ProductQuery query = (ProductQuery) list.get(i);
HSSFRow datarow = sheet.createRow(i + 1);
HSSFCell data[] = new HSSFCell[8];
for (short j = 0; j < 8; j++) {
data[j] = datarow.createCell(j);
//將單元格定義成UTF_16編碼,這樣才能使輸出數據不會亂碼
data[j].setEncoding(HSSFCell.ENCODING_UTF_16);
}
data[0].setCellValue(query.getCertId());
data[1].setCellValue(query.getCertNum());
data[2].setCellValue(query.getCityCode());
data[3].setCellValue(query.getSoftWareCname());
data[4].setCellValue(query.getSoftWareEname());
data[5].setCellValue(query.getSoftwareFor());
data[6].setCellValue(query.getSoftwareFuncDesc());
data[7].setCellValue(query.getSoftwareType());
}
}
//將工作薄輸出到輸出流
ServletOutputStream sos=response.getOutputStream();
wb.write(sos);
sos.close();

//也可輸出成xls文件
File file = new File("workbook.xls");
try {
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace(); 
}


52.設置JDK環境變量
@echo off 
IF EXIST %1\bin\java.exe ( 
rem 如輸入正確的 Java2SDK 安裝目錄,開始設置環境變量 
@setx JAVA_HOME %1 
@setx path %path%;%JAVA_HOME%\bin 
@setx classpath %classpath%;. 
@setx classpath %classpath%;%JAVA_HOME%\lib\tools.jar 
@setx classpath %classpath%;%JAVA_HOME%\lib\dt.jar 
@setx classpath %classpath%;%JAVA_HOME%\jre\lib\rt.jar 
@echo on 
@echo Java 2 SDK 環境參數設置完畢,正常退出。 
) ELSE ( 
IF "%1"=="" ( 
rem 如沒有提供安裝目錄,提示之后退出
@echo on
@echo 沒有提供 Java2SDK 的安裝目錄,不做任何設置,現在退出環境變量設置。
) ELSE (
rem 如果提供非空的安裝目錄但沒有bin\java.exe,則指定的目錄為錯誤的目錄
@echo on
@echo 非法的 Java2SDK 的安裝目錄,不做任何設置,現在退出環境變量設置。
)
)
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*;
//import java.util.*;
1.打開鍵
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
2.添加鍵
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); 
r.create(); 
9.寫入字符串值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data");
r.setValue(v);
6.獲取DWORD值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); 
if(r.hasValue("myValue")) { 
RegistryValue v = r.getValue("myValue"); 
v.setType(ValueType.REG_DWORD);
} // if


53.選擇文件夾對話框
/*
import java.io.*;
import javax.swing.*;
*/
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".gif")
|| f.isDirectory();
}
public String getDescription() {
return "GIF Images";
}
});
int r = chooser.showOpenDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getPath();
// label.setIcon(new ImageIcon(name));
}

54.刪除空文件夾
//import java.io.*;
File f=new File(%%1);
if (isFolerNull(f)) { 
for (File file :f.listFiles()) { 
if (file.list().length == 0) { 
System.out.println(file.getPath()); 
file.delete(); 
}
}
}

55.發送數據到剪貼板
/*
import java.awt.*;
import java.awt.datatransfer.*;
*/
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(%%1);
clipboard.setContents(tText, null);

56.從剪貼板中取數據
/*
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
*/
// 取得系統剪貼板里可傳輸的數據構造的Java對象 
Transferable t = Toolkit.getDefaultToolkit() 
.getSystemClipboard().getContents(null); 
try { 
if (t != null 
&& t.isDataFlavorSupported(DataFlavor.stringFlavor)) { 
// 因為原系的剪貼板里有多種信息, 如文字, 圖片, 文件等 
// 先判斷開始取得的可傳輸的數據是不是文字, 如果是, 取得這些文字

String %%1 = (String) t 
.getTransferData(DataFlavor.stringFlavor); 
// 同樣, 因為Transferable中的DataFlavor是多種類型的, 
// 所以傳入DataFlavor這個參數, 指定要取得哪種類型的Data.

} catch (UnsupportedFlavorException ex) { 
ex.printStackTrace(); 
} catch (IOException ex) { 
ex.printStackTrace(); 
}

57.獲取文件路徑的父路徑
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));

58.創建快捷方式
//import java.io.*; 
try {
PrintWriter pw=new PrintWriter(new FileOutputStream("C:/a.bat")); 
pw.println(%%1);"C:/a.txt"
pw.close(); 
}
catch(IOException e){
e.printStackTrace();
}

59.彈出快捷菜單
//MouseEvent e
JPopupMenu jpm=new JPopupMenu();
show(jpm,x,y);

60.文件夾復制到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc.showDialog(null, %%1);
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String>folderList2 = new LinkedList<String>();
folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() + File.separator
+ file[i]);
} else {
temp = new File(folderList.peek() + File.separator
+ file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夾
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//System.out.println("復制整個文件夾內容操作出錯");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}

61.文件夾移動到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

62.目錄下所有文件夾復制到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc.showDialog(null, %%1);
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

63.目錄下所有文件夾移動到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

64.目錄下所有文件復制到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

65.目錄下所有文件移動到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

66.對目標壓縮文件解壓縮到指定文件夾
/*
import java.io.*;
import java.util.zip.*;
*/
String zipFileName=%%1;
String extPlace=%%2;
File myFolderPath = new File(extPlace);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
//新建目錄操作出錯
e.printStackTrace();
return;
}
try {
ZipInputStream in = new ZipInputStream(new FileInputStream(
zipFileName));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String entryName = entry.getName();
File file = new File(extPlace , entryName);
if (entry.isDirectory()) {
file.mkdirs();
} else {
FileOutputStream os = new FileOutputStream(file);
// Transfer bytes from the ZIP file to the output
// file
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
in.closeEntry();
}
}
} catch (IOException e) {
e.printStackTrace();
}

67.創建目錄副本整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("請選擇源路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("請選擇目標路徑"); // 建立選擇檔案對話方塊盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

68.打開網頁
//import java.io.*;
try{ 
String command = "C:\\Program Files\\Internet Explorer\\Iexplore.exe "+%%1;
Runtime.getRuntime().exec(command);
} catch (IOException ex) {
ex.printStackTrace();
}

69.刪除空文件夾整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/

70.獲取磁盤所有分區后再把光驅盤符去除(用"\0"代替),把結果放在數組allfenqu[] 中,數組中每個元素代表一個分區盤符,不包括 :\\ 這樣的路徑,allfenqu[]數組開始時存放的是所有盤符。 
當我用這樣的代碼測試結果是正確的,光驅盤符會被去掉: 
String root; //root代表盤符路徑 
for(i=0;i<20;i++) //0-20代表最大的盤符數 

root.Format("%c:\\",allfenqu[i]); 
if(GetDriveType(root)==5) 
allfenqu[i]='\0'; 
}

但我用這樣的代碼時結果卻無法去掉光驅盤符,allfenqu[]中還是會包含光驅盤符:
String root;
for(i=0;i<20;i++)
{
root=allfenqu[i]+":\\";
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}

71.激活一個程序或程序關聯的文件
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1);
} catch (IOException e) {
e.printStackTrace();
}

72.HTTP下載
/*
import java.io.*;
*/
public class DownloadCSVFileAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
try { 
String fileName = request.getParameter( "fileName ");
long maID = Long.parseLong(request.getParameter( "maID "));
String filePath = request.getSession().getServletContext ().getRealPath( "/ ")+ "csv/ "+maID+ "/ "+fileName;
File fdown = new File(filePath);
int filelength = Integer.parseInt(String.valueOf(fdown.length())); 
//下載類型
response.setContentType( "application/text;charset=GB2312 ");
response.setHeader( "Content-Dispositon ", "attachment;filename=銷售詳細記錄.csv "); //銷售詳細記錄.csv是我想要的下載文件的文件名,但是下載對話框中顯示的是 downLoadCSVFile.do
response.setContentLength(filelength);
byte b[]=new byte[filelength];
FileInputStream fi=new FileInputStream(fdown);
OutputStream o=response.getOutputStream();
int n = 0;
while((n=fi.read(b))!=-1) {
o.write(b,0,n);
}
fi.close();
o.close();
return null;
}catch (Exception e) {
request.setAttribute( "ERROR ", e);
return mapping.findForward( "error ");
}
}
}

對應的下載類型
private String getContentType(String fileName) {
String fileNameTmp = fileName.toLowerCase();
String ret = "";
if (fileNameTmp.endsWith("txt")) {
ret = "text/plain";
}
if (fileNameTmp.endsWith("gif")) {
ret = "image/gif";
}
if (fileNameTmp.endsWith("jpg")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("jpeg")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("jpe")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("zip")) {
ret = "application/zip";
}
if (fileNameTmp.endsWith("rar")) {
ret = "application/rar";
}
if (fileNameTmp.endsWith("doc")) {
ret = "application/msword";
}
if (fileNameTmp.endsWith("ppt")) {
ret = "application/vnd.ms-powerpoint";
}
if (fileNameTmp.endsWith("xls")) {
ret = "application/vnd.ms-excel";
}
if (fileNameTmp.endsWith("html")) {
ret = "text/html";
}
if (fileNameTmp.endsWith("htm")) {
ret = "text/html";
}
if (fileNameTmp.endsWith("tif")) {
ret = "image/tiff";
}
if (fileNameTmp.endsWith("tiff")) {
ret = "image/tiff";
}
if (fileNameTmp.endsWith("pdf")) {
ret = "application/pdf";
}
return ret;
}

73.FTP下載
/*
import sun.net.ftp.FtpClient;
import java.io.*;
import sun.net.*;
*/
//如果文件在某個目錄下,則加入fc.cd("foodir");
//比如要下載ftp://ftp.xx.com/index.html則:
try
{
FtpClient fc=new FtpClient("ftp.xx.com");
fc.login("username","888888");
int ch;
File fi = new File("c:\\index.html");
RandomAccessFile getFile = new RandomAccessFile(fi,"rw");
getFile.seek(0);
TelnetInputStream fget=fc.get("index.html");
DataInputStream puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
fget.close();
getFile.close();
fc.closeServer();
}
catch (IOException ex)
{

ex.printStackTrace();
}

74.寫圖像到剪切板 setClipboardImage
/*
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
private final Image image;
*/
Transferable trans = new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}

public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}

public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
return image;
throw new UnsupportedFlavorException(flavor);
}
};
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
null);

75.從剪貼板復制圖像到窗體

76.刪除文件夾下的所有文件且不刪除文件夾下的文件夾
//import java.io.*;
//import java.util.*;
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
ArrayList<File>fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}

78.拷貝文件名復制文件
package p1;
import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
public class VCFileCopy {
public static void main(String[] args) {
// TODO Auto-generated method stub
//
// 取得系統剪貼板里可傳輸的數據構造的Java對象
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
.getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// 因為原系的剪貼板里有多種信息, 如文字, 圖片, 文件等
// 先判斷開始取得的可傳輸的數據是不是文字, 如果是, 取得這些文字

String s = (String) t.getTransferData(DataFlavor.stringFlavor);
// 同樣, 因為Transferable中的DataFlavor是多種類型的,
// 所以傳入DataFlavor這個參數, 指定要取得哪種類型的Data.
System.out.println(s);
int bytesum = 0;
int byteread = 0;
File oldfile = new File(s);
try {
if (oldfile.exists()) { // 文件存在時
FileInputStream inStream = new FileInputStream(oldfile); // 讀入原文件
FileOutputStream fs = new FileOutputStream(new File(
"C:\\"
,
oldfile.getName()));
byte[] buffer = new byte[5120];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字節數 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("復制單個文件操作出錯");
e.printStackTrace();
}
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

79.開源程序庫Xercesc-C++代碼工程中內聯
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class InlineXercesc {
private final String filter = ".cpp";

private ArrayList<String> all = new ArrayList<String>();

private LinkedList<String> fal2 = new LinkedList<String>();

private static String CurDir = System.getProperty("user.dir");

private void doSearch(String path) {
File filepath = new File(path);
if (filepath.exists()) {
if (filepath.isDirectory()) {
File[] fileArray = filepath.listFiles();
for (File f : fileArray) {
if (f.isDirectory()) {
doSearch(f.getPath());
} else {
if (f.getName().indexOf(filter) >= 0) {
for (String file : all) {
if (file.substring(file.lastIndexOf("\\") + 1)
.equals(f.getName())) {
fal2.add(f.getAbsolutePath());
}
}
}
}
}
} else {
System.out.println("Couldn't open the path!");
}
} else {
System.out.println("The path had been apointed was not Exist!");
}
}

public InlineXercesc(String lib) throws IOException {
String SourceLib = "D:\\Desktop\\大項目\\xerces-c-3.0.1\\src";
Pattern pattern = Pattern.compile("include.*?" + lib + ".*?>"); // 第一個參數為需要匹配的字符串
Matcher matcher = pattern.matcher("");
LinkedList<String>fal = new LinkedList<String>();
File delfile = new File(CurDir);
File[] files2 = delfile.listFiles();
for (int l = 0; l < files2.length; l++) {
if (files2[l].isDirectory()) {
String enumDir = CurDir + "\\" + files2[l].getName() + "\\";
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(files2[l].getAbsolutePath());
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
String fileStr = files[i].getAbsolutePath(); // 第2個參數開始,均為文件名。
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(fileStr)); // 打開文件
} catch (IOException e) {
// 沒有打開文件,則產生異常
System.err.println("Cannot read '" + fileStr
+ "': " + e.getMessage());
continue;
}
StringBuilder sb = new StringBuilder(2048);
while ((line = br.readLine()) != null) { // 讀入一行,直到文件結束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,則輸出
sb.append(line.replace(
line.substring(line.indexOf("<"),
line.lastIndexOf("/") + 1),
"\"").replace('>', '\"'));
line = line.substring(
line.indexOf("<") + 1,
line.lastIndexOf(">")).replace('/',
'\\');
fal.add(SourceLib + "\\" + line);
} else {
sb.append(line);
}
sb.append("\r\n");
}
br.close(); // 關閉文件
FileWriter fw2 = new FileWriter(fileStr);
fw2.write(sb.toString());
fw2.flush();
fw2.close();
}
}
}
while (fal.size() > 0) {
String file = fal.poll(); // 第2個參數開始,均為文件名。
String targetPath = enumDir
+ file.substring(file.lastIndexOf("\\") + 1);
if (!new File(targetPath).exists()) {
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(file)); // 打開文件
} catch (IOException e) {
// 沒有打開文件,則產生異常
System.err.println("Cannot read '" + file + "': "
+ e.getMessage());
continue;
}
FileWriter fw = new FileWriter(targetPath);
while ((line = br.readLine()) != null) { // 讀入一行,直到文件結束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,則輸出
fal.add(SourceLib
+ "\\"
+ line.substring(line.indexOf("<") + 1,
line.lastIndexOf(">")).replace(
'/', '\\'));
line = line.replace(line.substring(line
.indexOf("<"),
line.lastIndexOf("/") + 1), "\"");
line = line.replace(">", "\"");

}
fw.write(line + "\r\n");
}
fw.flush();
fw.close();
br.close(); // 關閉文件

}
}
LinkedList<String>folderListArr = new LinkedList<String>();
folderListArr.add(CurDir);
while (folderListArr.size() > 0) {
File file = new File(folderListArr.poll());
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderListArr.add(files[i].getPath());
} else {
if (files[i].getName().substring(
files[i].getName().lastIndexOf("."))
.equals(".hpp"))
all.add(files[i].getAbsoluteFile().toString()
.replace(".hpp", ".cpp"));
}
}
}
int count = 1;
while (count > 0) {
doSearch(SourceLib);
all.clear();
while (fal2.size() > 0) {
String file1 = fal2.poll(); // 第2個參數開始,均為文件名。
String targetPath = enumDir
+ file1.substring(file1.lastIndexOf("\\") + 1);
if (!new File(targetPath).exists()) {
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(file1)); // 打開文件
} catch (IOException e) {
// 沒有打開文件,則產生異常
System.err.println("Cannot read '" + file1
+ "': " + e.getMessage());
continue;
}
FileWriter fw;
try {
fw = new FileWriter(targetPath);
while ((line = br.readLine()) != null) { // 讀入一行,直到文件結束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,則輸出
fal2.add(SourceLib
+ "\\"
+ line.substring(
line.indexOf('<') + 1,
line.lastIndexOf('>'))
.replace('/', '\\'));
all.add(fal2.getLast().replace(".hpp",
".cpp"));
line = line.replace(line.substring(line
.indexOf('<'), line
.lastIndexOf('/') + 1), "\"");
line = line.replace('>', '\"');
}
fw.write(line + "\r\n");
}
fw.flush();
fw.close();
br.close(); // 關閉文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
count = all.size();
}
}
}
}

public static void main(String[] args) {
try {
new InlineXercesc("xercesc");
// 將數據寫入文件
try {
FileWriter fw = new FileWriter(CurDir + "\\DetailCpp.cmd");
fw.write("copy StdAfx.cpp+*.c+*.cpp " + CurDir
+ "\\StdAfx.cpp && del *.c && del *.cpp");
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
}
}
}

80.提取包含頭文件列表
import java.io.*;
import java.util.regex.*;
import java.util.*;
public class InlineExt {
private String CurDir = System.getProperty("user.dir");
public InlineExt() {
Pattern pattern = Pattern.compile("include.*?\".*?.hpp\""); // 第一個參數為需要匹配的字符串
Matcher matcher = pattern.matcher("");
File delfile = new File(CurDir);
File[] files2 = delfile.listFiles();
for (int l = 0; l < files2.length; l++) {
if (files2[l].isDirectory()) {
Set<String>ts = new LinkedHashSet<String>();
File file = new File(files2[l].getPath(), "StdAfx.cpp");
BufferedReader br = null;
FileWriter fw = null;
String line;
try {
br = new BufferedReader(new FileReader(file)); // 打開文件
while ((line = br.readLine()) != null) {
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,則輸出
ts.add(line.substring(line.indexOf('\"') + 1, line
.lastIndexOf('\"')));
}
}
Iterator<String>it = ts.iterator();
File file2 = new File(files2[l], "ReadMe.txt");
if (file2.exists()) {
fw = new FileWriter(file2);
while (it.hasNext()) {
fw.write("#include \"" + it.next() + "\"\r\n");
}
}
} catch (IOException e) {
// 沒有打開文件,則產生異常
System.err.println("Cannot read '" + file + "': "
+ e.getMessage());
continue;
} finally {
try {
if (br != null)
br.close();
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new InlineExt();
}
}

81.剪貼扳轉換成打印字符
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
public class ClipBoard {
public static void main(String[] args) {
// 取得系統剪貼板里可傳輸的數據構造的Java對象 
Transferable t = Toolkit.getDefaultToolkit() 
.getSystemClipboard().getContents(null); 
try { 
if (t != null 
&& t.isDataFlavorSupported(DataFlavor.stringFlavor)) { 
// 因為原系的剪貼板里有多種信息, 如文字, 圖片, 文件等 
// 先判斷開始取得的可傳輸的數據是不是文字, 如果是, 取得這些文字 
String s = (String) t 
.getTransferData(DataFlavor.stringFlavor); 
String[]arr=s.split("\n");
StringBuilder sb=new StringBuilder(1024);
for(String ss:arr) {
if(!ss.trim().equals("")){
sb.append("w.WriteLine(\"ECHO " + ss.replace("^", "^^").replace("&", "^&").replace(":", "^:").replace(">", "^>").replace("<", "^<").replace("|", "^|").replace("\"", "^\"").replace("\\", "\\\\").replace("\"", "\\\"") + "\");");
sb.append("\r\n");
}
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(sb.toString());
clipboard.setContents(tText, null);

} catch (UnsupportedFlavorException ex) { 
ex.printStackTrace(); 
} catch (IOException ex) { 
ex.printStackTrace(); 
}
}
}

82.把JButton或JTree組件寫到一個流中
/*
由於JButton和JTree都已經實現了Serializable接口,因此你所說的問題是可以做到的。
使用ObjectInputStream讀取文件中的對象,使用ObjectOutputStream把對象寫入文件。如:
*/
/*
import java.io.*;
import javax.swing.*;
*/
public class Save {
public static void main(String[] args) {

// Write
JButton button = new JButton("TEST Button");
JTree tree = new JTree();
try {
ObjectOutputStream outForButton = new ObjectOutputStream(
new FileOutputStream("button"));
outForButton.writeObject(button);
outForButton.close();
ObjectOutputStream outForTree = new ObjectOutputStream(
new FileOutputStream("tree"));
outForTree.writeObject(tree);
outForTree.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read

try {
ObjectInputStream inForButton = new ObjectInputStream(
new FileInputStream("button"));
JButton buttonReaded = (JButton) inForButton.readObject();

ObjectInputStream inForTree = new ObjectInputStream(
new FileInputStream("tree"));
JTree treeReaded = (JTree) inForTree.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

83.注冊全局熱鍵
//http://hi.baidu.com/ekou/blog/item/81cd52087a305bd463d986e4.html
//http://www.blogjava.net/Files/walsece/jintellitype.rar
//http://commons.apache.org/logging/
commons-loggins.jar


所謂系統級熱鍵就是指一組快捷鍵,不論當前系統焦點在哪個程序中,只要按下該鍵,程序就能夠捕捉該事件並進行相關處理。該功能在應用程序中是非常有用的,比如系統自帶的 “win+L”自動鎖屏,QQ中默認的“ctrl+alt+Z”自動打開當前的消息窗口等等。 Java中的事件監聽機制雖然功能強大,但是當系統焦點脫離該程序時也無能為力。要實現該功能必須調用系統的鈎子函數,因此在java中也必須通過jni調用來實現,但是對於不熟悉系統函數或者其他編成語言的朋友來說卻是個難題。 以前實現類似的功能都是自己通過c調用系統的鈎子函數然后再通過jni調用,自己寫的東西只要能滿足簡單的需求即可,因此功能和程序結構也比較簡單。后來在國外的一個網站上發現了一個組件“jintellitype”幫我們封裝了絕大部分的功能,而且結構上也采用java中的事件監聽機制,我們只要在程序中通過注冊即可實現,下面是一個簡單的例子:

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;

public class HotKey implements HotkeyListener {
static final int KEY_1 = 88;
static final int KEY_2 = 89;
static final int KEY_3 = 90;

/**
* 該方法負責監聽注冊的系統熱鍵事件

* @param key:觸發的熱鍵標識
*/
public void onHotKey(int key) {
switch (key) {
case KEY_1:
System.out.println("ctrl+alt+I 按下.........");
break;
case KEY_2:
System.out.println("ctrl+alt+O 按下.........");
break;
case KEY_3:
System.out.println("系統退出..........");
destroy();
}

}

/**
* 解除注冊並退出
*/
void destroy() {
JIntellitype.getInstance().unregisterHotKey(KEY_1);
JIntellitype.getInstance().unregisterHotKey(KEY_2);
JIntellitype.getInstance().unregisterHotKey(KEY_3);
System.exit(0);
}

/**
* 初始化熱鍵並注冊監聽事件
*/
void initHotkey() {
// 參數KEY_1表示改組熱鍵組合的標識,第二個參數表示組合鍵,如果沒有則為0,該熱鍵對應ctrl+alt+I
JIntellitype.getInstance().registerHotKey(KEY_1,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'I');
JIntellitype.getInstance().registerHotKey(KEY_2,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'O');
JIntellitype.getInstance().registerHotKey(KEY_3,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'X');

JIntellitype.getInstance().addHotKeyListener(this);
}

public static void main(String[] args) {
HotKey key = new HotKey();
key.initHotkey();

// 下面模擬長時間執行的任務
while (true) {
try {
Thread.sleep(10000);
} catch (Exception ex) {
break;
}
}
}
}

偶爾,我們可以給用戶添加一些快捷鍵,不管現在焦點在哪里。

有個做法就是,任何組建上注冊你的監聽器,但顯然,這不是一個好做法

java的toolkit可以直接添加一個監聽器,

一下就是示例

Toolkit toolkit = Toolkit.getDefaultToolkit();

toolkit.addAWTEventListener(capListener, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK| AWTEvent.WINDOW_EVENT_MASK);

實現一個監聽器:

class CapListener implements AWTEventListener {

public void eventDispatched(AWTEvent event) {

}

}
這就可以了

84.菜單勾選/取消完成后關閉計算機
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -f -s -t 0");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 內部線程類 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回調接口 */
interface ICallBack
{
public void output();
}

85.菜單勾選/取消完成后重新啟動計算機
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -f -r -t 0");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 內部線程類 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回調接口 */
interface ICallBack
{
public void output();
}

86.菜單勾選/取消完成后注銷計算機
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -l");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 內部線程類 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回調接口 */
interface ICallBack
{
public void output();
}

87.菜單勾選/取消開機自啟動程序
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*; 
//import java.util.*; 
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
RegistryValue v = new RegistryValue("run", ValueType.REG_SZ, "data");
r.setValue(v);

/////////////////////////////////////////////////////////////

拖一個CheckBox

1、軟件啟動時給CheckBox重置狀態:
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*; 
//import java.util.*; 
RegistryKey R_local = Registry.LocalMachine;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
if (R_run.GetValue("BirthdayTipF") == null)
{
checkBox1.Checked = false;
}
else
{
checkBox1.Checked = true;
}
R_run.Close();
R_local.Close();

2、CheckChanged事件:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
string R_startPath = Application.ExecutablePath;
if (checkBox1.Checked == true)
{
RegistryKey R_local = Registry.LocalMachine;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.SetValue("BirthdayTipF", R_startPath);
R_run.Close();
R_local.Close();
}
else
{
try
{
RegistryKey R_local = Registry.LocalMachine;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.Deletue("BirthdayTipF", false);
R_run.Close();
R_local.Close();
}
catch (Exception ex)
{
MessageBox.Show("您需要管理員權限修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}

}
}

88.菜單勾選/取消自動登錄系統

89.模擬鍵盤輸入字符串
/*
import java.awt.*;
import java.awt.event.*;
throws Exception{
*/
static Robot robot;
static{
try {
robot = new Robot();
} catch (AWTException e) {}
}

static void sendKey(String ks){
KeyStore k = KeyStore.findKeyStore(ks);
if(k!=null){
if(k.upCase)
upCase(k.v);
else
sendKey(k.v);
}
else{
for(int i=0; i<ks.length(); i++){
char c = ks.charAt(i);
if(c>='0'&&c<='9'){
sendKey(c);
}
else if(c>='a'&&c<='z'){
sendKey(c-32);
}
else if(c>='A'&&c<='Z'){
upCase(c);
}
}
}
}
private static void upCase(int kc){
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(kc);
robot.keyRelease(kc);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
private static void sendKey(int kc){
robot.keyPress(kc);
robot.keyRelease(kc);
}
static class KeyStore{
//special keys
final static KeyStore[] sp = {
new KeyStore("{Tab}",KeyEvent.VK_TAB),//tab
new KeyStore("{Enter}",KeyEvent.VK_ENTER),//enter
new KeyStore("{PUp}",KeyEvent.VK_PAGE_UP),//page up
new KeyStore("{<}",KeyEvent.VK_LESS),//<
new KeyStore("{Up}",KeyEvent.VK_UP),//up key
new KeyStore("{At}",KeyEvent.VK_AT,true),//@
new KeyStore("{Dollar}",KeyEvent.VK_DOLLAR,true),//$
};

String k;
int v;
boolean upCase;
KeyStore(String k,int v){
this(k,v,false);
}

KeyStore(String s,int i,boolean up){
k=s;
v=i;
upCase=up;
}
static KeyStore findKeyStore(String k){
for(int i=0; i<sp.length; i++){
if(sp[i].k.equals(k))
return sp[i];
}
return null;
}
}
Thread.sleep(1000);
sendKey("{Tab}");//tab
sendKey("{<}");//<
sendKey("abcd123AHahahAA");//abcd123AHahahAA
sendKey("{At}");//@
sendKey("{Dollar}");//$
sendKey("{Up}");//up arrow

90.提取PDF文件中的文本
//http://incubator.apache.org/pdfbox/
/*
import java.io.*; 
import org.pdfbox.pdfparser.*; 
import org.pdfbox.pdmodel.*; 
import org.pdfbox.util.*; 
*/
public class SimplePDFReader { 
/** 
* simply reader all the text from a pdf file. 
* You have to deal with the format of the output text by yourself. 
* 2008-2-25 
* @param pdfFilePath file path 
* @return all text in the pdf file 
*/ 
public static String getTextFromPDF(String pdfFilePath) { 
String result = null; 
FileInputStream is = null; 
PDDocument document = null; 
try { 
is = new FileInputStream(pdfFilePath); 
PDFParser parser = new PDFParser(is); 
parser.parse(); 
document = parser.getPDDocument(); 
PDFTextStripper stripper = new PDFTextStripper(); 
result = stripper.getText(document); 
} catch (FileNotFoundException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} finally { 
if (is != null) { 
try { 
is.close(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 


if (document != null) { 
try { 
document.close(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 



return result; 


得到PDF的文本內容之后,自己根據文件的格式,取得想要的文本(這里我找的就是文章的標題,在文本中恰巧都是文件的第一行的內容),然后通過java的File相關api,對文件進行更名操作。 
import java.io.File; 
import java.io.FilenameFilter;

public class PaperNameMender {
public static void changePaperName(String filePath) { 
//使用SimplePDFReader得到pdf文本 
String ts = SimplePDFReader.getTextFromPDF(filePath); 
//取得一行內容 
String result = ts.substring(0, ts.indexOf('\n')); 
//得到源文件名中的最后一個逗點.的位置 
int index = filePath.indexOf('.'); 
int nextIndex = filePath.indexOf('.', index + 1); 
while(nextIndex != -1) { 
index = nextIndex; 
nextIndex = filePath.indexOf('.', index + 1); 

//合成新文件名 
String newFilename = filePath.substring(0, index) + " " + 
result.trim() + ".pdf"; 
File originalFile = new File(filePath); 
//修改文件名 
originalFile.renameTo(new File(newFilename)); 

}


91.操作內存映射文件
/*
import java.io.*; 
import java.nio.*; 
import java.nio.channels.*;
*/ 
private static int length = 0x8FFFFFF; // 128 Mb 
MappedByteBuffer out = 
new RandomAccessFile("test.dat", "rw").getChannel() 
.map(FileChannel.MapMode.READ_WRITE, 0, length); 
for(int i = 0; i < length; i++) 
out.put((byte)'x'); 
System.out.println("Finished writing"); 
for(int i = length/2; i < length/2 + 6; i++) 
System.out.print((char)out.get(i));

92.重定向windows控制台程序的輸出信息
92.1 取得Runtime.getRuntime().exec("cmd /c dir")的輸入輸出
//import java.io.*;
try {
String command = "cmd /c dir";
Process proc = Runtime.getRuntime().exec(command);
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader lnr = new LineNumberReader(ir);
String line;
while( (line = lnr.readLine()) != null)
{
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

92.2 利用ProcessBuilder來創建Process對象,執行外部可執行程序
// //Eg1:
// String address = null;
//
// String os = System.getProperty("os.name");
// System.out.println(os);
//
// if (os != null) {
// if (os.startsWith("Windows")) {
// try {
// ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
// Process p = pb.start();
//
// BufferedReader br = new BufferedReader(
// new InputStreamReader(p.getInputStream()));
//
// String line;
// while ((line = br.readLine()) != null) {
// if (line.indexOf("Physical Address") != -1) {
// int index = line.indexOf(":");
// address = line.substring(index + 1);
// break;
// }
// }
// br.close();
// address = address.trim();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// } else if (os.startsWith("Linux")) {
// try {
// ProcessBuilder pb = new ProcessBuilder(
//
// "ifconfig", "/all");
//
// Process p = pb.start();
// BufferedReader br = new BufferedReader(
// new InputStreamReader(p.getInputStream()));
// String line;
// while ((line = br.readLine()) != null) {
// int index = line.indexOf("硬件地址");
// if (index != -1) {
// address = line.substring(index + 4);
// break;
// }
// }
// br.close();
// address = address.trim();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }

// //Eg2:
// try {
// Process proc;
// proc = Runtime.getRuntime().exec("cmd.exe");
// BufferedReader read = new BufferedReader(new InputStreamReader(proc
// .getInputStream()));
// new Thread(new Echo(read)).start();
//
// PrintWriter out = new PrintWriter(new OutputStreamWriter(proc
// .getOutputStream()));
// BufferedReader in = new BufferedReader(new InputStreamReader(
// System.in));
// String instr = in.readLine();
// while (!"exit".equals(instr)) {
// instr = in.readLine();
// out.println(instr);
// out.flush();
// }
//
// in.readLine();
// read.close();
// out.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }

}
}

class Echo implements Runnable {
private BufferedReader read;

public Echo(BufferedReader read) {
this.read = read;
}

public void run() {
try {
String line = read.readLine();
while (line != null) {
System.out.println(line);
line = read.readLine();
}
System.out.println("---執行完畢:");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
93.接受郵件
//import javax.mail.*;
public class UserAuthentication extends Authenticator {
private String userName;
private String password;
public void setPassword(String password){
this.password = password;
}

public void setUserName(String userName){
this.userName = userName;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}

//ReceiveMailTest.java
import javax.mail.*;
import java.io.*;
import java.util.*;
import javax.mail.*;

public class ReceiveMailTest {
private Folder inbox;
private Store store;

//連接郵件服務器,獲得所有郵件的列表
public Message[] getMail(String host, String name, String password) throws
Exception {
Properties prop = new Properties();
prop.put("mail.pop3.host", host);
Session session = Session.getDefaultInstance(prop);

store = session.getStore("pop3");
store.connect(host, name, password);

inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);

Message[] msg = inbox.getMessages();

FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
profile.add(FetchProfile.Item.FLAGS);
profile.add("X-Mailer");
inbox.fetch(msg, profile);

return msg;
}

//處理任何一種郵件都需要的方法
private void handle(Message msg) throws Exception {
System.out.println("郵件主題:" + msg.getSubject());
System.out.println("郵件作者:" + msg.getFrom()[0].toString());
System.out.println("發送日期:" + msg.getSentDate());

}

//處理文本郵件
public void handleText(Message msg) throws Exception {
this.handle(msg);
System.out.println("郵件內容:" + msg.getContent());
}

//處理Multipart郵件,包括了保存附件的功能
public void handleMultipart(Message msg) throws Exception {
String disposition;
BodyPart part;
// 1、從Message中取到Multipart
// 2、遍歷Multipart里面得所有bodypart
// 3、判斷BodyPart是否是附件,
// 如果是,就保存附件
// 否則就取里面得文本內容
Multipart mp = (Multipart) msg.getContent();
int mpCount = mp.getCount(); //Miltipart的數量,用於除了多個part,比如多個附件
for (int m = 0; m < mpCount; m++) {
this.handle(msg);

part = mp.getBodyPart(m);
disposition = part.getDisposition();
if (disposition != null && disposition.equals(Part.ATTACHMENT)) { //判斷是否有附件
this.saveAttach(part);//這個方法負責保存附件,注釋掉是因為附件可能有病毒,請清理信箱之后再取掉注釋
} else {
System.out.println(part.getContent());
}
}
}

private void saveAttach(BodyPart part) throws Exception {
String temp = part.getFileName(); //得到未經處理的附件名字
System.out.println("*********temp=" + temp);
System.out.println("**********" + base64Decoder(temp));
String s = temp;//temp.substring(11, temp.indexOf("?=") - 1); //去到header和footer

//文件名一般都經過了base64編碼,下面是解碼
String fileName = s;//this.base64Decoder(s);
System.out.println("有附件:" + fileName);

InputStream in = part.getInputStream();
FileOutputStream writer = new FileOutputStream(new File("d:/temp/"+fileName));
byte[] content = new byte[255];
int read = 0;
while ((read = in.read(content)) != -1) {
writer.write(content);
}
writer.close();
in.close();
}

//base64解碼
private String base64Decoder(String s) throws Exception {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
//sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
//String str = encoder.encode(bytes);

return (new String(b));
}

//關閉連接
public void close() throws Exception {
if (inbox != null) {
inbox.close(false);
}

if (store != null) {
store.close();
}
}

public static void main(String args[]) {
String host = "192.168.1.245";
String name = "user2";
String password = "yyaccp";

ReceiveMailTest receiver = new ReceiveMailTest();

try {
Message[] msg = receiver.getMail(host, name, password);

for (int i = 0; i < msg.length; i++) {
if (msg[i].isMimeType("text/*")) { //判斷郵件類型
receiver.handleText(msg[i]);
} else {
receiver.handleMultipart(msg[i]);
}
System.out.println("****************************");
}
receiver.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}

94.發送郵件
//import javax.mail.*;
public class UserAuthentication extends Authenticator {
private String userName;
private String password;
public void setPassword(String password){
this.password = password;
}

public void setUserName(String userName){
this.userName = userName;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}

//SendMailTest.java
import java.io.*;
import javax.mail.internet.*;
import javax.mail.*;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
import javax.mail.*;

public class SendMailTest {

public SendMailTest() {
}

public static void main(String[] args) throws Exception {
String smtpServer = "192.168.1.245";
String userName = "user2";
String password = "yyaccp";
String fromAddress = "user1@mailserver";
String toAddress = "user2@mailserver";

String subject = "郵件標題";
String content = "郵件內容";
String attachFile1 = "d:/temp/test.txt";
String attachFile2 = "d:/temp/test2.txt";

SendMailTest sendMail = new SendMailTest();
Session session = sendMail.getSession(smtpServer, userName, password);
if(session != null){
String[] files = {attachFile1, attachFile2};
//Message msg = sendMail.getMessage(session, subject, content, files);
Message msg = sendMail.getMessage(session, subject, content);

if(msg != null){
//發送源地址
msg.setFrom(new InternetAddress(fromAddress));

//發送目的地址
InternetAddress[] tos = InternetAddress.parse(toAddress);
msg.setRecipients(Message.RecipientType.TO, tos);
//抄送目的地址
// InternetAddress[] toscc = InternetAddress.parse(ccAddr);
// msg.setRecipients(Message.RecipientType.CC, toscc);
//
//密送目的地址
// InternetAddress[] tosbcc = InternetAddress.parse(bccAddr);
// msg.setRecipients(Message.RecipientType.BCC, tosbcc);

//發送郵件
boolean bool = sendMail.sendMail(msg);
if(bool){
System.out.println("發送成功");
}else{
System.out.println("發送失敗");
}
}
}
}

public Session getSession(String smtpServer, String userName, String password){
// 192.168.1.245
// user2
// yyaccp
Session session = null;
try{
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer); //例如:202.108.44.206 smtp.163.com
props.put("mail.smtp.auth", "true"); //認證是否設置

UserAuthentication authen = new UserAuthentication();
authen.setPassword(password);
authen.setUserName(userName);

session = Session.getDefaultInstance(props, authen);
}catch(Exception e){
e.printStackTrace();
}
return session;
}

public Message getMessage(Session session, String subject, String text){
Message msg = null;
try{
msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);

}catch(Exception e){
e.printStackTrace();
}
return msg;
}

public boolean sendMail(Message msg){
boolean bool = false;
try {
Transport.send(msg);
bool = true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return bool;
}

public Message getMessage(Session session, String subject, String text, String[] archives){
// d:/temp/saa.txt
Message msg = null;
try{
Multipart contentPart = new MimeMultipart();
// 生成Message對象
msg = new MimeMessage(session);
// 設置郵件內容
msg.setContent(contentPart);
// 設置郵件標題
msg.setSubject(subject);

// 組織郵件內容,包括郵件的文本內容和附件
// 1 郵件文本內容
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text);
// 將文本部分,添加到郵件內容
contentPart.addBodyPart(textPart);

// 2 附件
if(archives != null){
for(int i=0; i<archives.length; i++){
MimeBodyPart archivePart = new MimeBodyPart();
//選擇出每一個附件文件名
String filename = archives[i];
//得到數據源
FileDataSource fds = new FileDataSource(filename);
//得到附件本身並至入BodyPart
archivePart.setDataHandler(new DataHandler(fds));
//得到文件名同樣至入BodyPart
archivePart.setFileName(fds.getName());
// 將附件添加到附件集
contentPart.addBodyPart(archivePart);
}
}
}catch(Exception e){
e.printStackTrace();
}
return msg;
}

/**
* 獲取文本文件內容
* @param path String
* @throws IOException
* @return String
*/
public String getFile(String path) throws IOException {
//讀取文件內容
char[] chrBuffer = new char[10];//緩沖十個字符
int intLength;
String s = "";//文件內容字符串
FileReader fis = new FileReader(path);
while ( (intLength = fis.read(chrBuffer)) != -1) {
String temp = String.valueOf(chrBuffer);//轉換字符串
s = s + temp;//累加字符串
}
return s;
}
}

95.報表相關
//http://www.jfree.org/jfreechart/
/*
import java.io.*;
import java.awt.*;
import org.jfree.chart.*; 
import org.jfree.chart.title.TextTitle; 
import org.jfree.data.general.*;
*/
String title = "夢澤科技員工學歷情況統計"; 
DefaultPieDataset piedata = new DefaultPieDataset();
piedata.setValue("大專", 8.1); 
piedata.setValue("大學", 27.6); 
piedata.setValue("碩士", 53.2); 
piedata.setValue("博士及以上", 19.2); 
piedata.setValue("大專以下", 1.9); 
JFreeChart chart = ChartFactory.createPieChart(title, piedata, true, true, true); 
chart.setTitle(new TextTitle(title, new Font("宋體", Font.BOLD, 25))); 
chart.addSubtitle(new TextTitle("最后更新日期:2005年5月19日", new Font("楷書", Font.ITALIC, 18))); 
chart.setBackgroundPaint(Color.white); 
try { 
ChartUtilities.saveChartAsJPEG(new File("PieChart.jpg"), chart, 360, 300); 
} catch (IOException exz) { 
System.out.print("....Cant′t Create image File"); 
}

96.全屏幕截取
/*
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
*/
try{
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage screenshot = (new Robot())
.createScreenCapture(new Rectangle(0, 0,
(int) d.getWidth(), (int) d.getHeight()));
// 根據文件前綴變量和文件格式變量,自動生成文件名
String name = %%1 + "."
+ %%2; //"png"
File f = new File(name);
ImageIO.write(screenshot, %%2, f);
} catch (Exception ex) {
System.out.println(ex);
}

97.區域截幕
/*
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
*/
interface ImageType {
public final static String JPG = "JPG";
public final static String PNG = "PNG";
public final static String GIF = "GIF";
}
public class ScreenDumpHelper {
/** ScreenDumpHelper 靜態對象 */
private static ScreenDumpHelper defaultScreenDumpHelper;
public static ScreenDumpHelper getDefaultScreenDumpHelper() {
if (defaultScreenDumpHelper == null)
return new ScreenDumpHelper();
return defaultScreenDumpHelper;
}
public ScreenDumpHelper() {
Dimension dime = Toolkit.getDefaultToolkit().getScreenSize();
this.setScreenArea(new Rectangle(dime));
}
private Rectangle screenArea;

public Rectangle getScreenArea() {
return this.screenArea;
}

public void setScreenArea(Rectangle screenArea) {
this.screenArea = screenArea;
}

public void setScreenArea(int x, int y, int width, int height) {
this.screenArea = new Rectangle(x, y, width, height);
}
private BufferedImage getBufferedImage() throws AWTException {
BufferedImage imgBuf = null;
;
imgBuf = (new Robot()).createScreenCapture(this.getScreenArea());
return imgBuf;
}

/**
* 將 圖像數據寫到 輸出流中去,方便再處理

* @param fileFormat
* @param output
* @return
*/
public boolean saveToOutputStream(String fileFormat, OutputStream output) {
try {
ImageIO.write(this.getBufferedImage(), fileFormat, output);
} catch (AWTException e) {
return false;
// e.printStackTrace();
} catch (IOException e) {
return false;
// e.printStackTrace();
}
return true;
}

/**
* 根據文件格式 返回隨機文件名稱

* @param fileFormat
* @return
*/
public String getRandomFileName(String fileFormat) {
return "screenDump_" + (new Date()).getTime() + "." + fileFormat;
}

/**
* 抓取 指定區域的截圖 到指定格式的文件中 -- 這個函數是核心,所有的都是圍繞它來展開的 * 圖片的編碼並不是以后綴名來判斷: 比如s.jpg
* 如果其采用png編碼,那么這個圖片就是png格式的

* @param fileName
* @param fileFormat
* @return boolean
*/
public boolean saveToFile(String fileName, String fileFormat) {
if (fileName == null)
fileName = getRandomFileName(fileFormat);
try {
FileOutputStream fos = new FileOutputStream(fileName);
this.saveToOutputStream(fileFormat, fos);
} catch (FileNotFoundException e) {
System.out.println("非常規文件或不能創建抑或覆蓋此文件: " + fileName);
e.printStackTrace();
}
return true;
}

/**
* 抓取 指定 Rectangle 區域的截圖 到指定格式的文件中

* @param fileName
* @param fileFormat
* @param screenArea
* @return
*/
public boolean saveToFile(String fileName, String fileFormat,
Rectangle screenArea) {
this.setScreenArea(screenArea);
return this.saveToFile(fileName, fileFormat);
}

/**
* 抓取 指定區域的截圖 到指定格式的文件中

* @param fileName
* @param fileFormat
* @param x
* @param y
* @param width
* @param height
*/
public boolean saveToFile(String fileName, String fileFormat, int x, int y,
int width, int height) {
this.setScreenArea(x, y, width, height);
return this.saveToFile(fileName, fileFormat);
}

/**
* 將截圖使用 JPG 編碼

* @param fileName
*/
public void saveToJPG(String fileName) {
this.saveToFile(fileName, ImageType.JPG);
}

public void saveToJPG(String fileName, Rectangle screenArea) {
this.saveToFile(fileName, ImageType.JPG, screenArea);
}

public void saveToJPG(String fileName, int x, int y, int width, int height) {
this.saveToFile(fileName, ImageType.JPG, x, y, width, height);
}

/**
* 將截圖使用 PNG 編碼

* @param fileName
*/
public void saveToPNG(String fileName) {
this.saveToFile(fileName, ImageType.PNG);
}

public void saveToPNG(String fileName, Rectangle screenArea) {
this.saveToFile(fileName, ImageType.PNG, screenArea);
}

public void saveToPNG(String fileName, int x, int y, int width, int height) {
this.saveToFile(fileName, ImageType.PNG, x, y, width, height);
}

public void saveToGIF(String fileName) {
throw new UnsupportedOperationException("不支持保存到GIF文件");
// this.saveToFile(fileName, ImageType.GIF);
}

/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 5; i++)
ScreenDumpHelper.getDefaultScreenDumpHelper().saveToJPG(null,
i * 150, i * 150, 400, 300);
}
}

98.計算文件MD5值
/*
import java.io.*;
import java.math.*;
import java.security.*;
import java.util.*;
*/
File file=new File(%%1); 
if (!file.isFile()){
return null;
}
MessageDigest digest = null;
FileInputStream in=null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}

99.計算獲取文件夾中文件的MD5值
/*
import java.io.*;
import java.math.*;
import java.security.*;
import java.util.*;
*/
public static String getFileMD5(File file) {
if (!file.isFile()){
return null;
}
MessageDigest digest = null;
FileInputStream in=null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/**
* 獲取文件夾中文件的MD5值
* @param file
* @param listChild ;true遞歸子目錄中的文件
* @return
*/
public static Map<String, String> getDirMD5(File file,boolean listChild) {
if(!file.isDirectory()){
return null;
}
//<filepath,md5>
Map<String, String> map=new HashMap<String, String>();
String md5;
File files[]=file.listFiles();
for(int i=0;i<files.length;i++){
File f=files[i];
if(f.isDirectory()&&listChild){
map.putAll(getDirMD5(f, listChild));
} else {
md5=getFileMD5(f);
if(md5!=null){
map.put(f.getPath(), md5);
}
}
}
return map;
}
getDirMD5(%%1,%%2);

備注:
%%1
Runtime.getRuntime().
89.模擬鍵盤輸入字符串
96.全屏幕截取
98.計算文件MD5值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM