欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java最全文件操作实例汇总

程序员文章站 2024-03-07 23:57:58
本文实例汇总了java文件操作。分享给大家供大家参考,具体如下: 1.创建文件夹 //import java.io.*; file myfolderpath...

本文实例汇总了java文件操作。分享给大家供大家参考,具体如下:

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); 
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.*; 
file delfolderpath = new file(%%1); 
try { 
delfolderpath.delete(); //删除空文件夹 
} 
catch (exception e) { 
system.out.println("删除文件夹操作出错"); 
e.printstacktrace(); 
}

5.删除一个文件下夹所有的文件夹

//import java.io.*; 
file delfile=new file(%%1); 
file[] files=delfile.listfiles(); 
for(int i=0;i<files.length;i++){ 
if(files[i].isdirectory()){ 
files[i].delete(); 
} 
}

6.清空文件夹

//import java.io.*; 
file delfilefolder=new file(%%1); 
try { 
if (!delfilefolder.exists()) { 
delfilefolder.delete(); 
} 
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.peek()); 
folderlist.removelast(); 
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) { 
%%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()){ 
arraylist<string>folderlist=new arraylist<string>(); 
folderlist.add(copyfolderslist[k].getpath()); 
arraylist<string>folderlist2=new arraylist<string>(); 
folderlist2.add(%%2+"/"+copyfolderslist[k].getname()); 
for(int j=0;j<folderlist.length;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[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(); 
} 
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()) 
system.out.println("删除单个文件操作出错!"); 
} 
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(); 
} 
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()){ 
arraylist<string>folderlist=new arraylist<string>(); 
folderlist.add(movefolderslist[k].getpath()); 
arraylist<string>folderlist2=new arraylist<string>(); 
folderlist2.add(%%2+"/"+movefolderslist[k].getname()); 
for(int j=0;j<folderlist.length;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[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) { 
system.out.println("复制整个文件夹内容操作出错"); 
e.printstacktrace(); 
} 
} 
movefolderslist[k].delete(); 
} 
}

17.以一个文件夹的框架在另一个目录创建文件夹和空文件

//import java.io.*; 
//import java.util.*; 
boolean b=false;//不创建空文件 
arraylist<string>folderlist=new arraylist<string>(); 
folderlist.add(%%1); 
arraylist<string>folderlist2=new arraylist<string>(); 
folderlist2.add(%%2); 
for(int j=0;j<folderlist.length;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[i]); 
} 
else{ 
temp=new file(folderlist.get(j)+"/"+file.separator+file[i]); 
} 
fileinputstream input = new fileinputstream(temp); 
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) { 
system.out.println("复制整个文件夹内容操作出错"); 
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]; 
int length; 
while ( (byteread = instream.read(buffer)) != -1) { 
bytesum += byteread; //字节数 文件大小 
system.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
instream.close(); 
} 
} 
catch (exception e) { 
system.out.println("复制单个文件操作出错"); 
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].isdirectory()){ 
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]; 
int length; 
while ( (byteread = instream.read(buffer)) != -1) { 
bytesum += byteread; //字节数 文件大小 
system.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
instream.close(); 
} catch (exception e) { 
system.out.println("复制单个文件操作出错"); 
e.printstacktrace(); 
} 
} 
}

20.提取扩展名

复制代码 代码如下:
string %%2=%%1.substring(%%1.lastindexof(".")+1);

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]; 
int length; 
while ( (byteread = instream.read(buffer)) != -1) { 
bytesum += byteread; //字节数 文件大小 
//system.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
instream.close(); 
oldfile.delete(); 
} 
} 
catch (exception e) { 
system.out.println("复制单个文件操作出错"); 
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]; 
int length; 
while ( (byteread = instream.read(buffer)) != -1) { 
bytesum += byteread; //字节数 文件大小 
//system.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
instream.close(); 
oldfile.delete(); 
} 
} 
catch (exception e) { 
system.out.println("复制单个文件操作出错"); 
e.printstacktrace(); 
} 
} 
}

27.指定目录下搜索文件

