//importjava.io.*;
FilemyFolderPath=newFile(%%1);try{
if(!myFolderPath.exists()){
myFolderPath.mkdir();
}
}
catch(Exceptione){
System.out.println(\"新建目录操作出错\");e.printStackTrace();
}
2.创建文件
//importjava.io.*;
FilemyFilePath=newFile(%%1);try{
if(!myFilePath.exists()){
myFilePath.createNewFile();
}
FileWriterresultFile=newFileWriter(myFilePath);PrintWritermyFile=newPrintWriter(resultFile);myFile.println(%%2);myFile.flush();resultFile.close();
}
catch(Exceptione){
System.out.println(\"新建文件操作出错\");e.printStackTrace();
}
3.删除文件
//importjava.io.*;
FilemyDelFile=newFile(%%1);try{
myDelFile.delete();
}
catch(Exceptione){
System.out.println(\"删除文件操作出错\");e.printStackTrace();
}
4.删除文件夹/*
importjava.io.*;importjava.util.*;*/
LinkedListfolderList=newLinkedList while(folderList.size()>0){ Filefile=newFile(folderList.poll());File[]files=file.listFiles(); ArrayList folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } } folderList=newLinkedList while(folderList.size()>0){ Filefile=newFile(folderList.getLast());if(file.delete()){ folderList.removeLast(); }else{ File[]files=file.listFiles(); for(inti=0;i } } } 5.删除一个文件下夹所有的文件夹/* importjava.io.*; privatestaticLinkedList Filedelfile=newFile(%%1);File[]files=delfile.listFiles();for(inti=0;i if(!files[i].delete()){ folderList=newLinkedList folderList.add(files[i]); while(folderList.size()>0){ Filefile=newFile(folderList.poll());File[]files=file.listFiles(); ArrayList folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } } folderList=newLinkedList while(folderList.size()>0){ Filefile=newFile(folderList.getLast());if(file.delete()){ folderList.removeLast(); }else{ File[]files=file.listFiles(); for(inti=0;i } } } } } } 6.清空文件夹//importjava.io.*; Filedelfilefolder=newFile(%%1);try{ if(!delfilefolder.exists()&&!delfilefolder.delete()){ LinkedListfolderList=newLinkedList Filefile=newFile(folderList.poll());File[]files=file.listFiles(); ArrayList folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } } folderList=newLinkedList Filefile=newFile(folderList.getLast());if(file.delete()){ folderList.removeLast(); }else{ File[]files=file.listFiles(); for(inti=0;i } } } } delfilefolder.mkdir(); } catch(Exceptione){ System.out.println(\"清空目录操作出错\");e.printStackTrace(); } 7.读取文件 //importjava.io.*;//逐行读取数据 FileReaderfr=newFileReader(%%1); BufferedReaderbr=newBufferedReader(fr);String%%2=br.readLine();while(%%2!=null){ %%3 %%2=br.readLine(); } br.close();fr.close();8.写入文件 //importjava.io.*;//将数据写入文件try{ FileWriterfw=newFileWriter(%%1);fw.write(%%2);fw.flush();fw.close(); }catch(IOExceptione){ e.printStackTrace(); } 9.写入随机文件//importjava.io.*;try{ RandomAcessFilelogFile=newRandomAcessFile(%%1,\"rw\");longlg=logFile.length();logFile.seek(%%2); logFile.writeByte(%%3); }catch(IOExceptionioe){ System.out.println(\"无法写入文件:\"+ioe.getMessage()); } 10.读取文件属性//importjava.io.*;//文件属性的取得Fileaf=newFile(%%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(\"文件夹的最后修改日期为:\"+newDate(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(\"文件的最后修改日期为:\"+newDate(f.lastModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 } 11.写入属性 //importjava.io.*; Filefilereadonly=newFile(%%1);try{ booleanb=filereadonly.setReadOnly(); } catch(Exceptione){ System.out.println(\"拒绝写访问:\"+e.printStackTrace()); } 12.枚举一个文件夹中的所有文件/* importjava.io.*;importjava.util.*;*/ LinkedList while(folderList.size()>0){ Filefile=newFile(folderList.poll());File[]files=file.listFiles(); List folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ %%2=f.getAbsoluteFile();%%3 } } 13.复制文件夹/* importjava.io.*;importjava.util.*;*/ LinkedList LinkedList folderList2.add(%%2+%%1.substring(%%1.lastIndexOf(\"\\\\\")));while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹Filefolders=newFile(folderList.peek());String[]file=folders.list();Filetemp=null;try{ for(inti=0;i temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp);FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator+(temp.getName()).toString()); byte[]b=newbyte[5120];intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush();output.close();input.close(); } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //System.out.println(\"复制整个文件夹内容操作出错\");e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } 14.复制一个目录下所有的文件夹到另一个文件夹下/* importjava.io.*;importjava.util.*;*/ Filecopyfolders=newFile(%%1); File[]copyfoldersList=copyfolders.listFiles();for(intk=0;k List folderList2.add(%%2+\"/\"+copyfoldersList[k].getName());for(intj=0;j 件夹 Filefolders=newFile(folderList.get(j));String[]file=folders.list();Filetemp=null;try{ for(inti=0;i temp=new File(folderList.get(j)+File.separator+file[i]); }else{ temp=new File(folderList.get(j)+File.separator+file[i]); } FileInputStreaminput=newFileInputStream(temp);if(temp.isFile()){ FileOutputStreamoutput=new FileOutputStream(folderList2.get(j)+File.separator+ (temp.getName()).toString()); byte[]b=newbyte[5120];intlen; 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(Exceptione){ System.out.println(\"复制整个文件夹内容操作出错\");e.printStackTrace(); } } } } 15.移动文件夹/* importjava.io.*;importjava.util.*;*/ LinkedList LinkedList folderList2.add(%%2+%%1.substring(%%1.lastIndexOf(\"\\\\\")));while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹Filefolders=newFile(folderList.peek());String[]file=folders.list();Filetemp=null;try{ for(inti=0;i temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp);FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator+(temp.getName()).toString()); byte[]b=newbyte[5120];intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush();output.close();input.close();if(!temp.delete()) //删除单个文件操作出错 } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //复制整个文件夹内容操作出错e.printStackTrace(); } folderList.removeFirst();folderList2.removeFirst(); } Filef=newFile(%%1);if(!f.delete()){ for(Filefile:f.listFiles()){ if(file.list().length==0){ System.out.println(file.getPath());file.delete(); } } } 16.移动一个目录下所有的文件夹到另一个目录下/* importjava.io.*;importjava.util.*;*/ Filemovefolders=newFile(%%1); File[]movefoldersList=movefolders.listFiles();for(intk=0;k List folderList2.add(%%2+\"/\"+movefoldersList[k].getName());for(intj=0;j 件夹 Filefolders=newFile(folderList.get(j));String[]file=folders.list();Filetemp=null;try{ for(inti=0;i temp=new File(folderList.get(j)+File.separator+file[i]); }else{ temp=new File(folderList.get(j)+File.separator+file[i]); } FileInputStreaminput=newFileInputStream(temp);if(temp.isFile()){ FileInputStreaminput=new FileInputStream(temp); FileOutputStreamoutput=new FileOutputStream(folderList2.get(j)+\"/\"+ (temp.getName()).toString()); byte[]b=newbyte[5120];intlen; 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(Exceptione){ //复制整个文件夹内容操作出错e.printStackTrace(); } } movefoldersList[k].delete(); } } 17.以一个文件夹的框架在另一个目录创建文件夹和空文件/* importjava.io.*;importjava.util.*;*/ booleanb=false;//不创建空文件 List List for(intj=0;j for(inti=0;i temp=newFile(folderList.get(j)+File.separator+file[i]); }else{ temp=newFile(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(Exceptione){ //复制整个文件夹内容操作出错e.printStackTrace(); } } 18.复制文件 //importjava.io.*;intbytesum=0;intbyteread=0; Fileoldfile=newFile(%%1);try{ if(oldfile.exists()){//文件存在时 FileInputStreaminStream=newFileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,oldfile.getName()));byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小fs.write(buffer,0,byteread); } inStream.close(); } } catch(Exceptione){ //复制单个文件操作出错e.printStackTrace(); } 19.复制一个目录下所有的文件到另一个目录//importjava.io.*; Filecopyfiles=newFile(%%1);File[]files=copyfiles.listFiles();for(inti=0;i intbytesum=0;intbyteread=0;try{ InputStreaminStream=newFileInputStream(files[i]);//读入原文件FileOutputStreamfs=newFileOutputStream(new File(%%2,files[i].getName()); byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小fs.write(buffer,0,byteread); } inStream.close(); }catch(Exceptione){ //复制单个文件操作出错 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.替换扩展名//importjava.io.*; FilereplaceExt=newFile(%%1); replaceExt.renameTo(replaceExt.getName().split(\".\")[0]+\".\"+%%2);24.追加路径 finalStringpath=%%1.endsWith(\"\\\\\")?%%1:%%1+\"\\\\\";%%3=path+%%2; 25.移动文件 //importjava.io.*;intbytesum=0;intbyteread=0; Fileoldfile=newFile(%%1);try{ if(oldfile.exists()){//文件存在时 InputStreaminStream=newFileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,oldfile.getName()));byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小fs.write(buffer,0,byteread); } inStream.close();oldfile.delete(); } } catch(Exceptione){ //复制单个文件操作出错e.printStackTrace(); } 26.移动一个目录下所有文件到另一个目录//importjava.io.*; Filemovefile=newFile(%%1); File[]movefiles=movefile.listFiles();for(inti=0;i intbytesum=0;intbyteread=0; Fileoldfile=newFile(movefiles[i]);try{ if(oldfile.exists()){//文件存在时 InputStreaminStream=newFileInputStream(oldfile);//读入原文 件 FileOutputStreamfs=newFileOutputStream(new File(%%2,oldfile.getName())); byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小fs.write(buffer,0,byteread); } inStream.close();oldfile.delete(); } } catch(Exceptione){ //复制单个文件操作出错e.printStackTrace(); } } } 27.指定目录下搜索文件//importjava.io.*; privatestaticfinalStringfilter=%%1;//\"*.*\"privatestaticvoiddoSearch(Stringpath){ Filefile=newFile(path);if(file.exists()){ if(file.isDirectory()){ File[]fileArray=file.listFiles();for(Filef:fileArray){ if(f.isDirectory()){ doSearch(f.getPath()); }else{ if(f.getName().indexOf(filter)>=0){ //f.getPath() } } //f.getPath() } //\"Thenumbersoffileshadbeenfound:\"+countFiles }else{ //\"Couldn'topenthepath!\" } }else{ System.out.println(\"ThepathhadbeenapointedwasnotExist!\"); } } doSearch(%%1); 28.打开对话框/* importjava.io.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser();//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(Jfc.isFileSelectionEnabled()){ File%%2=Jfc.getSelectedFile(); } 29.文件分割 //importjava.io.*;try{ Filef=newFile(%%1); FileInputStreamfileInputStream=newFileInputStream(f);byte[]buffer=newbyte[fileInputStream.available()];FileInputStream.read(buffer);fileInputStream.close(); StringstrFileName=f.getName(); FileOutputStreamfileOutputStream=newFileOutputStream(newFile(%%2+\"\\\\\"+ strFileName+\"1\")); fileOutputStream.write(buffer,0,buffer.length/2);fileOutputStream.close(); fileOutputStream=newFileOutputStream(newFile(%%2+\"\\\\\"+strFileName+\"2\"));fileOutputStream.write(buffer,buffer.length/2,buffer.length-buffer.length/2);fileOutputStream.close(); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.print(\"usingFileStreamDemosrcdes\");e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); } 30.文件合并 //importjava.io.*; StringstrFileName=%%1.substring(%%1.LastIndexOf(\"\\\\\")+1);try{ FileInputStreamfileInputStream1=newFileInputStream(newFile(%%2+strFileName+ \"1\")); FileInputStreamfileInputStream2=newFileInputStream(newFile(%%2+strFileName+ \"2\")); byte[]buffer=newbyte[fileInputStream1.available()+fileInputStream2.available()];FileInputStream.read(buffer,0,fileInputStream1.available()); FileInputStream2.read(buffer,fileInputStream1.available(),fileInputStream2.available());fileInputStream.close();fileInputStream2.close(); FileOutputStreamfileOutputStream=newFileOutputStream(newFile(%%2+\"\\\\\"+ strFileName)); fileOutputStream.write(buffer,0,buffer.length);fileOutputStream.close(); } catch(IOExceptione){ e.printStackTrace(); } 31.文件简单加密//importjava.io.*; try{ Filef=newFile((newFile(%%1)).getPath()+\"\\\\enc_\"+(new File(%%1)).getName().split(\"//\")[1]); StringstrFileName=f.getName(); FileInputStreamfileInputStream=new FileInputStream(%%2+\"\\\\\"+strFilename); byte[]buffer=newbyte[fileInputStream.available()];FileInputStream.read(buffer);fileInputStream.close(); for(inti=0;i buffer[i]=(byte)ibt; } FileOutputStreamfileOutputStream=newFileOutputStream(f);fileOutputStream.write(buffer,0,buffer.length);fileOutputStream.close(); } catch(ArrayIndexOutOfBoundExceptione){ e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); } 32.文件简单解密//importjava.io.*; try{ Filef=newFile(%%1); StringstrFileName=f.getName(); FileInputStreamfileInputStream=new FileInputStream(%%2+\"\\\\enc_\"+strFilename); byte[]buffer=newbyte[fileInputStream.available()];FileInputStream.read(buffer);fileInputStream.close(); for(inti=0;i buffer[i]=(byte)ibt; } FileOutputStreamfileOutputStream=newFileOutputStream(f);fileOutputStream.write(buffer,0,buffer.length);fileOutputStream.close(); } catch(ArrayIndexOutOfBoundExceptione){ e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); }33.读取ini文件属性/* importjava.io.*; importjava.util.*; importjava.util.regex.*; privatestaticHashMapconfigMap=null;privatestaticFileReaderfileReader=null;*/ privatestaticbooleanreadIni(){ if(configMap==null){ configMap=newHashMap StringcurrentNode=null;StringpreviousNode=null; ArrayList BufferedReaderbufferedReader=new BufferedReader(fileReader); try{ while((strLine=bufferedReader.readLine())!=null){ StringoneLine=strLine.trim();if(oneLine.length()>=1){ Patternp= Pattern.compile(\"\\\\[\\\\s*.*\\\\s*\\\\]\"); intnodelen=oneLine.split(\"[;]\").length;String[]strArray1=newString[4];if(nodelen==1){ oneLine= oneLine.split(\"[;]\")[0].trim(); }elseif(nodelen==2){ strArray1[3]= oneLine.split(\"[;]\")[1].trim(); oneLine= oneLine.split(\"[;]\")[0].trim(); } Matcherm=p.matcher(oneLine);if(m.matches()){ strArray1[0]=\"@Node\";strArray1[1]=oneLine;strArray1[2]=\"\"; }else{ intkeylen= oneLine.split(\"=\").length; if(keylen==1){ strArray1[0]=\"@Key\";strArray1[1]= oneLine.split(\"=\")[0]; strArray1[2]=\"\"; }elseif(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; } }elseif(strArray1[0].equals(\"@Key\")&& row==0){ Propertiesht=newProperties();ht.setProperty(strArray1[1], strArray1[2]); vec.add(ht);row++; }elseif(strArray1[0].equals(\"@Key\")&& row>0){ Propertiesht2=newProperties();ht2.put(strArray1[1],strArray1[2]);vec.add(ht2);row++; } } } configMap.put(currentNode,(ArrayList)vec.clone()); }catch(FileNotFoundExceptione){ configMap=null;e.printStackTrace();returnfalse; }catch(IOExceptione){ configMap=null;e.printStackTrace();returnfalse; } } returntrue; }try{ fileReader=newFileReader(%%1);//\"Setup.ini\" }catch(FileNotFoundExceptione1){ e1.printStackTrace(); } if(readIni()){ ArrayList li=(ArrayList if(pro.containsKey(%%3)) %%4=pro.getProperty(%%3); } }try{ fileReader.close(); }catch(IOExceptione){ e.printStackTrace(); } 34.合并一个目录下所有的文件//importjava.io.*; Filecombinefiles=newFile(%%1);File[]files=combinefiles.listFiles();FileOutputStreamfs;try{ fs=newFileOutputStream(newFile(%%2)); } catch(IOExceptione){ e.printStackTrace(); } for(inti=0;i intbytesum=0;intbyteread=0;try{ FileInputStreaminStream=newFileInputStream(files[i]);byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread; fs.write(buffer,0,byteread); } inStream.close(); } catch(Exceptione){ //复制文件出错e.printStackTrace(); } } }try{ fs.close(); } catch(IOExceptione){ e.printStackTrace(); } 35.写入ini文件属性/* importjava.io.*;importjava.util.*; importjava.util.regex.*; privatestaticHashMapconfigMap=null;*/ if(readIni()){ ArrayList FileWriterfw=newFileWriter(\"Setup.ini\"); li=(ArrayList if(pro.containsKey(\"ip\")) fw.write(\"ip=\"+jt1.getText()+\"\\r\\n\"); elseif(pro.containsKey(\"username\")) fw.write(\"username=\"+username1+ \"\\r\\n\"); elseif(pro.containsKey(\"password\")) fw.write(\"password=\"+password1+ \"\\r\\n\"); elseif(pro.containsKey(\"database\")) fw.write(\"database=\"+database1+ \"\\r\\n\"); elseif(pro.containsKey(\"table\")) fw.write(\"table=\"+table1+\"\\r\\n\"); } li=(ArrayList if(pro.containsKey(\"ip\")) fw.write(\"ip=\"+jt2.getText()+\"\\r\\n\"); elseif(pro.containsKey(\"username\")) fw.write(\"username=\"+username2+ \"\\r\\n\"); elseif(pro.containsKey(\"password\")) fw.write(\"password=\"+password2+ \"\\r\\n\"); elseif(pro.containsKey(\"database\")) fw.write(\"database=\"+database2+ \"\\r\\n\"); elseif(pro.containsKey(\"table\")) fw.write(\"table=\"+table2+\"\\r\\n\"); } fw.flush();fw.close(); }catch(IOExceptione){ e.printStackTrace(); } } 36.获得当前路径 String%%1=this.getClass().getResource(\"/\").getPath();//String%%1=System.getProperty(\"user.dir\") 37.读取XML数据库/* importjava.io.*; importjavax.xml.parsers.*;importorg.w3c.dom.*; privatestaticDocumentdocument;privatestaticElementnode;*/ Filexml_file=newFile(%%1); DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();try{ DocumentBuilderbuilder=factory.newDocumentBuilder();document=builder.parse(xml_file); }catch(Exceptione){e.printStackTrace();} StringsubNodeTag=%%2; ElementrootNode=document.getDocumentElement();//%%2=\"Product\"//%%4=\"id\"//%%6=\"port\"//%%3=\"Name\"//%%5=\"001\" NodeListnlist=rootNode.getElementsByTagName(subNodeTag);intlen=nlist.getLength();for(inti=0;i StringgetNodeAttrValue=null; NamedNodeMapattrList=node.getAttributes();for(intj=0;j 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数据库/* importjava.io.*; importjavax.xml.parsers.*;importorg.w3c.dom.*; importjavax.xml.transform.*; importjavax.xml.transform.dom.*;importjavax.xml.transform.stream.*;privateDocumentdocument;privateElementnode;*/ Filexml_file=newFile(%%1); DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();try{ DocumentBuilderbuilder=factory.newDocumentBuilder();document=builder.parse(xml_file); }catch(Exceptione){ e.printStackTrace(); } StringsubNodeTag=%%2; ElementrootNode=document.getDocumentElement();//%%2=\"Product\"//%%4=\"pid\"//%%6=\"author\"//%%3=\"Name\"//%%5=\"price\" NodeListnlist=rootNode.getElementsByTagName(subNodeTag);Stringss=null; intlen=nlist.getLength();for(inti=0;i //node.setAttribute(%%4,\"0\"+String.valueOf(i));//ID格式化StringgetNodeAttrValue=null; NamedNodeMapattrList=node.getAttributes();for(intj=0;j 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\"));Elementserver=document.createElement(%%3); server.appendChild(document.createTextNode(%%7)); node.appendChild(server); ElementipNode=document.createElement(%%6); ipNode.appendChild(document.createTextNode(%%8));node.appendChild(ipNode); node.appendChild(document.createTextNode(\"\\n\"));Elementport=document.createElement(%%5); port.appendChild(document.createTextNode(%%9));node.appendChild(port); node.appendChild(document.createTextNode(\"\\n\"));rootNode.appendChild(node); } TransformerFactorytFactory=TransformerFactory.newInstance();Transformertransformer=null;try{ transformer=tFactory.newTransformer(); DOMSourcesource=newDOMSource(document);StreamResultresult=newStreamResult(xml_file);transformer.transform(source,result); }catch(Exceptione){ e.printStackTrace(); } 39.ZIP压缩文件/* importjava.io.*;importjava.util.zip.*;*/ //创建文件输入流对象 FileInputStreamfis=newFileInputStream(%%1); //创建文件输出流对象 FileOutputStreamfos=newFileOutputStream(%%2);//创建ZIP数据输出流对象 ZipOutputStreamzipOut=newZipOutputStream(fos);//创建指向压缩原始文件的入口ZipEntryentry=newZipEntry(args[0]);zipOut.putNextEntry(entry);//向压缩文件中输出数据intnNumber; byte[]buffer=newbyte[1024]; while((nNumber=fis.read(buffer))!=-1) zipOut.write(buffer,0,nNumber); //关闭创建的流对象zipOut.close();fos.close(); fis.close(); } catch(IOExceptione){ System.out.println(e); } 40.ZIP解压缩 /* importjava.io.*;importjava.util.zip.*;*/try{ //创建文件输入流对象实例 FileInputStreamfis=newFileInputStream(%%1);//创建ZIP压缩格式输入流对象实例 ZipInputStreamzipin=newZipInputStream(fis);//创建文件输出流对象实例 FileOutputStreamfos=newFileOutputStream(%%2);//获取Entry对象实例 ZipEntryentry=zipin.getNextEntry();byte[]buffer=newbyte[1024];intnNumber; while((nNumber=zipin.read(buffer,0,buffer.length))!=-1) fos.write(buffer,0,nNumber); //关闭文件流对象zipin.close();fos.close();fis.close(); } catch(IOExceptione){ System.out.println(e); } 41.获得应用程序完整路径 String%%1=System.getProperty(\"user.dir\");42.递归删除目录中的文件 /* importjava.io.*;importjava.util.*;*/ ArrayList folderList.add(%%1); for(intj=0;j ArrayList folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } } 43.ZIP压缩文件夹 /* importjava.io.*;importjava.util.*;importjava.util.zip.*;*/ publicstaticStringzipFileProcess(ArrayListoutputZipFileNameList,String outputZipNameAndPath){ ArrayListfileNames=newArrayList();ArrayListfiles=newArrayList();FileOutputStreamfileOut=null; ZipOutputStreamoutputStream=null;FileInputStreamfileIn=null; StringBuffersb=newStringBuffer(outputZipNameAndPath);//FileInputStreamfileIn=null;try{ if(outputZipNameAndPath.indexOf(\".zip\")!=-1){ outputZipNameAndPath=outputZipNameAndPath; }else{ sb.append(\".zip\"); outputZipNameAndPath=sb.toString(); } fileOut=newFileOutputStream(outputZipNameAndPath);outputStream=newZipOutputStream(fileOut);intoutputZipFileNameListSize=0;if(outputZipFileNameList!=null){ outputZipFileNameListSize=outputZipFileNameList.size(); } for(inti=0;i File(outputZipFileNameList.get(i).toString()); listFile(rootFile,fileNames,files,\"\"); } for(intloop=0;loop fileNames.get(loop))); byte[]buffer=newbyte[1024];while(fileIn.read(buffer)!=-1){ outputStream.write(buffer); } outputStream.closeEntry();fileIn.close(); } returnoutputZipNameAndPath; }catch(IOExceptionioe){ returnnull; }finally{ if(outputStream!=null){ try{ outputStream.close(); }catch(IOExceptione){} } if(fileIn!=null){ try{ fileIn.close(); }catch(IOExceptione){} } } } privatestaticvoidlistFile(FileparentFile,ListnameList,ListfileList,StringdirectoryName){ if(parentFile.isDirectory()){ File[]files=parentFile.listFiles(); for(intloop=0;loop parentFile.getName()+\"/\"); } }else{ fileList.add(parentFile); nameList.add(directoryName+parentFile.getName()); } } ArrayListoutputZipFileName=newArrayList();StringsavePath=\"\";intargSize=0;savePath=%%1; outputZipFileName.add(%%2); ZipFileOtherinstance=newZipFileOther(); instance.zipFileProcess(outputZipFileName,savePath); 44.验证DTD/* importjava.io.*; importjavax.xml.parsers.*;importorg.w3c.dom.*;*/ Filexml_dtd=newFile(%%1); DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();try{ DocumentBuilderbuilder=factory.newDocumentBuilder();document=builder.parse(xml_dtd);//进行dtd检查 factory.setValidating(true); }catch(Exceptione){e.printStackTrace();} 45.验证Schema/* importjavax.xml.*; importjavax.xml.transform.stream.*;importjavax.xml.validation.*;importorg.xml.sax.*;*/ SchemaFactoryfactory= SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSourcess=newStreamSource(%%1);//\"mySchema.xsd\"try{ Schemaschema=factory.newSchema(ss); }catch(SAXExceptione){ e.printStackTrace(); }46.Grep/* importjava.util.regex.*;importjava.io.*; */ throwsException Patternpattern=Pattern.compile(%%1);//第一个参数为需要匹配的字符串Matchermatcher=pattern.matcher(\"\"); Stringfile=%%2; BufferedReaderbr=null;Stringline;try{ br=newBufferedReader(newFileReader(file));//打开文件 }catch(IOExceptione){ //没有打开文件,则产生异常 System.err.println(\"Cannotread'\"+file +\"':\"+e.getMessage()); } while((line=br.readLine())!=null){//读入一行,直到文件结束 matcher.reset(line);//匹配字符串 if(matcher.find()){//如果有匹配的字符串,则输出 System.out.println(file+\":\"+line); } } br.close();//关闭文件47.直接创建多级目录//importjava.io.*;Filef=newFile(%%1);f.mkdirs(); 48.批量重命名//importjava.io.*; Filetarget=newFile(\"%%1\");String[]files=target.list();Filef=null; Stringfilename=null;for(Stringfile:files){ f=newFile(target,file);filename=f.getName(); if(filename.substring(filename.lastIndexOf(\".\")).equalsIgnoreCase( \"%%2\")){ f.renameTo(newFile(target.getAbsolutePath(),filename.replace( \"%%2\\"%%3\"))); //这里可以反复使用replace替换,当然也可以使用正则表达式来替换 了\".txt\"\".bat\" } } 49.文本查找替换//importjava.nio.*;Strings1=%%1;Strings2=%%2;Strings3=%%3;intpos=%%4; /*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/inti,j,k=0;i=pos;j=0; //将s1转化成StringBuffer型进行操作repStr=newStringBuffer(s1); while(i ++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;} } returnk; 50.文件关联 //importjava.io.*;try{ Runtime.getRuntime().exec(%%1);//\"assoc.txt=mynote\"\"assoc[.ext[=[filetype]]]\" }catch(IOExceptione){ e.printStackTrace(); } 51.操作Excel文件 //http://sourceforge.net/projects/poi/importjava.io.*; importorg.apache.poi.hpsf.*; importorg.apache.poi.poifs.eventfilesystem.*;staticclassMyPOIFSReaderListener implementsPOIFSReaderListener { publicvoidprocessPOIFSReaderEvent(POIFSReaderEventevent){ SummaryInformationsi=null;try{ si=(SummaryInformation) PropertySetFactory.create(event.getStream()); } catch(Exceptionex){ thrownewRuntimeException (\"属性集流\\\"\"+event.getPath()+event.getName()+\"\\\":\"+ex); } finalStringtitle=si.getTitle(); if(title!=null) System.out.println(\"标题:\\\"\"+title+\"\\\"\"); else System.out.println(\"该文档没有标题.\"); } } Stringfilename=%%1;POIFSReaderr=newPOIFSReader(); r.registerListener(newMyPOIFSReaderListener(), \"\\005SummaryInformation\"); r.read(newFileInputStream(filename));利用Servlet创建和返回一个工作簿。 packageorg.apache.poi.hssf.usermodel.examples;importjava.io.*;importjava.net.*;importjavax.servlet.*;importjavax.servlet.http.*; importorg.apache.poi.hssf.usermodel.*;publicclassHSSFCreateextendsHttpServlet{ publicvoidinit(ServletConfigconfig) throwsServletException{ super.init(config); } publicvoiddestroy(){} /**处理HTTPGET和POST请求*@paramrequest:请求*@paramresponse:应答*/ protectedvoidprocessRequest(HttpServletRequestrequest, HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType(\"application/vnd.ms-excel\");HSSFWorkbookwb=newHSSFWorkbook(); HSSFSheetsheet=wb.createSheet(\"newsheet\");//创建一个新的行,添加几个单元格。//行号从0开始计算 HSSFRowrow=sheet.createRow((short)0);//创建一个单元格,设置单元格的值HSSFCellcell=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);//写入输出结果 OutputStreamout=response.getOutputStream();wb.write(out);out.close(); } /**处理HTTPGET请求*@paramrequest:请求*@paramresponse:应答*/ protectedvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /**处理HTTPPOST请求*@paramrequest:请求*@paramresponse:应答*/ protectedvoiddoPost(HttpServletRequestrequest, HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /**返回关于Servlet的简单说明*/ publicStringgetServletInfo(){ return\"示例:在Servlet中用HSSF创建Excel工作簿\"; } } 一,建立Excel工作薄 HSSFWorkbookwb=newHSSFWorkbook(); 二,建立Excel工作表,每个工作表对应的是Excel界面左下角的一个标签sheet1,sheet2…HSSFSheetsheet1=wb.createSheet(\"newsheet\");三,在工作表中建立单元格 //首先,建立行对像,行号作为参数传给createRow方法,第一行由0开始计算。HSSFRowrow=sheet.createRow((short)0);//建单元格 HSSFCellcell=row.createCell((short)0);//给单元格赋值cell.setCellValue(1); //也可同一行内完成建立单元格和赋值row.createCell((short)1).setCellValue(1.2); row.createCell((short)2).setCellValue(\"Thisisastring\");row.createCell((short)3).setCellValue(true); //数据格式可通过创建单元格值时默认如上面所视//也可以创建单元格后调用setCellType指定cell.setCellType(CELL_TYPE_NUMERIC); 四,向单元格插入日期值 HSSFWorkbookwb=newHSSFWorkbook(); HSSFSheetsheet=wb.createSheet(\"newsheet\"); //可通过Sheet.setSheetName(sheetindex,\"SheetName\设定工作表名//创建新行并向其加入单元格,行号由0开始。HSSFRowrow=sheet.createRow((short)0); //创建一个单元格并向其输入一日期值,但这第一个单元格并非是日期格式。HSSFCellcell=row.createCell((short)0);cell.setCellValue(newDate()); //我们将这第二个单元格改成日期格式,这需要从工作薄创建一个新的单元格格式,这可//以只影响当前建立的一个单元格。 HSSFCellStylecellStyle=wb.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(\"m/d/yyh:mm\"));cell=row.createCell((short)1);cell.setCellValue(newDate());cell.setCellStyle(cellStyle); 五,各种单元格样式 HSSFCellStylecellStyle=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);六,行高,列宽。 HSSFWorkbookwb=newHSSFWorkbook(); HSSFSheetsheet=wb.createSheet(\"newsheet\");HSSFRowrow=sheet.createRow((short)0);//2是行高值 row.setRowHeight(2); //3是列号,4是列宽值sheet.setColumnWidth(3,4); //建工作薄 HSSFWorkbookwb=newHSSFWorkbook();//建名为example的工作表 HSSFSheetsheet=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);//在表中建行 HSSFRowrow=sheet.createRow(0);//建立单元格 HSSFCellcell[]=newHSSFCell[8];for(shorti=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实例Listlist=newArrayList(); ProductDataManagermgr=newProductDataManager();try{ list=mgr.listProductQuery(\"\\"\\"\\"\\"1999-2-1\\"2004-2-1\"); }catch(SrrdExceptione){ e.printStackTrace(); } //从List中取出数据放入工作表中 if(list!=null&&list.size()>0){ for(inti=0;i 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()); } } //将工作薄输出到输出流 ServletOutputStreamsos=response.getOutputStream();wb.write(sos);sos.close(); //也可输出成xls文件 Filefile=newFile(\"workbook.xls\");try{ FileOutputStreamfileOut=newFileOutputStream(file);wb.write(fileOut);fileOut.close(); }catch(IOExceptione){ e.printStackTrace(); } 52.设置JDK环境变量@echooff IFEXIST%1\\bin\\java.exe( rem如输入正确的Java2SDK安装目录,开始 设置环境变量 @setxJAVA_HOME%1 @setxpath%path%;%JAVA_HOME%\\bin@setxclasspath%classpath%;. @setxclasspath %classpath%;%JAVA_HOME%\\lib\ools.jar @setxclasspath %classpath%;%JAVA_HOME%\\lib\\dt.jar @setxclasspath %classpath%;%JAVA_HOME%\\jre\\lib\\rt.jar @echoon @echoJava2SDK环境参数设置完毕,正常退 出。 )ELSE( IF\"%1\"==\"\"( rem如没有提供安装目录,提示之后退出@echoon @echo没有提供Java2SDK的安装目录,不做任 何设置,现在退出环境变量设置。 )ELSE( rem如果提供非空的安装目录但没有 bin\\java.exe,则指定的目录为错误的目录 @echoon @echo非法的Java2SDK的安装目录,不做任何 设置,现在退出环境变量设置。 )) //http://sourceforge.net/projects/jregistrykey///importca.beq.util.win32.registry.*;//importjava.util.*;1.打开键 RegistryKeyr=new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\ShellFolders\");2.添加键 RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,\"Software\\\\BEQTechnologies\");r.create(); 9.写入字符串值 RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,\"Software\\\\BEQTechnologies\");RegistryValuev=newRegistryValue(\"myVal\ValueType.REG_SZ,\"data\");r.setValue(v); 6.获取DWORD值 RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,\"Software\\\\BEQTechnologies\");if(r.hasValue(\"myValue\")){ RegistryValuev=r.getValue(\"myValue\");v.setType(ValueType.REG_DWORD); }//if 53.选择文件夹对话框/* importjava.io.*;importjavax.swing.*;*/ JFileChooserchooser=newJFileChooser();chooser.setCurrentDirectory(newFile(\".\")); chooser.setFileFilter(newjavax.swing.filechooser.FileFilter(){ publicbooleanaccept(Filef){ returnf.getName().toLowerCase().endsWith(\".gif\") ||f.isDirectory(); } publicStringgetDescription(){ return\"GIFImages\"; } }); intr=chooser.showOpenDialog(null);if(r==JFileChooser.APPROVE_OPTION){ Stringname=chooser.getSelectedFile().getPath();//label.setIcon(newImageIcon(name)); } .删除空文件夹//importjava.io.*;Filef=newFile(%%1);if(isFolerNull(f)){ for(Filefile:f.listFiles()){ if(file.list().length==0){ System.out.println(file.getPath());file.delete(); } } } 55.发送数据到剪贴板/* importjava.awt.*; importjava.awt.datatransfer.*;*/ Clipboardclipboard=Toolkit.getDefaultToolkit().getSystemClipboard();TransferabletText=newStringSelection(%%1);clipboard.setContents(tText,null);56.从剪贴板中取数据 /* importjava.awt.*; importjava.awt.datatransfer.*;importjava.io.*;*/ //取得系统剪贴板里可传输的数据构造的Java对象Transferablet=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(UnsupportedFlavorExceptionex){ ex.printStackTrace(); }catch(IOExceptionex){ ex.printStackTrace(); } 57.获取文件路径的父路径 String%%2=%%1.substring(0,%%1.lastIndexOf(\"\\\\\")); 58.创建快捷方式//importjava.io.*;try{ PrintWriterpw=newPrintWriter(newFileOutputStream(\"C:/a.bat\"));pw.println(%%1);\"C:/a.txt\" pw.close(); } catch(IOExceptione){ e.printStackTrace(); } 59.弹出快捷菜单//MouseEvente JPopupMenujpm=newJPopupMenu();show(jpm,x,y); 60.文件夹复制到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent();Jfc.showDialog(null,%%1); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒Jfcif(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); LinkedList LinkedList folderList2.add(%%2+%%1.substring(%%1.lastIndexOf(\"\\\\\")));while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹Filefolders=newFile(folderList.peek());String[]file=folders.list();Filetemp=null;try{ for(inti=0;i temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp);FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator+(temp.getName()).toString()); byte[]b=newbyte[5120];intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush();output.close();input.close(); } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //System.out.println(\"复制整个文件夹内容操作出错\");e.printStackTrace(); } folderList.removeFirst();folderList2.removeFirst(); } 61.文件夹移动到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();62.目录下所有文件夹复制到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent();Jfc.showDialog(null,%%1); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒Jfcif(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); 63.目录下所有文件夹移动到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); .目录下所有文件复制到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); 65.目录下所有文件移动到整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();66.对目标压缩文件解压缩到指定文件夹/* importjava.io.*;importjava.util.zip.*;*/ StringzipFileName=%%1;StringextPlace=%%2; FilemyFolderPath=newFile(extPlace);try{ if(!myFolderPath.exists()){ myFolderPath.mkdir(); } }catch(Exceptione){ //新建目录操作出错 e.printStackTrace();return; }try{ ZipInputStreamin=newZipInputStream(newFileInputStream( zipFileName)); ZipEntryentry=null; while((entry=in.getNextEntry())!=null){ StringentryName=entry.getName();Filefile=newFile(extPlace,entryName);if(entry.isDirectory()){ file.mkdirs(); }else{ FileOutputStreamos=newFileOutputStream(file);//TransferbytesfromtheZIPfiletotheoutput//file byte[]buf=newbyte[4096];intlen; while((len=in.read(buf))>0){ os.write(buf,0,len); } os.close();in.closeEntry(); } } }catch(IOExceptione){ e.printStackTrace(); } 67.创建目录副本整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ JFileChooserJfc=newJFileChooser(\"请选择源路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser(\"请选择目标路径\");//建立选择档案对话方块盒JfcJfc.showDialog(null,%%1); if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); 68.打开网页 //importjava.io.*;try{ Stringcommand=\"C:\\\\ProgramFiles\\\\InternetExplorer\\\\Iexplore.exe\"+%%1;Runtime.getRuntime().exec(command); }catch(IOExceptionex){ ex.printStackTrace(); } 69.删除空文件夹整合操作/* importjava.io.*;importjava.util.*;importjavax.swing.*;*/ 70.获取磁盘所有分区后再把光驱盘符去除(用\"\\0\"代替),把结果放在数组allfenqu[]中,数组中每个元素代表一个分区盘符,不包括:\\\\这样的路径,allfenqu[]数组开始时存放的是所有盘符。 当我用这样的代码测试结果是正确的,光驱盘符会被去掉:Stringroot;//root代表盘符路径 for(i=0;i<20;i++)//0-20代表最大的盘符数{ root.Format(\"%c:\\\\\if(GetDriveType(root)==5) allfenqu[i]='\\0'; } 但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符:Stringroot;for(i=0;i<20;i++){ root=allfenqu[i]+\":\\\\\";if(GetDriveType(root)==5) allfenqu[i]='\\0'; } 71.激活一个程序或程序关联的文件//importjava.io.*;try{ Runtime.getRuntime().exec(%%1); }catch(IOExceptione){ e.printStackTrace(); } 72.HTTP下载/* importjava.io.*;*/ publicclassDownloadCSVFileActionextendsAction{ publicActionForwardexecute(ActionMappingmapping,ActionFormform, HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ try{ StringfileName=request.getParameter(\"fileName\"); longmaID=Long.parseLong(request.getParameter(\"maID\"));StringfilePath=request.getSession().getServletContext ().getRealPath(\"/\")+\"csv/\"+maID+\"/\"+fileName; Filefdown=newFile(filePath); intfilelength=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);byteb[]=newbyte[filelength]; FileInputStreamfi=newFileInputStream(fdown);OutputStreamo=response.getOutputStream();intn=0; while((n=fi.read(b))!=-1){ o.write(b,0,n); } fi.close();o.close();returnnull; }catch(Exceptione){ request.setAttribute(\"ERROR\e);returnmapping.findForward(\"error\"); } } } 对应的下载类型 privateStringgetContentType(StringfileName){ StringfileNameTmp=fileName.toLowerCase(); Stringret=\"\"; 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\"; } returnret; } 73.FTP下载/* importsun.net.ftp.FtpClient;importjava.io.*;importsun.net.*;*/ //如果文件在某个目录下,则加入fc.cd(\"foodir\");//比如要下载ftp://ftp.xx.com/index.html则:try{ FtpClientfc=newFtpClient(\"ftp.xx.com\");fc.login(\"username\intch; Filefi=newFile(\"c:\\\\index.html\"); RandomAccessFilegetFile=newRandomAccessFile(fi,\"rw\");getFile.seek(0); TelnetInputStreamfget=fc.get(\"index.html\"); DataInputStreamputs=newDataInputStream(fget);while((ch=puts.read())>=0){ getFile.write(ch); } fget.close();getFile.close();fc.closeServer(); } catch(IOExceptionex){ ex.printStackTrace(); } 74.写图像到剪切板setClipboardImage/* importjava.awt.*; importjava.awt.datatransfer.*;importjava.io.*; privatefinalImageimage;*/ Transferabletrans=newTransferable(){ publicDataFlavor[]getTransferDataFlavors(){ returnnewDataFlavor[]{DataFlavor.imageFlavor}; } publicbooleanisDataFlavorSupported(DataFlavorflavor){ returnDataFlavor.imageFlavor.equals(flavor); } publicObjectgetTransferData(DataFlavorflavor) throwsUnsupportedFlavorException,IOException{ if(isDataFlavorSupported(flavor)) returnimage; thrownewUnsupportedFlavorException(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null); 75.从剪贴板复制图像到窗体 76.删除文件夹下的所有文件且不删除文件夹下的文件夹//importjava.io.*;//importjava.util.*; LinkedList while(folderList.size()>0){ Filefile=newFile(folderList.poll());File[]files=file.listFiles(); ArrayList folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } } 78.拷贝文件名复制文件packagep1;importjava.io.*;importjava.awt.*; importjava.awt.datatransfer.*; publicclassVCFileCopy{ publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub// //取得系统剪贴板里可传输的数据构造的Java对象 Transferablet=Toolkit.getDefaultToolkit().getSystemClipboard() .getContents(null); try{ if(t!=null&&t.isDataFlavorSupported(DataFlavor.stringFlavor)){ //因为原系的剪贴板里有多种信息,如文字,图片,文件等 //先判断开始取得的可传输的数据是不是文字,如果是,取得这 些文字 Strings=(String)t.getTransferData(DataFlavor.stringFlavor);//同样,因为Transferable中的DataFlavor是多种类型的, //所以传入DataFlavor这个参数,指定要取得哪种类型的Data.System.out.println(s);intbytesum=0;intbyteread=0; Fileoldfile=newFile(s);try{ if(oldfile.exists()){//文件存在时 FileInputStreaminStream=new FileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(new File( \"C:\\\\\", oldfile.getName())); byte[]buffer=newbyte[5120]; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大 小 fs.write(buffer,0,byteread); } inStream.close(); } }catch(Exceptione){ System.out.println(\"复制单个文件操作出错\");e.printStackTrace(); } } }catch(UnsupportedFlavorExceptionex){ ex.printStackTrace(); }catch(IOExceptionex){ ex.printStackTrace(); } } } 79.开源程序库Xercesc-C++代码工程中内联importjava.io.*;importjava.util.*; importjava.util.regex.*;publicclassInlineXercesc{ privatefinalStringfilter=\".cpp\"; privateArrayList privatevoiddoSearch(Stringpath){ Filefilepath=newFile(path);if(filepath.exists()){ if(filepath.isDirectory()){ File[]fileArray=filepath.listFiles();for(Filef:fileArray){ if(f.isDirectory()){ doSearch(f.getPath()); }else{ if(f.getName().indexOf(filter)>=0){ for(Stringfile:all){ if (file.substring(file.lastIndexOf(\"\\\\\")+1) .equals(f.getName())){ fal2.add(f.getAbsolutePath()); } } } } } }else{ System.out.println(\"Couldn'topenthepath!\"); } }else{ System.out.println(\"ThepathhadbeenapointedwasnotExist!\"); } } publicInlineXercesc(Stringlib)throwsIOException{ StringSourceLib=\"D:\\\\Desktop\\\\大项目\\\\xerces-c-3.0.1\\\\src\"; Patternpattern=Pattern.compile(\"include.*?\"+lib+\".*?>\");//第一个参数为需 要匹配的字符串 Matchermatcher=pattern.matcher(\"\"); LinkedList StringenumDir=CurDir+\"\\\\\"+files2[l].getName()+\"\\\\\";LinkedList Filefile=newFile(folderList.poll());File[]files=file.listFiles(); for(inti=0;i folderList.add(files[i].getPath()); }else{ StringfileStr=files[i].getAbsolutePath(); //第2个参数开始,均为文件名。 BufferedReaderbr=null;Stringline;try{ br=newBufferedReader(new FileReader(fileStr));//打开文件 }catch(IOExceptione){ //没有打开文件,则产生异常System.err.println(\"Cannotread'\" +fileStr +\"':\"+e.getMessage()); continue; } StringBuildersb=newStringBuilder(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();//关闭文件 FileWriterfw2=newFileWriter(fileStr);fw2.write(sb.toString());fw2.flush();fw2.close(); } } } while(fal.size()>0){ Stringfile=fal.poll();//第2个参数开始,均为文件名。StringtargetPath=enumDir +file.substring(file.lastIndexOf(\"\\\\\")+1); if(!newFile(targetPath).exists()){ BufferedReaderbr=null;Stringline;try{ br=newBufferedReader(new FileReader(file));//打开文件 }catch(IOExceptione){ //没有打开文件,则产生异常 System.err.println(\"Cannotread'\"+file+ \"':\" +e.getMessage()); continue; } FileWriterfw=newFileWriter(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 while(folderListArr.size()>0){ Filefile=newFile(folderListArr.poll());File[]files=file.listFiles(); for(inti=0;i 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\")); } } } intcount=1;while(count>0){ doSearch(SourceLib);all.clear(); 为文件名。 1); FileReader(file1));//打开文件 +file1 {//读入一行,直到文件结束 配字符串 果有匹配的字符串,则输出 fal2.add(SourceLib line.substring( line.indexOf('<')+1,line.lastIndexOf('>')) while(fal2.size()>0){ Stringfile1=fal2.poll();//第2个参数开始,均 StringtargetPath=enumDir +file1.substring(file1.lastIndexOf(\"\\\\\")+ if(!newFile(targetPath).exists()){ BufferedReaderbr=null;Stringline;try{ br=newBufferedReader(new }catch(IOExceptione){ //没有打开文件,则产生异常System.err.println(\"Cannotread'\" +\"':\"+e.getMessage()); continue; } FileWriterfw;try{ fw=newFileWriter(targetPath);while((line=br.readLine())!=null) matcher.reset(line);//匹 if(matcher.find()){//如 +\"\\\\\"+ .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(IOExceptione){ e.printStackTrace(); } } } count=all.size(); } } } } publicstaticvoidmain(String[]args){ try{ newInlineXercesc(\"xercesc\");//将数据写入文件try{ FileWriterfw=newFileWriter(CurDir+\"\\\\DetailCpp.cmd\");fw.write(\"copyStdAfx.cpp+*.c+*.cpp\"+CurDir +\"\\\\StdAfx.cpp&&del*.c&&del*.cpp\"); fw.flush();fw.close(); }catch(IOExceptione){ e.printStackTrace(); } }catch(IOExceptione){} } } 80.提取包含头文件列表importjava.io.*; importjava.util.regex.*;importjava.util.*;publicclassInlineExt{ privateStringCurDir=System.getProperty(\"user.dir\");publicInlineExt(){ Patternpattern=Pattern.compile(\"include.*?\\\".*?.hpp\\\"\");//第一个参数为需要 匹配的字符串 Matchermatcher=pattern.matcher(\"\");Filedelfile=newFile(CurDir);File[]files2=delfile.listFiles();for(intl=0;l Set Filefile=newFile(files2[l].getPath(),\"StdAfx.cpp\");BufferedReaderbr=null;FileWriterfw=null;Stringline;try{ br=newBufferedReader(newFileReader(file));//打开文 件 while((line=br.readLine())!=null){ matcher.reset(line);//匹配字符串 if(matcher.find()){//如果有匹配的字符串,则 输出 ts.add(line.substring(line.indexOf('\\\"')+1, line .lastIndexOf('\\\"'))); } } Iterator Filefile2=newFile(files2[l],\"ReadMe.txt\");if(file2.exists()){ fw=newFileWriter(file2);while(it.hasNext()){ fw.write(\"#include\\\"\"+it.next()+ \"\\\"\\r\\n\"); } } }catch(IOExceptione){ //没有打开文件,则产生异常 System.err.println(\"Cannotread'\"+file+\"':\" +e.getMessage()); continue; }finally{ try{ if(br!=null) br.close(); if(fw!=null) fw.close(); }catch(IOExceptione){ e.printStackTrace(); } } } } } publicstaticvoidmain(String[]args){ newInlineExt(); } } 81.剪贴扳转换成打印字符importjava.awt.*; importjava.awt.datatransfer.*;importjava.io.*; publicclassClipBoard{ publicstaticvoidmain(String[]args){ //取得系统剪贴板里可传输的数据构造的Java对象Transferablet=Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); try{ if(t!=null &&t.isDataFlavorSupported(DataFlavor.stringFlavor)){ //因为原系的剪贴板里有多种信息,如文字,图片,文件 等 //先判断开始取得的可传输的数据是不是文字,如果是, 取得这些文字 Strings=(String)t .getTransferData(DataFlavor.stringFlavor); String[]arr=s.split(\"\\n\"); StringBuildersb=newStringBuilder(1024);for(Stringss:arr){ if(!ss.trim().equals(\"\")){ sb.append(\"w.WriteLine(\\\"ECHO\"+ ss.replace(\"^\\"^^\").replace(\"&\\"^&\").replace(\":\\"^:\").replace(\">\\"^>\").replace(\"<\ \"^<\").replace(\"|\\"^|\").replace(\"\\\"\\"^\\\"\").replace(\"\\\\\\"\\\\\\\\\").replace(\"\\\"\\"\\\\\\\"\")+\"\\\");\"); sb.append(\"\\r\\n\"); } } Clipboardclipboard= Toolkit.getDefaultToolkit().getSystemClipboard(); TransferabletText=newStringSelection(sb.toString());clipboard.setContents(tText,null); } }catch(UnsupportedFlavorExceptionex){ ex.printStackTrace(); }catch(IOExceptionex){ ex.printStackTrace(); } } } 82.把JButton或JTree组件写到一个流中/* 由于JButton和JTree都已经实现了Serializable接口,因此你所说的问题是可以做到的。使用ObjectInputStream读取文件中的对象,使用ObjectOutputStream把对象写入文件。如:*//* importjava.io.*;importjavax.swing.*;*/ publicclassSave{ publicstaticvoidmain(String[]args){ //Write JButtonbutton=newJButton(\"TESTButton\");JTreetree=newJTree();try{ ObjectOutputStreamoutForButton=newObjectOutputStream( newFileOutputStream(\"button\")); outForButton.writeObject(button);outForButton.close(); ObjectOutputStreamoutForTree=newObjectOutputStream( newFileOutputStream(\"tree\")); outForTree.writeObject(tree);outForTree.close(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } //Readtry{ ObjectInputStreaminForButton=newObjectInputStream( newFileInputStream(\"button\")); JButtonbuttonReaded=(JButton)inForButton.readObject(); ObjectInputStreaminForTree=newObjectInputStream( newFileInputStream(\"tree\")); JTreetreeReaded=(JTree)inForTree.readObject(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); }catch(ClassNotFoundExceptione){ 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中的事件监听机制,我们只要在程序中通过注册即可实现,下面是一个简单的例子: importcom.melloware.jintellitype.HotkeyListener;importcom.melloware.jintellitype.JIntellitype; publicclassHotKeyimplementsHotkeyListener{ staticfinalintKEY_1=88;staticfinalintKEY_2=;staticfinalintKEY_3=90;/** *该方法负责监听注册的系统热键事件* *@paramkey:触发的热键标识*/ publicvoidonHotKey(intkey){ switch(key){ caseKEY_1: System.out.println(\"ctrl+alt+I按下.........\");break; caseKEY_2: System.out.println(\"ctrl+alt+O按下.........\");break; caseKEY_3: System.out.println(\"系统退出..........\");destroy(); } } /** *解除注册并退出*/ voiddestroy(){ JIntellitype.getInstance().unregisterHotKey(KEY_1);JIntellitype.getInstance().unregisterHotKey(KEY_2);JIntellitype.getInstance().unregisterHotKey(KEY_3);System.exit(0); } /** *初始化热键并注册监听事件*/ voidinitHotkey(){ //参数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); } publicstaticvoidmain(String[]args){ HotKeykey=newHotKey();key.initHotkey(); //下面模拟长时间执行的任务while(true){ try{ Thread.sleep(10000); }catch(Exceptionex){ break; } } } } 偶尔,我们可以给用户添加一些快捷键,不管现在焦点在哪里。有个做法就是,任何组建上注册你的,但显然,这不是一个好做法java的toolkit可以直接添加一个,一下就是示例 Toolkittoolkit=Toolkit.getDefaultToolkit(); toolkit.addAWTEventListener(capListener,AWTEvent.KEY_EVENT_MASK|AWTEvent.MOUSE_EVENT_MASK|AWTEvent.WINDOW_EVENT_MASK);实现一个: classCapListenerimplementsAWTEventListener{ publicvoideventDispatched(AWTEventevent){} } 这就可以了 84.菜单勾选/取消完成后关闭计算机//importjava.io.*; publicclassParentimplementsICallBack{ publicstaticvoidmain(String[]args){ Parentparent=newParent();Threadson=newSon(parent);son.start(); } publicvoidoutput(){ try{ Runtime.getRuntime().exec(\"shutdown-f-s-t0\"); }catch(IOExceptione){ e.printStackTrace(); } } } /*内部线程类*/ classSonextendsThread{ privateICallBackevent; publicSon(ICallBackcallback){ event=callback; } publicvoidrun(){ try{ java.text.SimpleDateFormatfmt=newjava.text.SimpleDateFormat(\"yyyy-MM-ddHH:mm:ss\"); while(true){ Thread.currentThread().sleep(3000); event.output(fmt.format(newjava.util.Date()));Thread.currentThread().sleep(3000); } } catch(Exceptione) {} } } /*回调接口*/interfaceICallBack{ publicvoidoutput(); } 85.菜单勾选/取消完成后重新启动计算机//importjava.io.*; publicclassParentimplementsICallBack{ publicstaticvoidmain(String[]args){ Parentparent=newParent();Threadson=newSon(parent);son.start(); } publicvoidoutput(){ try{ Runtime.getRuntime().exec(\"shutdown-f-r-t0\"); }catch(IOExceptione){ e.printStackTrace(); } } } /*内部线程类*/ classSonextendsThread{ privateICallBackevent; publicSon(ICallBackcallback){ event=callback; } publicvoidrun(){ try{ java.text.SimpleDateFormatfmt=newjava.text.SimpleDateFormat(\"yyyy-MM-ddHH:mm:ss\"); while(true){ Thread.currentThread().sleep(3000); event.output(fmt.format(newjava.util.Date()));Thread.currentThread().sleep(3000); } } catch(Exceptione){} } } /*回调接口*/interfaceICallBack{ publicvoidoutput(); } 86.菜单勾选/取消完成后注销计算机//importjava.io.*; publicclassParentimplementsICallBack{ publicstaticvoidmain(String[]args){ Parentparent=newParent();Threadson=newSon(parent);son.start(); } publicvoidoutput(){ try{ Runtime.getRuntime().exec(\"shutdown-l\"); }catch(IOExceptione){ e.printStackTrace(); } } } /*内部线程类*/ classSonextendsThread{ privateICallBackevent; publicSon(ICallBackcallback){ event=callback; } publicvoidrun(){ try{ java.text.SimpleDateFormatfmt=newjava.text.SimpleDateFormat(\"yyyy-MM-ddHH:mm:ss\"); while(true){ Thread.currentThread().sleep(3000); event.output(fmt.format(newjava.util.Date()));Thread.currentThread().sleep(3000); } } catch(Exceptione){} } } /*回调接口*/interfaceICallBack{ publicvoidoutput(); } 87.菜单勾选/取消开机自启动程序 //http://sourceforge.net/projects/jregistrykey///importca.beq.util.win32.registry.*;//importjava.util.*; RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,\"Software\\\\BEQTechnologies\");RegistryValuev=newRegistryValue(\"run\ValueType.REG_SZ,\"data\");r.setValue(v); /////////////////////////////////////////////////////////////拖一个CheckBox 1、软件启动时给CheckBox重置状态: //http://sourceforge.net/projects/jregistrykey///importca.beq.util.win32.registry.*;//importjava.util.*; RegistryKeyR_local=Registry.LocalMachine; RegistryKeyR_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事件: privatevoidcheckBox1_CheckedChanged(objectsender,EventArgse){ stringR_startPath=Application.ExecutablePath;if(checkBox1.Checked==true){ RegistryKeyR_local=Registry.LocalMachine;RegistryKeyR_run= R_local.CreateSubKey(@\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"); R_run.SetValue(\"BirthdayTipF\R_startPath);R_run.Close();R_local.Close(); }else{ try{ RegistryKeyR_local=Registry.LocalMachine;RegistryKeyR_run= R_local.CreateSubKey(@\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"); R_run.Deletue(\"BirthdayTipF\false);R_run.Close();R_local.Close(); } catch(Exceptionex){ MessageBox.Show(\"您需要管理员权限修改\\"提示\ MessageBoxButtons.OK,MessageBoxIcon.Error); throw; } } } 88.菜单勾选/取消自动登录系统.模拟键盘输入字符串/* importjava.awt.*; importjava.awt.event.*;throwsException{*/ staticRobotrobot;static{ try{ robot=newRobot(); }catch(AWTExceptione){} } staticvoidsendKey(Stringks){ KeyStorek=KeyStore.findKeyStore(ks);if(k!=null){ if(k.upCase) upCase(k.v); else sendKey(k.v); }else{ for(inti=0;i sendKey(c); } elseif(c>='a'&&c<='z'){ sendKey(c-32); } elseif(c>='A'&&c<='Z'){ upCase(c); } } } } privatestaticvoidupCase(intkc){ robot.keyPress(KeyEvent.VK_SHIFT);robot.keyPress(kc);robot.keyRelease(kc); robot.keyRelease(KeyEvent.VK_SHIFT); } privatestaticvoidsendKey(intkc){ robot.keyPress(kc);robot.keyRelease(kc); } staticclassKeyStore{ //specialkeys finalstaticKeyStore[]sp={ newKeyStore(\"{Tab}\ newKeyStore(\"{Enter}\newKeyStore(\"{PUp}\upnewKeyStore(\"{<}\ newKeyStore(\"{Up}\keynewKeyStore(\"{At}\ newKeyStore(\"{Dollar}\ }; Stringk;intv; booleanupCase; KeyStore(Stringk,intv){ this(k,v,false); } KeyStore(Strings,inti,booleanup){ k=s;v=i; upCase=up; } staticKeyStorefindKeyStore(Stringk){ for(inti=0;i returnsp[i]; } returnnull; } } Thread.sleep(1000);sendKey(\"{Tab}\");//tabsendKey(\"{<}\");//< sendKey(\"abcd123AHahahAA\");//abcd123AHahahAAsendKey(\"{At}\");//@sendKey(\"{Dollar}\");//$sendKey(\"{Up}\");//uparrow 90.提取PDF文件中的文本 //http://incubator.apache.org/pdfbox//* importjava.io.*; importorg.pdfbox.pdfparser.*;importorg.pdfbox.pdmodel.*;importorg.pdfbox.util.*;*/ publicclassSimplePDFReader{ /** *simplyreaderallthetextfromapdffile. *Youhavetodealwiththeformatoftheoutputtextbyyourself.*2008-2-25 *@parampdfFilePathfilepath*@returnalltextinthepdffile*/ publicstaticStringgetTextFromPDF(StringpdfFilePath){ Stringresult=null; FileInputStreamis=null; PDDocumentdocument=null;try{ is=newFileInputStream(pdfFilePath);PDFParserparser=newPDFParser(is);parser.parse(); document=parser.getPDDocument(); PDFTextStripperstripper=newPDFTextStripper();result=stripper.getText(document); }catch(FileNotFoundExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace(); }catch(IOExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace(); }finally{ if(is!=null){ try{ is.close(); }catch(IOExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace(); } } if(document!=null){ try{ document.close(); }catch(IOExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace(); } } } returnresult; } } 得到PDF的文本内容之后,自己根据文件的格式,取得想要的文本(这里我找的就是文章的标题,在文本中恰巧都是文件的第一行的内容),然后通过java的File相关api,对文件进行更名操作。importjava.io.File; importjava.io.FilenameFilter; publicclassPaperNameMender{ publicstaticvoidchangePaperName(StringfilePath){ //使用SimplePDFReader得到pdf文本 Stringts=SimplePDFReader.getTextFromPDF(filePath);//取得一行内容 Stringresult=ts.substring(0,ts.indexOf('\\n'));//得到源文件名中的最后一个逗点.的位置intindex=filePath.indexOf('.'); intnextIndex=filePath.indexOf('.',index+1);while(nextIndex!=-1){ index=nextIndex; nextIndex=filePath.indexOf('.',index+1); } //合成新文件名 StringnewFilename=filePath.substring(0,index)+\"\"+ result.trim()+\".pdf\"; FileoriginalFile=newFile(filePath);//修改文件名 originalFile.renameTo(newFile(newFilename)); } } 91.操作内存映射文件/* importjava.io.*;importjava.nio.*; importjava.nio.channels.*; */ privatestaticintlength=0x8FFFFFF;//128MbMappedByteBufferout= newRandomAccessFile(\"test.dat\\"rw\").getChannel().map(FileChannel.MapMode.READ_WRITE,0,length);for(inti=0;i 92.1取得Runtime.getRuntime().exec(\"cmd/cdir\")的输入输出//importjava.io.*;try{ Stringcommand=\"cmd/cdir\"; Processproc=Runtime.getRuntime().exec(command); InputStreamReaderir=newInputStreamReader(proc.getInputStream());LineNumberReaderlnr=newLineNumberReader(ir);Stringline; while((line=lnr.readLine())!=null){ System.out.println(line); } }catch(IOExceptione){ e.printStackTrace(); } 92.2利用ProcessBuilder来创建Process对象,执行外部可执行程序////Eg1: //Stringaddress=null;// //Stringos=System.getProperty(\"os.name\");//System.out.println(os);// //if(os!=null){ //if(os.startsWith(\"Windows\")){//try{ //ProcessBuilderpb=newProcessBuilder(\"ipconfig\\"/all\");//Processp=pb.start();// //BufferedReaderbr=newBufferedReader(//newInputStreamReader(p.getInputStream()));// //Stringline; //////////////////////////////////////////////////////////////////////////////////////// while((line=br.readLine())!=null){ if(line.indexOf(\"PhysicalAddress\")!=-1){intindex=line.indexOf(\":\"); address=line.substring(index+1);break;}} br.close(); address=address.trim();}catch(IOExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace();} }elseif(os.startsWith(\"Linux\")){try{ ProcessBuilderpb=newProcessBuilder(\"ifconfig\\"/all\"); Processp=pb.start(); BufferedReaderbr=newBufferedReader( newInputStreamReader(p.getInputStream()));Stringline; while((line=br.readLine())!=null){intindex=line.indexOf(\"硬件地址\");if(index!=-1){ address=line.substring(index+4);break;}} br.close(); address=address.trim();}catch(IOExceptione){e.printStackTrace();}}} //Eg2:try{ Processproc; proc=Runtime.getRuntime().exec(\"cmd.exe\"); BufferedReaderread=newBufferedReader(newInputStreamReader(proc.getInputStream())); newThread(newEcho(read)).start(); //////////////////////////////////////}} PrintWriterout=newPrintWriter(newOutputStreamWriter(proc.getOutputStream())); BufferedReaderin=newBufferedReader(newInputStreamReader(System.in)); Stringinstr=in.readLine();while(!\"exit\".equals(instr)){instr=in.readLine();out.println(instr);out.flush();} in.readLine();read.close();out.close(); }catch(IOExceptione){ //TODOAuto-generatedcatchblocke.printStackTrace();} classEchoimplementsRunnable{ privateBufferedReaderread; publicEcho(BufferedReaderread){ this.read=read; } publicvoidrun(){ try{ Stringline=read.readLine();while(line!=null){ System.out.println(line);line=read.readLine(); } System.out.println(\"---执行完毕:\"); }catch(IOExceptionex){ ex.printStackTrace(); } } } 93.接受邮件 //importjavax.mail.*; publicclassUserAuthenticationextendsAuthenticator{ privateStringuserName;privateStringpassword; publicvoidsetPassword(Stringpassword){ this.password=password; } publicvoidsetUserName(StringuserName){ this.userName=userName; } publicPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(userName,password); } } //ReceiveMailTest.javaimportjavax.mail.*;importjava.io.*;importjava.util.*;importjavax.mail.*;publicclassReceiveMailTest{ privateFolderinbox;privateStorestore; //连接邮件服务器,获得所有邮件的列表 publicMessage[]getMail(Stringhost,Stringname,Stringpassword)throws Exception{ Propertiesprop=newProperties();prop.put(\"mail.pop3.host\host); Sessionsession=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();FetchProfileprofile=newFetchProfile();profile.add(FetchProfile.Item.ENVELOPE);profile.add(FetchProfile.Item.FLAGS);profile.add(\"X-Mailer\"); inbox.fetch(msg,profile);returnmsg; } //处理任何一种邮件都需要的方法 privatevoidhandle(Messagemsg)throwsException{ System.out.println(\"邮件主题:\"+msg.getSubject()); System.out.println(\"邮件作者:\"+msg.getFrom()[0].toString());System.out.println(\"发送日期:\"+msg.getSentDate());} //处理文本邮件 publicvoidhandleText(Messagemsg)throwsException{ this.handle(msg); System.out.println(\"邮件内容:\"+msg.getContent()); } //处理Multipart邮件,包括了保存附件的功能 publicvoidhandleMultipart(Messagemsg)throwsException{ Stringdisposition;BodyPartpart; //1、从Message中取到Multipart //2、遍历Multipart里面得所有bodypart//3、判断BodyPart是否是附件,//如果是,就保存附件//否则就取里面得文本内容 Multipartmp=(Multipart)msg.getContent(); intmpCount=mp.getCount();//Miltipart的数量,用于除了多个part,比如多个附 件 for(intm=0;m part=mp.getBodyPart(m); disposition=part.getDisposition(); if(disposition!=null&&disposition.equals(Part.ATTACHMENT)){//判断 是否有附件 this.saveAttach(part);//这个方法负责保存附件,注释掉是因为 附件可能有病毒,请清理信箱之后再取掉注释 }else{ System.out.println(part.getContent()); } } } privatevoidsaveAttach(BodyPartpart)throwsException{ Stringtemp=part.getFileName();//得到未经处理的附件名字System.out.println(\"*********temp=\"+temp); System.out.println(\"**********\"+baseDecoder(temp)); Strings=temp;//temp.substring(11,temp.indexOf(\"?=\")-1);//去到header和 footer //文件名一般都经过了base编码,下面是解码StringfileName=s;//this.baseDecoder(s);System.out.println(\"有附件:\"+fileName); InputStreamin=part.getInputStream(); FileOutputStreamwriter=newFileOutputStream(newFile(\"d:/temp/\"+fileName));byte[]content=newbyte[255];intread=0; while((read=in.read(content))!=-1){ writer.write(content); } writer.close();in.close(); } //base解码 privateStringbaseDecoder(Strings)throwsException{ sun.misc.BASEDecoderdecoder=newsun.misc.BASEDecoder();byte[]b=decoder.decodeBuffer(s); //sun.misc.BASEEncoderencoder=newsun.misc.BASEEncoder();//Stringstr=encoder.encode(bytes); return(newString(b)); } //关闭连接 publicvoidclose()throwsException{ if(inbox!=null){ inbox.close(false); } if(store!=null){ store.close(); } } publicstaticvoidmain(Stringargs[]){ Stringhost=\"192.168.1.245\";Stringname=\"user2\"; Stringpassword=\"yya\"; ReceiveMailTestreceiver=newReceiveMailTest();try{ Message[]msg=receiver.getMail(host,name,password); for(inti=0;i receiver.handleText(msg[i]); }else{ receiver.handleMultipart(msg[i]); } System.out.println(\"****************************\"); } receiver.close(); }catch(Exceptione){ e.printStackTrace();System.out.println(e); } } } 94.发送邮件 //importjavax.mail.*; publicclassUserAuthenticationextendsAuthenticator{ privateStringuserName;privateStringpassword; publicvoidsetPassword(Stringpassword){ this.password=password; } publicvoidsetUserName(StringuserName){ this.userName=userName; } publicPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(userName,password); } } //SendMailTest.javaimportjava.io.*; importjavax.mail.internet.*;importjavax.mail.*;importjava.io.*;importjava.util.*;importjavax.mail.*; importjavax.mail.internet.*;importjava.util.*; importjavax.activation.*;importjavax.mail.*;publicclassSendMailTest{ publicSendMailTest(){} publicstaticvoidmain(String[]args)throwsException{ StringsmtpServer=\"192.168.1.245\";StringuserName=\"user2\";Stringpassword=\"yya\"; StringfromAddress=\"user1@mailserver\";StringtoAddress=\"user2@mailserver\"; Stringsubject=\"邮件标题\";Stringcontent=\"邮件内容\"; StringattachFile1=\"d:/temp/test.txt\";StringattachFile2=\"d:/temp/test2.txt\"; SendMailTestsendMail=newSendMailTest(); Sessionsession=sendMail.getSession(smtpServer,userName,password);if(session!=null){ String[]files={attachFile1,attachFile2}; //Messagemsg=sendMail.getMessage(session,subject,content,files);Messagemsg=sendMail.getMessage(session,subject,content); if(msg!=null){ //发送源地址 msg.setFrom(newInternetAddress(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);//发送邮件 booleanbool=sendMail.sendMail(msg);if(bool){ System.out.println(\"发送成功\"); }else{ System.out.println(\"发送失败\"); } } } } publicSessiongetSession(StringsmtpServer,StringuserName,Stringpassword){ //192.168.1.245//user2//yya Sessionsession=null;try{ Propertiesprops=newProperties(); props.put(\"mail.smtp.host\smtpServer);//例如:202.108.44.206 smtp.163.com props.put(\"mail.smtp.auth\\"true\");//认证是否设置 UserAuthenticationauthen=newUserAuthentication();authen.setPassword(password);authen.setUserName(userName); session=Session.getDefaultInstance(props,authen); }catch(Exceptione){ e.printStackTrace(); } returnsession; } publicMessagegetMessage(Sessionsession,Stringsubject,Stringtext){ Messagemsg=null;try{ msg=newMimeMessage(session); msg.setText(text); msg.setSubject(subject); }catch(Exceptione){ e.printStackTrace(); } returnmsg; } publicbooleansendMail(Messagemsg){ booleanbool=false;try{ Transport.send(msg);bool=true; }catch(MessagingExceptionex){ ex.printStackTrace(); } returnbool; } publicMessagegetMessage(Sessionsession,Stringsubject,Stringtext,String[]archives){ //d:/temp/saa.txtMessagemsg=null;try{ MultipartcontentPart=newMimeMultipart();//生成Message对象 msg=newMimeMessage(session);//设置邮件内容 msg.setContent(contentPart);//设置邮件标题 msg.setSubject(subject); //组织邮件内容,包括邮件的文本内容和附件//1邮件文本内容 MimeBodyParttextPart=newMimeBodyPart();textPart.setText(text); //将文本部分,添加到邮件内容contentPart.addBodyPart(textPart); //2附件 if(archives!=null){ for(inti=0;i Stringfilename=archives[i];//得到数据源 FileDataSourcefds=newFileDataSource(filename);//得到附件本身并至入BodyPart archivePart.setDataHandler(newDataHandler(fds));//得到文件名同样至入BodyPart archivePart.setFileName(fds.getName());//将附件添加到附件集 contentPart.addBodyPart(archivePart); } } }catch(Exceptione){ e.printStackTrace(); } returnmsg; } /** *获取文本文件内容*@parampathString*@throwsIOException*@returnString*/ publicStringgetFile(Stringpath)throwsIOException{ //读取文件内容 char[]chrBuffer=newchar[10];//缓冲十个字符intintLength; Strings=\"\";//文件内容字符串 FileReaderfis=newFileReader(path); while((intLength=fis.read(chrBuffer))!=-1){ Stringtemp=String.valueOf(chrBuffer);//转换字符串s=s+temp;//累加字符串 } returns; } } 95.报表相关 //http://www.jfree.org/jfreechart//* importjava.io.*;importjava.awt.*; importorg.jfree.chart.*; importorg.jfree.chart.title.TextTitle; importorg.jfree.data.general.*;*/ Stringtitle=\"梦泽科技员工学历情况统计\"; DefaultPieDatasetpiedata=newDefaultPieDataset();piedata.setValue(\"大专\8.1);piedata.setValue(\"大学\27.6);piedata.setValue(\"硕士\53.2); piedata.setValue(\"博士及以上\19.2);piedata.setValue(\"大专以下\1.9); JFreeChartchart=ChartFactory.createPieChart(title,piedata,true,true,true);chart.setTitle(newTextTitle(title,newFont(\"宋体\Font.BOLD,25))); chart.addSubtitle(newTextTitle(\"最后更新日期:2005年5月19日\newFont(\"楷书\Font.ITALIC,18))); chart.setBackgroundPaint(Color.white);try{ ChartUtilities.saveChartAsJPEG(newFile(\"PieChart.jpg\"),chart,360,300); }catch(IOExceptionexz){ System.out.print(\"....Cant′tCreateimageFile\"); } 96.全屏幕截取/* importjava.awt.*; importjava.awt.image.*;importjava.io.*; importjavax.imageio.*;*/try{ Dimensiond=Toolkit.getDefaultToolkit().getScreenSize(); BufferedImagescreenshot=(newRobot()) .createScreenCapture(newRectangle(0,0, (int)d.getWidth(),(int)d.getHeight())); //根据文件前缀变量和文件格式变量,自动生成文件名Stringname=%%1+\".\" +%%2;//\"png\" Filef=newFile(name); ImageIO.write(screenshot,%%2,f); }catch(Exceptionex){ System.out.println(ex); }97.区域截幕/* importjava.awt.*; importjava.awt.image.*;importjava.io.*;importjava.util.*; importjavax.imageio.*;*/ interfaceImageType{ publicfinalstaticStringJPG=\"JPG\";publicfinalstaticStringPNG=\"PNG\";publicfinalstaticStringGIF=\"GIF\"; } publicclassScreenDumpHelper{ /**ScreenDumpHelper静态对象*/ privatestaticScreenDumpHelperdefaultScreenDumpHelper;publicstaticScreenDumpHelpergetDefaultScreenDumpHelper(){ if(defaultScreenDumpHelper==null) returnnewScreenDumpHelper(); returndefaultScreenDumpHelper; } publicScreenDumpHelper(){ Dimensiondime=Toolkit.getDefaultToolkit().getScreenSize();this.setScreenArea(newRectangle(dime)); } privateRectanglescreenArea; publicRectanglegetScreenArea(){ returnthis.screenArea; } publicvoidsetScreenArea(RectanglescreenArea){ this.screenArea=screenArea; } publicvoidsetScreenArea(intx,inty,intwidth,intheight){ this.screenArea=newRectangle(x,y,width,height); } privateBufferedImagegetBufferedImage()throwsAWTException{ BufferedImageimgBuf=null;; imgBuf=(newRobot()).createScreenCapture(this.getScreenArea());returnimgBuf; } /** *将图像数据写到输出流中去,方便再处理* *@paramfileFormat*@paramoutput*@return*/ publicbooleansaveToOutputStream(StringfileFormat,OutputStreamoutput){ try{ ImageIO.write(this.getBufferedImage(),fileFormat,output); }catch(AWTExceptione){ returnfalse; //e.printStackTrace(); }catch(IOExceptione){ returnfalse; //e.printStackTrace(); } returntrue; } /** *根据文件格式返回随机文件名称* *@paramfileFormat*@return*/ publicStringgetRandomFileName(StringfileFormat){ return\"screenDump_\"+(newDate()).getTime()+\".\"+fileFormat; } /** *抓取指定区域的截图到指定格式的文件中--这个函数是核心,所有的都是围绕它来 展开的*图片的编码并不是以后缀名来判断:比如s.jpg *如果其采用png编码,那么这个图片就是png格式的* *@paramfileName*@paramfileFormat*@returnboolean*/ publicbooleansaveToFile(StringfileName,StringfileFormat){ if(fileName==null) fileName=getRandomFileName(fileFormat); try{ FileOutputStreamfos=newFileOutputStream(fileName);this.saveToOutputStream(fileFormat,fos); }catch(FileNotFoundExceptione){ System.out.println(\"非常规文件或不能创建抑或覆盖此文件:\"+ fileName); e.printStackTrace(); } returntrue; } /** *抓取指定Rectangle区域的截图到指定格式的文件中* *@paramfileName*@paramfileFormat*@paramscreenArea*@return*/ publicbooleansaveToFile(StringfileName,StringfileFormat, RectanglescreenArea){ this.setScreenArea(screenArea); returnthis.saveToFile(fileName,fileFormat); } /** *抓取指定区域的截图到指定格式的文件中* *@paramfileName*@paramfileFormat*@paramx*@paramy*@paramwidth*@paramheight*/ publicbooleansaveToFile(StringfileName,StringfileFormat,intx,inty, intwidth,intheight){ this.setScreenArea(x,y,width,height); returnthis.saveToFile(fileName,fileFormat); } /** *将截图使用JPG编码* *@paramfileName*/ publicvoidsaveToJPG(StringfileName){ this.saveToFile(fileName,ImageType.JPG); } publicvoidsaveToJPG(StringfileName,RectanglescreenArea){ this.saveToFile(fileName,ImageType.JPG,screenArea); } publicvoidsaveToJPG(StringfileName,intx,inty,intwidth,intheight){ this.saveToFile(fileName,ImageType.JPG,x,y,width,height); } /** *将截图使用PNG编码* *@paramfileName*/ publicvoidsaveToPNG(StringfileName){ this.saveToFile(fileName,ImageType.PNG); } publicvoidsaveToPNG(StringfileName,RectanglescreenArea){ this.saveToFile(fileName,ImageType.PNG,screenArea); } publicvoidsaveToPNG(StringfileName,intx,inty,intwidth,intheight){ this.saveToFile(fileName,ImageType.PNG,x,y,width,height); } publicvoidsaveToGIF(StringfileName){ thrownewUnsupportedOperationException(\"不支持保存到GIF文件\");//this.saveToFile(fileName,ImageType.GIF); } /** *@paramargs*/ publicstaticvoidmain(String[]args){ for(inti=0;i<5;i++) ScreenDumpHelper.getDefaultScreenDumpHelper().saveToJPG(null, i*150,i*150,400,300); } } 98.计算文件MD5值/* importjava.io.*;importjava.math.*; importjava.security.*;importjava.util.*;*/ Filefile=newFile(%%1);if(!file.isFile()){returnnull;} MessageDigestdigest=null;FileInputStreamin=null; bytebuffer[]=newbyte[1024];intlen;try{ digest=MessageDigest.getInstance(\"MD5\");in=newFileInputStream(file); while((len=in.read(buffer,0,1024))!=-1){digest.update(buffer,0,len);} in.close(); }catch(Exceptione){e.printStackTrace();returnnull;} BigIntegerbigInt=newBigInteger(1,digest.digest());returnbigInt.toString(16);} 99.计算获取文件夹中文件的MD5值/* importjava.io.*;importjava.math.*;importjava.security.*;importjava.util.*;*/ publicstaticStringgetFileMD5(Filefile){if(!file.isFile()){returnnull;} MessageDigestdigest=null;FileInputStreamin=null; bytebuffer[]=newbyte[1024];intlen;try{ digest=MessageDigest.getInstance(\"MD5\");in=newFileInputStream(file); while((len=in.read(buffer,0,1024))!=-1){ digest.update(buffer,0,len); } in.close(); }catch(Exceptione){e.printStackTrace();returnnull;} BigIntegerbigInt=newBigInteger(1,digest.digest());returnbigInt.toString(16); }/** *获取文件夹中文件的MD5值*@paramfile *@paramlistChild;true递归子目录中的文件*@return*/ publicstaticMap // Map Filefiles[]=file.listFiles();for(inti=0;i map.putAll(getDirMD5(f,listChild));}else{ md5=getFileMD5(f);if(md5!=null){ map.put(f.getPath(),md5);}}} returnmap;} getDirMD5(%%1,%%2); 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务