码迷,mamicode.com
首页 > 编程语言 > 详细

Java文件操作源码大全

时间:2014-09-07 07:38:04      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   使用   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值

Java文件操作源码大全

标签:des   style   blog   http   color   os   io   使用   java   

原文地址:http://www.cnblogs.com/exmyth/p/3960077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!