//import java.io.*; 
string filter="*.*"; 
string path=%%1; 
file file = new file(path); 
if(file.exists()) { 
if(file.isdirectory()) { 
file[] filearray = file.listfiles(); 
for(file f:filearray) { 
if(f.isdirectory()) { 
dosearch(filter,f.getpath()); 
} else { 
if(f.getname().indexof(filter) >= 0) { 
countfiles++; 
result.append(f.getpath() + "/r/n"); 
} 
} 
statusshow1.settext(f.getpath()); 
} 
statusshow2.settext("the numbers of files had been found:" + countfiles); 
} else { 
system.out.println("couldn't open the path!"); 
} 
} else { 
system.out.println("the path had been apointed was not exist!"); 
}

28.打开对话框

//import java.io.*; 
//import javax.swing.*; 
jfilechooser jfc = new jfilechooser(); //建立选择档案对话方块盒 jfc 
if (jfc.isfileselectionenabled()) { 
file %%1 = 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.*; 
if (configmap == null) { 
string writebuffer = ""; 
configmap = new hashmap<string, serializable>(); 
string strline = null; 
string currentnode = null; 
string previousnode = null; 
vector<properties> vec = new vector<properties>(); 
int row = 0; 
filereader filereader = null; 
try { 
filereader = new filereader("config.ini"); 
} catch (filenotfoundexception e1) { 
e1.printstacktrace(); 
} 
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, vec.elementat(0)); 
vec.clear(); 
row = 0; 
} 
writebuffer += (oneline + "/r/n"); 
} else if (strarray1[0].equals("@key") && row == 0) { 
properties ht = new properties(); 
ht.setproperty(strarray1[1], strarray1[2]); 
if (strarray1[1].equals(%%1)) { 
writebuffer += (%%1+"=" + %%2 + "/r/n"); 
} else 
writebuffer += (oneline + "/r/n"); 
vec.add(0, ht); 
row++; 
} else if (strarray1[0].equals("@key") && row > 0) { 
properties ht2 = new properties(); 
ht2.put(strarray1[1], strarray1[2]); 
vec.clear(); 
vec.add(0, ht2); 
writebuffer += (oneline + "/r/n"); 
row++; 
} 
} 
} 
configmap.put(currentnode, vec.elementat(0)); 
} catch (filenotfoundexception e) { 
configmap = null; 
e.printstacktrace(); 
} catch (ioexception e) { 
configmap = null; 
e.printstacktrace(); 
} finally { 
vec.clear(); 
try { 
bufferedreader.close(); 
filereader.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
try { 
filewriter fw = new filewriter("config.ini"); 
fw.write(writebuffer); 
fw.flush(); 
fw.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
}

34.读取ini文件属性

//import java.io.*; 
//import java.util.*; 
//import java.util.regex.*; 
//private hashmap configmap=null; 
private map<string, serializable> configmap=null; 
string %%2=null; 
if (configmap == null) { 
configmap = new hashmap<string, serializable>(); 
string strline = null; 
string currentnode = null; 
string previousnode = null; 
vector<properties> vec = new vector<properties>(); 
int row = 0; 
filereader filereader = null; 
try { 
filereader = new filereader("config.ini"); 
} catch (filenotfoundexception e1) { 
e1.printstacktrace(); 
} 
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, vec.elementat(0)); 
vec.clear(); 
row = 0; 
} 
} else if (strarray1[0].equals("@key") && row == 0) { 
properties ht = new properties(); 
ht.setproperty(strarray1[1], strarray1[2]); 
if(strarray1[1].equals(%%1)) 
{ 
%%2=strarray1[2]; 
return; 
} 
vec.add(0, ht); 
row++; 
} else if (strarray1[0].equals("@key") && row > 0) { 
properties ht2 = new properties(); 
ht2.put(strarray1[1], strarray1[2]); 
vec.clear(); 
vec.add(0, ht2); 
row++; 
} 
} 
} 
configmap.put(currentnode, vec.elementat(0)); 
} catch (filenotfoundexception e) { 
configmap = null; 
e.printstacktrace(); 
} catch (ioexception e) { 
configmap = null; 
e.printstacktrace(); 
} finally { 
vec.clear(); 
try { 
bufferedreader.close(); 
filereader.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
}

35.合并一个文件下所有的文件

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]; 
int length; 
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(); 
}

36.写入ini文件属性

//import java.io.*; 
//import java.util.*; 
//import java.util.regex.*; 
//private hashmap configmap=null; 
private map<string, serializable> configmap=null; 
if(configmap==null) { 
string strline=null; 
string currentnode=null; 
string previousnode=null; 
vector<properties> vec=new vector<properties>(); 
int row=0; 
filereader filereader = null; 
try { 
filereader = new filereader(%%1); 
} catch (filenotfoundexception e1) { 
e1.printstacktrace(); 
} 
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,vec.elementat(0)); 
//"size:"+configmap.size() 
vec.clear(); 
row=0; 
} 
} else if(strarray1[0].equals("@key") && row==0) { 
properties ht=new properties(); 
ht.setproperty(strarray1[1],strarray1[2]); 
vec.add(0,ht); 
row++; 
} else if(strarray1[0].equals("@key") && row>0) { 
properties ht2=new properties(); 
ht2.put(strarray1[1],strarray1[2]); 
vec.clear(); 
vec.add(0,ht2); 
row++; 
} 
} 
} 
configmap.put(currentnode,vec.elementat(0)); 
} catch (filenotfoundexception e) { 
configmap=null; 
e.printstacktrace(); 
} catch (ioexception e) { 
configmap=null; 
e.printstacktrace(); 
} finally { 
vec.clear(); 
try { 
bufferedreader.close(); 
filereader.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
} 
string nodekey="["+%%2+"]"; 
properties ht=null; 
if(configmap.containskey(nodekey)) { 
ht=(properties)configmap.get(nodekey); 
} else { 
ht=(properties)configmap.put(nodekey,%%3); 
} 
try { 
ht.setproperty(%%3,%%4); 
} catch (nullpointexception e) { 
e.printstacktrace(); 
} 
filewriter fw= null; 
bufferedwriter bw= null; 
try { 
fw = new filewriter(%%1); 
bw=new bufferedwriter(fw); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
set keys=configmap.keyset(); 
iterator ite=keys.iterator(); 
while(ite.hasnext()) { 
string onekey=(string)ite.next(); 
try { 
bw.write(onekey+"/n"); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
ht=(properties)configmap.get(onekey); 
ht.list(new printwriter(bw,true)); 
}

37.获得当前路径

复制代码 代码如下:
string %%1=this.getclass().getresource("/").getpath();

38.读取xml数据库
//import java.io.*; 
//import javax.xml.parsers.*; 
//import org.xml.sax.*; 
//import org.w3c.dom.*; 
private document document; 
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="serverlist" //%%4="id" //%%6="port" 
//%%3="server" //%%5="ipaddr" 
nodelist nlist=rootnode.getelementsbytagname(subnodetag); 
int len=nlist.getlength(); 
node x=null; 
for(int i=0;i<len;i++) { 
x=nlist.item(i); 
string getnodeattrvalue=null; 
namednodemap attrlist=node.getattributes(); 
for(int j=0;j<attrlist.getlength();j++) { 
if(attrlist.item(j).getnodename().compareto(%%7)==0) { 
getnodeattrvalue=attrlist.item(j).getnodevalue(); 
break; 
} 
} 
if(getnodeattrvalue.compareto(%%8)==0) 
break; 
} 
string %%9=null; 
if(x!=null) { 
nodelist nlist=node.getchildnodes(); 
int len=nlist.getlength(); 
node currentnode; 
string nodename; 
for(int i=0;i<len;i++) { 
currentnode=nlist.item(i); 
nodename=currentnode.getnodename(); 
if(nodename.equals(%%5)==0) { 
%%9=document.getelementvalue(currentnode); 
break; 
} 
} 
}

39.写入xml数据库

//import java.io.*; 
//import javax.xml.parsers.*; 
//import org.xml.sax.*; 
//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="serverlist" //%%4="id" //%%6="port" 
//%%3="server" //%%5="ipaddr" 
nodelist nlist=rootnode.getelementbytagname(subnodetag); 
node=document.createelement(%%3); 
node.setattribute(%%4,nlist.getlength()+1).tostring()); 
node.appendchild(document.createtextnode("/n"); 
element ipnode=document.createelement(%%5); 
ipnode.appendchild(document.createtextnode(%%8)); 
node.appendchild(ipnode); 
node.appendchild(document,createtextnode("/n"); 
element port=document.createelement(%%6); 
port.appendchild(document.createtextnode(%%9)); 
node.appendchild(port); 
node.appendchild(document,createtextnode("/n"); 
nlist.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(); 
}

40.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); 
}

41.获得应用程序完整路径

复制代码 代码如下:
string %%1=system.getproperty("user.dir");

42.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); 
}

43.递归删除目录中的文件

//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 org.apache.tools.zip.zipoutputstream;
//这个包在ant.jar里,要到官方网下载 
//import java.util.zip.*; 
try { 
string zipfilename = %%2; //打包后文件名字 
file f=new file(%%1); 
zipoutputstream out = new zipoutputstream(new fileoutputstream(zipfilename)); 
string base= ""; 
if (f.isdirectory()) { 
file[] fl = f.listfiles(); 
out.putnextentry(new org.apache.tools.zip.zipentry(base + "/")); 
base = base.length() == 0 ? "" : base + "/"; 
for (int i = 0; i < fl.length; i++) { 
zip(out, fl[i], base + fl[i].getname()); 
} 
}else { 
out.putnextentry(new org.apache.tools.zip.zipentry(base)); 
fileinputstream in = new fileinputstream(f); 
int b; 
while ( (b = in.read()) != -1) { 
out.write(b); 
} 
in.close(); 
} 
out.close(); 
}catch (exception ex) { 
ex.printstacktrace(); 
}

44.java验证dtd

//import java.io.*; 
//import javax.xml.parsers.*; 
//import org.xml.sax.*; 
//import org.w3c.dom.*; 
try { 
inputstream in=new fileinputstream(filepath); 
saxreader saxreader = new saxreader(); 
this.document = saxreader.read(in); 
documentbuilderfactory factory = null; 
factory = documentbuilderfactory.newinstance(); 
//进行dtd检查 
factory.setvalidating(true); 
} catch (exception e) { 
}

45.验证schema

//import java.io.*; 
//import javax.xml.parsers.*; 
//import org.xml.sax.*; 
//import org.w3c.dom.*; 
string xsdfilename = /"q:////_dev_stu////xsdtest////src////note.xsd/"; 
try { 
//创建默认的xml错误处理器 
xmlerrorhandler errorhandler = new xmlerrorhandler(); 
//获取基于 sax 的解析器的实例 
saxparserfactory factory = saxparserfactory.newinstance(); 
//解析器在解析时验证 xml 内容。 
factory.setvalidating(true); 
//指定由此代码生成的解析器将提供对 xml 名称空间的支持。 
factory.setnamespaceaware(true); 
//使用当前配置的工厂参数创建 saxparser 的一个新实例。 
saxparser parser = factory.newsaxparser(); 
//创建一个读取工具 
saxreader xmlreader = new saxreader(); 
//获取要校验xml文档实例 
document xmldocument = (document) xmlreader.read(new file(xmlfilename)); 
//设置 xmlreader 的基础实现中的特定属性。核心功能和属性列表可以在 http://sax.sourceforge.net/?selected=get-set 中找到。 
parser.setproperty( 
/"http://java.sun.com/xml/jaxp/properties/schemalanguage", 
/"http://www.w3.org/2001/xmlschema"); 
parser.setproperty( 
/"http://java.sun.com/xml/jaxp/properties/schemasource", 
/"file:/" + xsdfilename); 
//创建一个saxvalidator校验工具,并设置校验工具的属性 
saxvalidator validator = new saxvalidator(parser.getxmlreader()); 
//设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 
validator.seterrorhandler(errorhandler); 
//校验 
validator.validate(xmldocument); 
xmlwriter writer = new xmlwriter(outputformat.createprettyprint()); 
//如果错误信息不为空,说明校验失败,打印错误信息 
if (errorhandler.geterrors().hascontent()) { 
system.out.println(/"xml文件通过xsd文件校验失败!/"); 
writer.write(errorhandler.geterrors()); 
} else { 
system.out.println(/"good! xml文件通过xsd文件校验成功!/"); 
} 
} catch (exception ex) { 
system.out.println(/"xml文件: /" + xmlfilename + /" 通过xsd文件:/" + xsdfilename + /"检验失败。/n原因: /" + ex.getmessage 
()); 
ex.printstacktrace(); 
} 
}

46.grep

//import java.util.regex.*; 
//import java.io.*; 
/** 
* simple implementation of the ubiquitous grep command. 
* first argument is the regular expression to search for (remember to 
* quote and/or escape as appropriate). all following arguments are 
* filenames to read and search for the regular expression. 
* 
* created: april, 2002 
* @author ron hitchens (ron@ronsoft.com) 
* @version $id: simplegrep.java,v 1.1 2002/05/07 02:21:08 ron exp $ 
*/ 
public static void main (string [] argv) 
throws exception 
{ 
if (argv.length < 2) { // 如果参数行没有输入参数,结束程序 
system.out.println ("usage: regex file [ ... ]"); 
return; 
} 
pattern pattern = pattern.compile (argv [0]); // 第一个参数为需要匹配的字符串 
matcher matcher = pattern.matcher (""); 
// 一次读取各个文件 
for (int i = 1; i < argv.length; i++) { 
string file = argv [i]; // 第2个参数开始,均为文件名。 
bufferedreader br = null; 
string line; 
try { 
br = new bufferedreader (new filereader (file)); // 打开文件 
} catch (ioexception e) { 
// 没有打开文件,则产生异常 
system.err.println ("cannot read '" + file 
+ "': " + e.getmessage()); 
continue; 
} 
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(fl, 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(); 
}

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();

3.写入字符串值

registrykey r = new registrykey(rootkey.hkey_current_user, "software//beq technologies"); 
registryvalue v = new registryvalue("myval", valuetype.reg_sz, "data"); 
r.setvalue(v); 

4.获取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.*; 
// 取得系统剪贴板里可传输的数据构造的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); 
} 
} 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 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
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 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
jfc = new jfilechooser("请选择目标路径"); // 建立选择档案对话方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%2 = jfc.getselectedfile().getparent();

62.目录下所有文件夹复制到整合操作

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/ 
jfilechooser jfc = new jfilechooser("请选择源路径");
// 建立选择档案对话 
//方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
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 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
jfc = new jfilechooser("请选择目标路径");
// 建立选择档案对话方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%2 = jfc.getselectedfile().getparent();

64.目录下所有文件复制到整合操作

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/ 
jfilechooser jfc = new jfilechooser("请选择源路径");
// 建立选择档案对话 
//方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
jfc = new jfilechooser("请选择目标路径");
// 建立选择档案对话方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%2 = jfc.getselectedfile().getparent();

65.目录下所有文件移动到整合操作

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/ 
jfilechooser jfc = new jfilechooser("请选择源路径");
// 建立选择档案对话 
//方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
jfc = new jfilechooser("请选择目标路径");
// 建立选择档案对话方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%2 = jfc.getselectedfile().getparent();

66.对目标压缩文件解压缩到指定文件夹

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/

67.创建目录副本整合操作

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/ 
jfilechooser jfc = new jfilechooser("请选择源路径");
// 建立选择档案对话 
方块盒 jfc 
if (!jfc.isfileselectionenabled()) { 
return; 
} 
string %%1 = jfc.getselectedfile().getparent(); 
jfc = new jfilechooser("请选择目标路径");
// 建立选择档案对话方块盒 jfc 
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下载

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.peek()); 
folderlist.removelast(); 
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(); 
} 
}

希望本文所述对大家java程序设计有所帮助。