• Java文件操作大全


       1 1.创建文件夹
       2 //import java.io.*;
       3 File myFolderPath = new File(%%1);
       4 try {
       5 if (!myFolderPath.exists())
       6 myFolderPath.mkdir();
       7 }
       8 catch (IOException e) {
       9 System.err.println("新建目录操作出错");
      10 }
      11 
      12 2.创建文件
      13 //import java.io.*;
      14 File myFilePath = new File(%%1);
      15 try {
      16 if (!myFilePath.exists())
      17 myFilePath.createNewFile();
      18 FileWriter resultFile = new FileWriter(myFilePath);
      19 PrintWriter myFile = new PrintWriter(resultFile);
      20 myFile.println(%%2);
      21 myFile.flush();
      22 resultFile.close();
      23 }
      24 catch (IOException e) {
      25 System.err.println("新建文件操作出错");
      26 }
      27 
      28 3.删除文件
      29 //import java.io.*;
      30 File myDelFile = new File(%%1);
      31 try {
      32 if(myDelFile.delete())
      33 {
      34 %%2
      35 }
      36 }
      37 catch (IOException e) {
      38 System.err.println("删除文件操作出错");
      39 }
      40 
      41 4.删除文件夹
      42 /*
      43 import java.io.*;
      44 import java.util.*;
      45 */
      46 LinkedList<String> folderList = new LinkedList<String>();
      47 folderList.add(%%1);
      48 while (folderList.size() > 0) {
      49 File file = new File((String)folderList.poll());
      50 File[] files = file.listFiles();
      51 ArrayList<File> fileList = new ArrayList<File>();
      52 for (int i = 0; i < files.length; i++) {
      53 if (files[i].isDirectory()) {
      54 folderList.add(files[i].getPath());
      55 } else {
      56 fileList.add(files[i]);
      57 }
      58 }
      59 for (File f : fileList) {
      60 f.delete();
      61 }
      62 }
      63 folderList = new LinkedList<String>();
      64 folderList.add(%%1);
      65 while (folderList.size() > 0) {
      66 File file = new File((String)folderList.getLast());
      67 if (file.delete())
      68 folderList.removeLast();
      69 else {
      70 File[] files = file.listFiles();
      71 for (int i = 0; i < files.length; i++) {
      72 folderList.add(files[i].getPath());
      73 }
      74 }
      75 }
      76 
      77 5.删除一个文件下夹所有的文件夹
      78 /*
      79 import java.io.*;
      80 private static LinkedList<String> folderList=null;
      81 */
      82 File delfile=new File(%%1);
      83 File[] files=delfile.listFiles();
      84 for(int i=0;i<files.length;i++){
      85 if(files[i].isDirectory()){
      86 if(!files[i].delete()){
      87 folderList = new LinkedList<String>();
      88 folderList.add(files[i]);
      89 while (folderList.size() > 0) {
      90 File file = new File((String)folderList.poll());
      91 File[] files = file.listFiles();
      92 ArrayList<File> fileList = new ArrayList<File>();
      93 for (int i = 0; i < files.length; i++) {
      94 if (files[i].isDirectory())
      95 folderList.add(files[i].getPath());
      96 else
      97 fileList.add(files[i]);
      98 }
      99 for (File f : fileList)
     100 f.delete();
     101 }
     102 folderList = new LinkedList<String>();
     103 folderList.add(files[i]);
     104 while (folderList.size() > 0) {
     105 File file = new File((String)folderList.getLast());
     106 if (file.delete())
     107 folderList.removeLast();
     108 else {
     109 File[] files = file.listFiles();
     110 for (int i = 0; i < files.length; i++) {
     111 folderList.add(files[i].getPath());
     112 }
     113 }
     114 }
     115 }
     116 }
     117 }
     118 
     119 6.清空文件夹
     120 //import java.io.*;
     121 File delfilefolder=new File(%%1);
     122 if (!delfilefolder.exists() && !delfilefolder.delete()){
     123 LinkedList<String> folderList = new LinkedList<String>();
     124 folderList.add(delfilefolder.getAbsolutePath());
     125 while (folderList.size() > 0) {
     126 File file = new File((String)folderList.poll());
     127 File[] files = file.listFiles();
     128 ArrayList<File> fileList = new ArrayList<File>();
     129 for (int i = 0; i < files.length; i++) {
     130 if (files[i].isDirectory())
     131 folderList.add(files[i].getPath());
     132 else
     133 fileList.add(files[i]);
     134 }
     135 for (File f : fileList)
     136 f.delete();
     137 }
     138 folderList = new LinkedList<String>();
     139 folderList.add(delfilefolder.getAbsolutePath());
     140 while (folderList.size() > 0) {
     141 File file = new File((String)folderList.getLast());
     142 if (file.delete())
     143 folderList.removeLast();
     144 else {
     145 File[] files = file.listFiles();
     146 for (int i = 0; i < files.length; i++) {
     147 folderList.add(files[i].getPath());
     148 }
     149 }
     150 }
     151 }
     152 delfilefolder.mkdir();
     153 
     154 7.读取文件
     155 //import java.io.*;
     156 7.1.操作系统默认编码
     157 FileReader fr=new FileReader(%%1);
     158 BufferedReader br = new BufferedReader();
     159 String %%2=nul;
     160 try {
     161 while ((%%2 = reader.readLine()) != null) {
     162 %%3
     163 }
     164 } catch (IOException e) {
     165 e.printStackTrace();
     166 } finally{
     167 try {
     168 br.close();
     169 fr.close();
     170 } catch (IOException e) {
     171 e.printStackTrace();
     172 }
     173 }
     174 
     175 7.2.UTF-8编码
     176 FileInputStream fis=new FileInputStream(new File(%%1));
     177 InputStreamReader read = new InputStreamReader(fis,"UTF-8");
     178 BufferedReader reader=new BufferedReader(read);
     179 String %%2=null;
     180 try {
     181 while ((%%2 = reader.readLine()) != null) {
     182 %%3
     183 }
     184 } catch (IOException e) {
     185 e.printStackTrace();
     186 } finally{
     187 try {
     188 br.close();
     189 read.close();
     190 fis.close();
     191 } catch (IOException e) {
     192 e.printStackTrace();
     193 }
     194 }
     195 
     196 7.3.分块读取
     197 FileInputStream fis=new FileInputStream(new File(%%1));
     198 byte[] buffer=new byte[10240];
     199 try {
     200 int byteread;
     201 while ((byteread=fis.read(buffer)) != -1) {
     202 String %%2=new String(buffer);
     203 %%3
     204 }
     205 } catch (IOException e) {
     206 e.printStackTrace();
     207 } finally{
     208 try {
     209 read.close();
     210 fis.close();
     211 } catch (IOException e) {
     212 e.printStackTrace();
     213 }
     214 }
     215 
     216 8.写入文件
     217 //import java.io.*;
     218 8.1.操作系统默认编码
     219 try {
     220 FileWriter fw = new FileWriter(%%1);
     221 fw.write(%%2);
     222 fw.flush();
     223 fw.close();
     224 } catch (IOException e) {
     225 e.printStackTrace();
     226 }
     227 
     228 8.2.UTF-8编码
     229 try {
     230 OutputStreamWriter out = new OutputStreamWriter(
     231 new FileOutputStream(%%1),"UTF-8");
     232 out.write(sb.toString());
     233 out.flush();
     234 out.close();
     235 } catch (UnsupportedEncodingException e) {
     236 e.printStackTrace();
     237 } catch (FileNotFoundException e){
     238 e.printStackTrace();
     239 } catch (IOException e){
     240 e.printStackTrace();
     241 }
     242 
     243 9.写入随机文件
     244 //import java.io.*;
     245 try {
     246 RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");
     247 long lg=logFile.length();
     248 logFile.seek(%%2);
     249 logFile.writeByte(%%3);
     250 }catch(IOException ioe){
     251 System.out.println("无法写入文件:"+ioe.getMessage());
     252 }
     253 
     254 10.读取文件属性
     255 //import java.io.*;
     256 // 文件属性的取得
     257 File af = new File(%%1);
     258 if (af.exists()) {
     259 System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());
     260 System.out.println(f.isFile() ? "是文件" : "不是文件");
     261 System.out.println(f.isDirectory() ? "是目录" : "不是目录");
     262 System.out.println(f.canRead() ? "可读取" : "不");
     263 System.out.println(f.canWrite() ? "是隐藏文件" : "");
     264 System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));
     265 } else {
     266 System.out.println(f.getName() + "的属性如下:");
     267 System.out.println(f.isFile() ? "是文件" : "不是文件");
     268 System.out.println(f.isDirectory() ? "是目录" : "不是目录");
     269 System.out.println(f.canRead() ? "可读取" : "不");
     270 System.out.println(f.canWrite() ? "是隐藏文件" : "");
     271 System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));
     272 }
     273 if(f.canRead()){
     274 %%2
     275 }
     276 if(f.canWrite()){
     277 %%3
     278 }
     279 
     280 11.写入属性
     281 //import java.io.*;
     282 File filereadonly=new File(%%1);
     283 try {
     284 boolean %%2=filereadonly.setReadOnly();
     285 }
     286 catch (IOException e) {
     287 System.err.println("拒绝写访问:"+e.printStackTrace());
     288 }
     289 
     290 12.枚举一个文件夹中的所有文件
     291 /*
     292 import java.io.*;
     293 import java.util.*;
     294 */
     295 LinkedList<String> folderList = new LinkedList<String>();
     296 folderList.add(%%1);
     297 while (folderList.size() > 0) {
     298 File file = new File((String)folderList.poll());
     299 File[] files = file.listFiles();
     300 List<File> fileList = new ArrayList<File>();
     301 for (int i = 0; i < files.length; i++) {
     302 if (files[i].isDirectory())
     303 folderList.add(files[i].getPath());
     304 else
     305 fileList.add(files[i]);
     306 }
     307 for (File f : fileList) {
     308 %%2=f.getAbsoluteFile();
     309 %%3
     310 }
     311 }
     312 
     313 13.复制文件夹
     314 /*
     315 import java.io.*;
     316 import java.util.*;
     317 */
     318 LinkedList<String> folderList = new LinkedList<String>();
     319 folderList.add(%%1);
     320 LinkedList<String> folderList2 = new LinkedList<String>();
     321 folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\")));
     322 while (folderList.size() > 0) {
     323 (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
     324 File folders = new File(folderList.peek());
     325 String[] file = folders.list();
     326 File temp = null;
     327 try {
     328 for (int i = 0; i < file.length; i++) {
     329 if (folderList.peek().endsWith(File.separator))
     330 temp = new File(folderList.peek() + File.separator
     331 + file[i]);
     332 else
     333 temp = new File(folderList.peek() + File.separator
     334 + file[i]);
     335 if (temp.isFile()) {
     336 FileInputStream input = new FileInputStream(temp);
     337 FileOutputStream output = new FileOutputStream(new File(
     338 folderList2.peek() ,temp.getName().toString()));
     339 byte[] b = new byte[10240];
     340 int len;
     341 while ((len = input.read(b)) != -1)
     342 output.write(b, 0, len);
     343 output.flush();
     344 output.close();
     345 input.close();
     346 }
     347 else if (temp.isDirectory()) {// 如果是子文件夹
     348 for (File f : temp.listFiles()) {
     349 if (f.isDirectory()) {
     350 folderList.add(f.getPath());
     351 folderList2.add(folderList2.peek()
     352 + File.separator + f.getName());
     353 }
     354 else if(f.isFile()) {
     355 FileInputStream input = new FileInputStream(f);
     356 FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
     357 byte[] b = new byte[10240];
     358 int len;
     359 while ((len = input.read(b)) != -1)
     360 output.write(b, 0, len);
     361 output.flush();
     362 output.close();
     363 input.close();
     364 }
     365 }
     366 }
     367 }
     368 } catch (IOException e) {
     369 System.err.println("复制整个文件夹内容操作出错");
     370 }
     371 folderList.removeFirst();
     372 folderList2.removeFirst();
     373 }
     374 
     375 14.复制一个目录下所有的文件夹到另一个文件夹下
     376 /*
     377 import java.io.*;
     378 import java.util.*;
     379 */
     380 File copyfolders=new File(%%1);
     381 File[] copyfoldersList=copyfolders.listFiles();
     382 for(int k=0;k<copyfoldersList.length;k++){
     383 if(copyfoldersList[k].isDirectory()){
     384 List<String>folderList=new ArrayList<String>();
     385 folderList.add(copyfoldersList[k].getPath());
     386 List<String>folderList2=new ArrayList<String>();
     387 folderList2.add(%%2+"/"+copyfoldersList[k].getName());
     388 for(int j=0;j<folderList.size();j++){
     389 (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
     390 File folders=new File(folderList.get(j));
     391 String[] file=folders.list();
     392 File temp=null;
     393 try {
     394 for (int i = 0; i < file.length; i++) {
     395 if(folderList.get(j).endsWith(File.separator))
     396 temp=new File(folderList.get(j),file[i]);
     397 else
     398 temp=new File(folderList.get(j),file[i]);
     399 FileInputStream input = new FileInputStream(temp);
     400 if(temp.isFile()){
     401 FileOutputStream output = new FileOutputStream(new File(folderList2.get(j) ,temp.getName()).toString()));
     402 byte[] b = new byte[10240];
     403 while ( (int len = input.read(b)) != -1)
     404 output.write(b, 0, len);
     405 output.flush();
     406 output.close();
     407 input.close();
     408 }
     409 else if(temp.isDirectory()){//如果是子文件夹
     410 for (File f : temp.listFiles()) {
     411 if (f.isDirectory()) {
     412 folderList.add(f.getPath());
     413 folderList2.add(folderList2.peek()
     414 + File.separator + f.getName());
     415 }
     416 else if(f.isFile()) {
     417 FileInputStream input = new FileInputStream(f);
     418 FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
     419 byte[] b = new byte[10240];
     420 int len;
     421 while ((len = input.read(b)) != -1) {
     422 output.write(b, 0, len);
     423 }
     424 output.flush();
     425 output.close();
     426 input.close();
     427 }
     428 }
     429 }
     430 }
     431 }
     432 }
     433 catch (IOException e) {
     434 System.err.println("复制整个文件夹内容操作出错");
     435 }
     436 }
     437 }
     438 }
     439 
     440 15.移动文件夹
     441 /*
     442 import java.io.*;
     443 import java.util.*;
     444 */
     445 LinkedList<String> folderList = new LinkedList<String>();
     446 folderList.add(%%1);
     447 LinkedList<String> folderList2 = new LinkedList<String>();
     448 folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\")));
     449 while (folderList.size() > 0) {
     450 (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
     451 File folders = new File(folderList.peek());
     452 String[] file = folders.list();
     453 File temp = null;
     454 try {
     455 for (int i = 0; i < file.length; i++) {
     456 if (folderList.peek().endsWith(File.separator)) {
     457 temp = new File(folderList.peek() , file[i]);
     458 } else {
     459 temp = new File(folderList.peek() ,file[i]);
     460 }
     461 if (temp.isFile()) {
     462 FileInputStream input = new FileInputStream(temp);
     463 FileOutputStream output = new FileOutputStream(
     464 folderList2.peek() + File.separator
     465 + (temp.getName()).toString());
     466 byte[] b = new byte[10240];
     467 while ((int len = input.read(b)) != -1)
     468 output.write(b, 0, len);
     469 output.flush();
     470 output.close();
     471 input.close();
     472 if (!temp.delete())
     473 //删除单个文件操作出错
     474 }
     475 else if (temp.isDirectory()) {// 如果是子文件夹
     476 for (File f : temp.listFiles()) {
     477 if (f.isDirectory()) {
     478 folderList.add(f.getPath());
     479 folderList2.add(folderList2.peek()
     480 + File.separator + f.getName());
     481 }
     482 else if (f.isFile()) {
     483 FileInputStream input = new FileInputStream(f);
     484 FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
     485 byte[] b = new byte[10240];
     486 while ((int len = input.read(b)) != -1)
     487 output.write(b, 0, len);
     488 output.flush();
     489 output.close();
     490 input.close();
     491 if (!temp.delete())
     492 //删除单个文件操作出错
     493 }
     494 }
     495 }
     496 }
     497 } catch (IOException e) {
     498 //复制整个文件夹内容操作出错
     499 e.printStackTrace();
     500 }
     501 folderList.removeFirst();
     502 folderList2.removeFirst();
     503 
     504 }
     505 File f = new File(%%1);
     506 if (!f.delete()) {
     507 for (File file : f.listFiles()) {
     508 if (file.list().length == 0)
     509 file.delete();
     510 }
     511 }
     512 
     513 16.移动一个目录下所有的文件夹到另一个目录下
     514 /*
     515 import java.io.*;
     516 import java.util.*;
     517 */
     518 File movefolders=new File(%%1);
     519 File[] movefoldersList=movefolders.listFiles();
     520 for(int k=0;k<movefoldersList.length;k++){
     521 if(movefoldersList[k].isDirectory()){
     522 List<String>folderList=new ArrayList<String>();
     523 folderList.add(movefoldersList[k].getPath());
     524 List<String>folderList2=new ArrayList<String>();
     525 folderList2.add(%%2+File.separator+movefoldersList[k].getName());
     526 for(int j=0;j<folderList.size();j++){
     527 (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
     528 File folders=new File(folderList.get(j));
     529 String[] file=folders.list();
     530 File temp=null;
     531 try {
     532 for (int i = 0; i < file.length; i++) {
     533 if(folderList.get(j).endsWith(File.separator))
     534 temp=new File(folderList.get(j),file[i]);
     535 else
     536 temp=new File(folderList.get(j),file[i]);
     537 FileInputStream input = new FileInputStream(temp);
     538 if(temp.isFile()){
     539 FileInputStream input = new FileInputStream(temp);
     540 FileOutputStream output = new FileOutputStream(new File(folderList2.get(j),temp.getName().toString()));
     541 byte[] b = new byte[10240];
     542 while ( (int len = input.read(b)) != -1)
     543 output.write(b, 0, len);
     544 output.flush();
     545 output.close();
     546 input.close();
     547 temp.delete();
     548 }
     549 else if(temp.isDirectory()){//如果是子文件夹
     550 for (File f : temp.listFiles()) {
     551 if (f.isDirectory()) {
     552 folderList.add(f.getPath());
     553 folderList2.add(folderList2.peek()
     554 + File.separator + f.getName());
     555 }
     556 else if (f.isFile()) {
     557 FileInputStream input = new FileInputStream(f);
     558 FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
     559 byte[] b = new byte[10240];
     560 while ((int len = input.read(b)) != -1)
     561 output.write(b, 0, len);
     562 output.flush();
     563 output.close();
     564 input.close();
     565 if (!temp.delete())
     566 //删除单个文件操作出错
     567 }
     568 }
     569 }
     570 }
     571 catch (IOException e) {
     572 //复制整个文件夹内容操作出错
     573 e.printStackTrace();
     574 }
     575 }
     576 movefoldersList[k].delete();
     577 }
     578 }
     579 
     580 17.以一个文件夹的框架在另一个目录创建文件夹和空文件
     581 /*
     582 import java.io.*;
     583 import java.util.*;
     584 */
     585 boolean b=false;//不创建空文件
     586 List<String>folderList=new ArrayList<String>();
     587 folderList.add(%%1);
     588 List<String>folderList2=new ArrayList<String>();
     589 folderList2.add(%%2);
     590 for(int j=0;j<folderList.size();j++){
     591 (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
     592 File folders=new File(folderList.get(j));
     593 String[] file=folders.list();
     594 File temp=null;
     595 try {
     596 for (int i = 0; i < file.length; i++) {
     597 if(folderList.get(j).endsWith(File.separator))
     598 temp=new File(folderList.get(j),file[i]);
     599 else
     600 temp=new File(folderList.get(j),file[i]);
     601 if(temp.isFile() && b)
     602 temp.createNewFile();
     603 else if(temp.isDirectory()){//如果是子文件夹
     604 folderList.add(folderList.get(j)+File.separator+file[i]);
     605 folderList2.add(folderList2.get(j)+File.separator+file[i]);
     606 }
     607 }
     608 }
     609 catch (IOException e) {
     610 //复制整个文件夹内容操作出错
     611 e.printStackTrace();
     612 }
     613 }
     614 
     615 18.复制文件
     616 //import java.io.*;
     617 File oldfile = new File(%%1);
     618 try {
     619 if (oldfile.exists()) { //文件存在时
     620 FileInputStream inStream = new FileInputStream(oldfile); //读入原文件
     621 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
     622 byte[] buffer = new byte[10240];
     623 int byteread;
     624 while ( (byteread = inStream.read(buffer)) != -1)
     625 fs.write(buffer, 0, byteread);
     626 inStream.close();
     627 }
     628 }
     629 catch (IOException e) {
     630 //复制单个文件操作出错
     631 e.printStackTrace();
     632 }
     633 
     634 19.复制一个目录下所有的文件到另一个目录
     635 //import java.io.*;
     636 File copyfiles=new File(%%1);
     637 File targetfiles = new File(%%2);
     638 if (!targetfiles.exists())
     639 targetfiles.mkdirs();
     640 File[] files=copyfiles.listFiles();
     641 for(int i=0;i<files.length;i++){
     642 if(files[i].isFile()){
     643 try {
     644 InputStream inStream = new FileInputStream(files[i]); //读入原文件
     645 FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()));
     646 byte[] buffer = new byte[10240];
     647 int byteread;
     648 while ( (byteread = inStream.read(buffer)) != -1)
     649 fs.write(buffer, 0, byteread);
     650 inStream.close();
     651 } catch (IOException e) {
     652 //复制单个文件操作出错
     653 e.printStackTrace();
     654 }
     655 }
     656 }
     657 
     658 20.提取扩展名
     659 String %%2=%%1.substring(%%1.lastIndexOf('.'));
     660 
     661 21.提取文件名
     662 String %%2=%%1.substring(%%1.lastIndexOf("\")+1);
     663 
     664 22.提取文件路径
     665 String %%2=%%1.substring(0,%%1.lastIndexOf("\"));
     666 
     667 23.替换扩展名
     668 //import java.io.*;
     669 File replaceExt=new File(%%1);
     670 replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);
     671 
     672 24.追加路径
     673 final String path=%%1.endsWith("\")?%%1:%%1+"\";
     674 %%3=path+%%2;
     675 
     676 25.移动文件
     677 //import java.io.*;
     678 File oldfile = new File(%%1);
     679 try {
     680 if (oldfile.exists()) { //文件存在时
     681 InputStream inStream = new FileInputStream(oldfile); //读入原文件
     682 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
     683 byte[] buffer = new byte[10240];
     684 int byteread;
     685 while ( (byteread = inStream.read(buffer)) != -1)
     686 fs.write(buffer, 0, byteread);
     687 inStream.close();
     688 oldfile.delete();
     689 }
     690 }
     691 catch (IOException e) {
     692 //复制单个文件操作出错
     693 e.printStackTrace();
     694 }
     695 
     696 26.移动一个目录下所有文件到另一个目录
     697 //import java.io.*;
     698 File movefile=new File(%%1);
     699 File[] movefiles=movefile.listFiles();
     700 for(int i=0;i<movefiles.length;i++){
     701 if(movefiles[i].isFile()){
     702 File oldfile = new File(movefiles[i]);
     703 try {
     704 if (oldfile.exists()) { //文件存在时
     705 InputStream inStream = new FileInputStream(oldfile); //读入原文件
     706 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
     707 byte[] buffer = new byte[10240];
     708 int byteread;
     709 while ( (byteread = inStream.read(buffer)) != -1)
     710 fs.write(buffer, 0, byteread);
     711 inStream.close();
     712 oldfile.delete();
     713 }
     714 }
     715 catch (IOException e) {
     716 //复制单个文件操作出错
     717 e.printStackTrace();
     718 }
     719 }
     720 }
     721 
     722 27.指定目录下搜索文件
     723 //import java.io.*;
     724 private static final String filter=%%1; //"*.*"
     725 private static void doSearch(String path){
     726 File file = new File(path);
     727 if(file.exists()) {
     728 if(file.isDirectory()) {
     729 File[] fileArray = file.listFiles();
     730 for(File f:fileArray) {
     731 if(f.isDirectory()) {
     732 doSearch(f.getPath());
     733 } else {
     734 if(f.getName().indexOf(filter) >= 0) {
     735 //f.getPath()
     736 }
     737 }
     738 //f.getPath()
     739 }
     740 //"The numbers of files had been found:" + countFiles
     741 } else {
     742 //"Couldn't open the path!"
     743 }
     744 } else {
     745 System.err.println("目录不存在");
     746 }
     747 }
     748 doSearch(%%1);
     749 
     750 28.打开对话框
     751 /*
     752 import java.io.*;
     753 import javax.swing.*;
     754 */
     755 JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc
     756 Jfc.showDialog(null, %%1);
     757 if (Jfc.getSelectedFile() != null) {
     758 File %%2 = Jfc.getSelectedFile();
     759 }
     760 
     761 29.文件分割
     762 //import java.io.*;
     763 try {
     764 File f=new File(%%1);
     765 FileInputStream fileInputStream = new FileInputStream(f);
     766 byte[] buffer = new byte[fileInputStream.available()];
     767 FileInputStream.read(buffer);
     768 fileInputStream.close();
     769 String strFileName = f.getName();
     770 FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\"+ strFileName + "1"));
     771 fileOutputStream.write(buffer,0,buffer.length/2);
     772 fileOutputStream.close();
     773 fileOutputStream = new FileOutputStream(new File(%%2+"\"+ strFileName + "2"));
     774 fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2);
     775 fileOutputStream.close();
     776 } catch (ArrayIndexOutOfBoundsException e) {
     777 e.printStackTrace();
     778 }
     779 catch(IOException e){
     780 e.printStackTrace();
     781 }
     782 
     783 30.文件合并
     784 //import java.io.*;
     785 String strFileName = %%1.substring(%%1.LastIndexOf("\") + 1);
     786 try {
     787 FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1"));
     788 FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2"));
     789 byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()];
     790 FileInputStream.read(buffer, 0, fileInputStream1.available());
     791 FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available());
     792 fileInputStream.close();
     793 fileInputStream2.close();
     794 FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\"+ strFileName));
     795 fileOutputStream.write(buffer,0,buffer.length);
     796 fileOutputStream.close();
     797 }
     798 catch(IOException e){
     799 e.printStackTrace();
     800 }
     801 
     802 31.文件简单加密
     803 /*
     804 import java.io.*;
     805 import javax.swing.*;
     806 private static final String CharSet = "0123456789ABCDEF";
     807 */
     808 JFileChooser jfc = new JFileChooser();
     809 JFileChooser jfc2 = new JFileChooser();
     810 jfc.showDialog(null, "请选择要加密编码的文件");
     811 jfc2.showDialog(null, "请选择要输出的文件名");
     812 if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
     813 File oldfile = jfc.getSelectedFile();
     814 FileInputStream inStream = null;
     815 FileWriter fw = null;
     816 try {
     817 if (oldfile.exists()) {
     818 inStream = new FileInputStream(oldfile);
     819 fw = new FileWriter(jfc2.getSelectedFile());
     820 byte[] sRead = new byte[10240];
     821 int byteread;
     822 while ((byteread = inStream.read(sRead)) != -1) {
     823 StringBuilder smi = new StringBuilder(byteread * 2);
     824 int ka = 3, kb = 5, kc = 2, kd = 7, js = 0;
     825 if (byteread % 2 != 0)
     826 js = 1;
     827 for (int i = 0; i < byteread - 1; i += 2) {
     828 char c1 = (char) sRead[i];
     829 char c2 = (char) sRead[i + 1];
     830 int tmp = ka * c1 + kc * c2;
     831 while (tmp < 0)
     832 tmp += 1024;
     833 byte s1 = (byte) (tmp % 1024);
     834 int js1 = (int) s1 >> 4 & 0xf;
     835 smi.append(CharSet.substring(js1, js1 + 1));
     836 int ks1 = s1 & 0xf;
     837 smi.append(CharSet.substring(ks1, ks1 + 1));
     838 tmp = kb * c1 + kd * c2;
     839 while (tmp < 0)
     840 tmp += 1024;
     841 byte s2 = (byte) (tmp % 1024);
     842 int js2 = (int) s2 >> 4 & 0xf;
     843 smi.append(CharSet.substring(js2, js2 + 1));
     844 int ks2 = s2 & 0xf;
     845 smi.append(CharSet.substring(ks2, ks2 + 1));
     846 }
     847 if (js == 1) {
     848 byte s3 = (byte) ((sRead[byteread - 1] - 4) % 1024);
     849 int js3 = (int) s3 >> 4 & 0xf;
     850 smi.append(CharSet.substring(js3, js3 + 1));
     851 int ks3 = (int) s3 & 0xf;
     852 smi.append(CharSet.substring(ks3, ks3 + 1));
     853 }
     854 fw.write(smi.toString());
     855 }
     856 fw.flush();
     857 }
     858 } catch (IOException e) {
     859 e.printStackTrace();
     860 } finally {
     861 try {
     862 fw.close();
     863 inStream.close();
     864 } catch (IOException e) {
     865 e.printStackTrace();
     866 }
     867 }
     868 }
     869 
     870 32.文件简单解密
     871 /*
     872 import java.io.*;
     873 import javax.swing.*;
     874 private static final String CharSet = "0123456789ABCDEF";
     875 */
     876 private static int niyuan(int m, int n) {
     877 int a, b, c, d, t, yu = 0, shang, mod;
     878 a = m;
     879 b = n;
     880 mod = a;
     881 c = 0;
     882 d = 1;
     883 while (b < 0)
     884 b += a;
     885 if (a % b == 0 || b % 2 == 0)
     886 return 0;
     887 while (b != 1) {
     888 t = a % b;
     889 shang = a / b;
     890 a = b;
     891 b = t;
     892 yu = c - shang * d;
     893 c = d;
     894 d = yu;
     895 }
     896 if (yu < 0)
     897 yu += mod;
     898 return yu;
     899 }
     900 JFileChooser jfc = new JFileChooser();
     901 JFileChooser jfc2 = new JFileChooser();
     902 jfc.showDialog(null, "请选择要解码解密的文件");
     903 jfc2.showDialog(null, "请选择要输出的文件名");
     904 if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
     905 FileOutputStream fw = null;
     906 try {
     907 FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
     908 fw = new FileOutputStream(jfc2
     909 .getSelectedFile());
     910 byte[] buffer = new byte[20480];
     911 int ka = 3, kb = 5, kc = 2, kd = 7, js = 0, tmp;
     912 int aany, ddny;
     913 int r00 = ka * kc * kd;
     914 int r01 = -ka * kb * kc;
     915 int r10 = -kb * kc * kc;
     916 int r11 = ka * kb * kc;
     917 int x00 = ka * ka * kc * kd - ka * kb * kc * kc;
     918 int x11 = ka * kb * kc * kd - kb * kb * kc * kc;
     919 while (x00 % 2 == 0) {
     920 x00 /= 2;
     921 r00 /= 2;
     922 r01 /= 2;
     923 }
     924 while (x11 % 2 == 0) {
     925 x11 /= 2;
     926 r10 /= 2;
     927 r11 /= 2;
     928 }
     929 aany = x00;
     930 ddny = x11;
     931 if (niyuan(1024, aany) != 0 && niyuan(1024, ddny) != 0) {
     932 int kn00 = r00 * niyuan(1024, x00);
     933 int kn01 = r01 * niyuan(1024, x00);
     934 int kn10 = r10 * niyuan(1024, x11);
     935 int kn11 = r11 * niyuan(1024, x11);
     936 ka = kn00;
     937 kb = kn01;
     938 kc = kn10;
     939 kd = kn11;
     940 } else {
     941 JOptionPane.showMessageDialog(null, "无逆矩阵!");
     942 System.exit(0);
     943 }
     944 while (ka < 0)
     945 ka += 1024;
     946 while (kb < 0)
     947 kb += 1024;
     948 while (kc < 0)
     949 kc += 1024;
     950 while (kd < 0)
     951 kd += 1024;
     952 ka %= 1024;
     953 kb %= 1024;
     954 kc %= 1024;
     955 kd %= 1024;
     956 try {
     957 int byteread;
     958 while ((byteread = fis.read(buffer)) != -1) {
     959 int nLen = byteread / 2;
     960 byte[] sming = new byte[nLen];
     961 String chs=new String(buffer,"US-ASCII");
     962 for (int i = 0; i < nLen; i++) {
     963 byte bTmp;
     964 if (byteread < 2)
     965 bTmp = -1;
     966 bTmp = (byte) (CharSet.indexOf(chs.substring(i * 2,i * 2+1)) * 16 + CharSet
     967 .indexOf(chs.substring(i * 2 + 1,i * 2 + 2)));
     968 sming[i] = bTmp;
     969 }
     970 if (nLen % 2 != 0)
     971 js = 1;
     972 for (int i = 0; i < nLen - 1; i += 2) {
     973 char c1 = (char) sming[i];
     974 char c2 = (char) sming[i + 1];
     975 tmp = ka * c1 + kc * c2;
     976 while (tmp < 0)
     977 tmp += 1024;
     978 char s1 = (char) (tmp % 1024);
     979 fw.write(s1);
     980 tmp = kb * c1 + kd * c2;
     981 while (tmp < 0)
     982 tmp += 1024;
     983 char s2 = (char) (tmp % 1024);
     984 fw.write(s2);
     985 }
     986 if (js == 1) {
     987 char c3 = (char) ((sming[nLen - 1] - 4) % 1024);
     988 fw.write(c3);
     989 }
     990 }
     991 fw.flush();
     992 } catch (IOException e) {
     993 e.printStackTrace();
     994 } finally {
     995 try {
     996 fis.close();
     997 fw.close();
     998 } catch (IOException e) {
     999 e.printStackTrace();
    1000 }
    1001 }
    1002 } catch (FileNotFoundException e1) {
    1003 // TODO Auto-generated catch block
    1004 e1.printStackTrace();
    1005 }
    1006 }
    1007 
    1008 33.读取ini文件属性
    1009 /*
    1010 import java.io.*;
    1011 import java.util.*;
    1012 import java.util.regex.*;
    1013 private static HashMap configMap=null;
    1014 private static FileReader fileReader = null;
    1015 */
    1016 private static boolean readIni() {
    1017 if (configMap == null) {
    1018 configMap = new HashMap<String, ArrayList>();
    1019 String strLine = null;
    1020 String currentNode = null;
    1021 String previousNode = null;
    1022 ArrayList<Properties> vec = new ArrayList<Properties>();
    1023 int row = 0;
    1024 BufferedReader bufferedReader = new BufferedReader(fileReader);
    1025 try {
    1026 while ((strLine = bufferedReader.readLine()) != null) {
    1027 String oneLine = strLine.trim();
    1028 if (oneLine.length() >= 1) {
    1029 Pattern p = Pattern.compile("\[\s*.*\s*\]");
    1030 int nodelen = oneLine.split("[;]").length;
    1031 String[] strArray1 = new String[4];
    1032 if (nodelen == 1) {
    1033 oneLine = oneLine.split("[;]")[0].trim();
    1034 } else if (nodelen == 2) {
    1035 strArray1[3] = oneLine.split("[;]")[1].trim();
    1036 oneLine = oneLine.split("[;]")[0].trim();
    1037 }
    1038 Matcher m = p.matcher(oneLine);
    1039 if (m.matches()) {
    1040 strArray1[0] = "@Node";
    1041 strArray1[1] = oneLine;
    1042 strArray1[2] = "";
    1043 } else {
    1044 int keylen = oneLine.split("=").length;
    1045 if (keylen == 1) {
    1046 strArray1[0] = "@Key";
    1047 strArray1[1] = oneLine.split("=")[0];
    1048 strArray1[2] = "";
    1049 } else if (keylen == 2) {
    1050 strArray1[0] = "@Key";
    1051 strArray1[1] = oneLine.split("=")[0];
    1052 strArray1[2] = oneLine.split("=")[1];
    1053 } else {
    1054 strArray1[0] = "@ElementError";
    1055 strArray1[1] = "";
    1056 strArray1[2] = "";
    1057 strArray1[3] = "";
    1058 }
    1059 }
    1060 if (strArray1[0].equals("@Node")) {
    1061 previousNode = currentNode;
    1062 currentNode = strArray1[1];
    1063 if (row > 0) {
    1064 configMap.put(previousNode, (ArrayList)vec.clone());
    1065 vec.clear();
    1066 row = 0;
    1067 }
    1068 } else if (strArray1[0].equals("@Key") && row == 0) {
    1069 Properties ht = new Properties();
    1070 ht.setProperty(strArray1[1], strArray1[2]);
    1071 vec.add(ht);
    1072 row++;
    1073 } else if (strArray1[0].equals("@Key") && row > 0) {
    1074 Properties ht2 = new Properties();
    1075 ht2.put(strArray1[1], strArray1[2]);
    1076 vec.add(ht2);
    1077 row++;
    1078 }
    1079 }
    1080 }
    1081 configMap.put(currentNode, (ArrayList)vec.clone());
    1082 } catch (FileNotFoundException e) {
    1083 configMap = null;
    1084 e.printStackTrace();
    1085 return false;
    1086 } catch (IOException e) {
    1087 configMap = null;
    1088 e.printStackTrace();
    1089 return false;
    1090 }
    1091 }
    1092 return true;
    1093 }
    1094 try {
    1095 fileReader = new FileReader(%%1); //"Setup.ini"
    1096 } catch (FileNotFoundException e1) {
    1097 e1.printStackTrace();
    1098 }
    1099 if (readIni()) {
    1100 ArrayList<Properties> li = null;
    1101 li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
    1102 for (Properties pro : li) {
    1103 if(pro.containsKey(%%3))
    1104 %%4=pro.getProperty(%%3);
    1105 }
    1106 }
    1107 try {
    1108 fileReader.close();
    1109 } catch (IOException e) {
    1110 e.printStackTrace();
    1111 }
    1112 
    1113 34.合并一个目录下所有的文件
    1114 //import java.io.*;
    1115 File combinefiles=new File(%%1);
    1116 File[] files=combinefiles.listFiles();
    1117 FileOutputStream fs;
    1118 try {
    1119 fs=new FileOutputStream(new File(%%2));
    1120 }
    1121 catch(IOException e){
    1122 e.printStackTrace();
    1123 }
    1124 for(int i=0;i<files.length;i++){
    1125 if(files[i].isFile()){
    1126 try {
    1127 FileInputStream inStream=new FileInputStream(files[i]);
    1128 byte[] buffer = new byte[10240];
    1129 int byteread;
    1130 while((byteread=inStream.read(buffer))!=-1)
    1131 fs.write(buffer,0,byteread);
    1132 inStream.close();
    1133 }
    1134 catch(Exception e){
    1135 //复制文件出错
    1136 e.printStackTrace();
    1137 }
    1138 }
    1139 }
    1140 try {
    1141 fs.close();
    1142 }
    1143 catch(IOException e){
    1144 e.printStackTrace();
    1145 }
    1146 
    1147 35.写入ini文件属性
    1148 /*
    1149 import java.io.*;
    1150 import java.util.*;
    1151 import java.util.regex.*;
    1152 private static HashMap configMap=null;
    1153 */
    1154 if (readIni()) {
    1155 ArrayList<Properties> li = null;
    1156 try {
    1157 FileWriter fw = new FileWriter(%%1);
    1158 li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
    1159 fw.write("%%2
    ");
    1160 for (Properties pro : li) {
    1161 if (pro.containsKey(%%3)) //"ip"
    1162 fw.write("%%3=" + %%6 + "
    ");
    1163 }
    1164 fw.flush();
    1165 fw.close();
    1166 } catch (IOException e) {
    1167 e.printStackTrace();
    1168 }
    1169 }
    1170 
    1171 36.获得当前路径
    1172 String %%1=getClass().getResource("/").getPath();
    1173 //String %%1=System.getProperty("user.dir");
    1174 
    1175 37.读取XML数据库
    1176 /*
    1177 import java.io.*;
    1178 import javax.xml.parsers.*;
    1179 import org.w3c.dom.*;
    1180 private static Document document;
    1181 private static Element node;
    1182 */
    1183 File xml_file = new File(%%1);
    1184 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    1185 try {
    1186 DocumentBuilder builder = factory.newDocumentBuilder();
    1187 document = builder.parse(xml_file);
    1188 } catch (Exception e) {
    1189 e.printStackTrace();
    1190 }
    1191 String subNodeTag = %%2;
    1192 Element rootNode = document.getDocumentElement();
    1193 //%%2="Product" //%%4="id" //%%6="port"
    1194 //%%3="Name" //%%5="001"
    1195 NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
    1196 int len = nlist.getLength();
    1197 for (int i = 0; i < len; i++) {
    1198 node = nlist.item(i);
    1199 String getNodeAttrValue = null;
    1200 NamedNodeMap attrList = node.getAttributes();
    1201 for (int j = 0; j < attrList.getLength(); j++) {
    1202 if (attrList.item(j).getNodeName().equals(%%4)) {
    1203 getNodeAttrValue = attrList.item(j).getNodeValue();
    1204 break;
    1205 }
    1206 }
    1207 if (getNodeAttrValue.equals(%%5)) {
    1208 nlist = node.getChildNodes();
    1209 String %%9=((Element) node).getElementsByTagName(%%3).item(0)
    1210 .getFirstChild().getNodeValue();
    1211 break;
    1212 }
    1213 }
    1214 
    1215 38.写入XML数据库
    1216 /*
    1217 import java.io.*;
    1218 import javax.xml.parsers.*;
    1219 import org.w3c.dom.*;
    1220 import javax.xml.transform.*;
    1221 import javax.xml.transform.dom.*;
    1222 import javax.xml.transform.stream.*;
    1223 private Document document;
    1224 private Element node;
    1225 */
    1226 File xml_file = new File(%%1);
    1227 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    1228 try {
    1229 DocumentBuilder builder = factory.newDocumentBuilder();
    1230 document = builder.parse(xml_file);
    1231 } catch (Exception e) {
    1232 e.printStackTrace();
    1233 }
    1234 String subNodeTag = %%2;
    1235 Element rootNode = document.getDocumentElement();
    1236 // %%2="Product" //%%4="pid" //%%6="author"
    1237 // %%3="Name" //%%5="price"
    1238 NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
    1239 String ss = null;
    1240 int len = nlist.getLength();
    1241 for (int i = 0; i < len; i++) {
    1242 node = (Element) nlist.item(i);
    1243 //node.setAttribute(%%4, "0"+String.valueOf(i)); //ID格式化
    1244 String getNodeAttrValue = null;
    1245 NamedNodeMap attrList = node.getAttributes();
    1246 for (int j = 0; j < attrList.getLength(); j++) {
    1247 if (attrList.item(j).getNodeName().equals(%%4)) {
    1248 getNodeAttrValue = attrList.item(j).getNodeValue();
    1249 break;
    1250 }
    1251 }
    1252 if (getNodeAttrValue.equals("001")) {
    1253 nlist = node.getChildNodes();
    1254 ss = ((Element) node).getElementsByTagName(%%3).item(0)
    1255 .getFirstChild().getNodeValue();
    1256 ss = ((Element) node).getElementsByTagName(%%6).item(0)
    1257 .getFirstChild().getNodeValue();
    1258 ss = ((Element) node).getElementsByTagName(%%5).item(0)
    1259 .getFirstChild().getNodeValue();
    1260 ((Element) node).getElementsByTagName(%%3).item(0)
    1261 .getFirstChild().setTextContent(%%7);
    1262 ((Element) node).getElementsByTagName(%%6).item(0)
    1263 .getFirstChild().setTextContent(%%8);
    1264 ((Element) node).getElementsByTagName(%%5).item(0)
    1265 .getFirstChild().setTextContent(%%9);
    1266 break;
    1267 }
    1268 }
    1269 if (ss == null) {
    1270 node = document.createElement(%%2);
    1271 node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1));
    1272 node.appendChild(document.createTextNode("
    "));
    1273 Element server = document.createElement(%%3);
    1274 server.appendChild(document.createTextNode(%%7));
    1275 node.appendChild(server);
    1276 Element ipNode = document.createElement(%%6);
    1277 ipNode.appendChild(document.createTextNode(%%8));
    1278 node.appendChild(ipNode);
    1279 node.appendChild(document.createTextNode("
    "));
    1280 Element port = document.createElement(%%5);
    1281 port.appendChild(document.createTextNode(%%9));
    1282 node.appendChild(port);
    1283 node.appendChild(document.createTextNode("
    "));
    1284 rootNode.appendChild(node);
    1285 }
    1286 TransformerFactory tFactory = TransformerFactory.newInstance();
    1287 Transformer transformer = null;
    1288 try {
    1289 transformer = tFactory.newTransformer();
    1290 DOMSource source = new DOMSource(document);
    1291 StreamResult result = new StreamResult(xml_file);
    1292 transformer.transform(source, result);
    1293 } catch (IOException e) {
    1294 e.printStackTrace();
    1295 }
    1296 
    1297 39.ZIP压缩文件
    1298 /*
    1299 import java.io.*;
    1300 import java.util.zip.*;
    1301 */
    1302 //创建文件输入流对象
    1303 FileInputStream fis=new FileInputStream(%%1);
    1304 //创建文件输出流对象
    1305 FileOutputStream fos=new FileOutputStream(%%2);
    1306 //创建ZIP数据输出流对象
    1307 ZipOutputStream zipOut=new ZipOutputStream(fos);
    1308 //创建指向压缩原始文件的入口
    1309 ZipEntry entry=new ZipEntry(args[0]);
    1310 try {
    1311 zipOut.putNextEntry(entry);
    1312 //向压缩文件中输出数据
    1313 int nNumber;
    1314 byte[] buffer=new byte[1024];
    1315 while((nNumber=fis.read(buffer))!=-1)
    1316 zipOut.write(buffer,0,nNumber);
    1317 //关闭创建的流对象
    1318 zipOut.close();
    1319 fos.close();
    1320 fis.close();
    1321 }
    1322 catch(IOException e)
    1323 {
    1324 e.printStackTrace();
    1325 }
    1326 
    1327 40.ZIP解压缩
    1328 /*
    1329 import java.io.*;
    1330 import java.util.zip.*;
    1331 */
    1332 //创建文件输入流对象实例
    1333 FileInputStream fis=new FileInputStream(%%1);
    1334 //创建ZIP压缩格式输入流对象实例
    1335 ZipInputStream zipin=new ZipInputStream(fis);
    1336 //创建文件输出流对象实例
    1337 FileOutputStream fos=new FileOutputStream(%%2);
    1338 //获取Entry对象实例
    1339 ZipEntry entry=zipin.getNextEntry();
    1340 byte[] buffer=new byte[1024];
    1341 int nNumber;
    1342 try{
    1343 while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
    1344 fos.write(buffer,0,nNumber);
    1345 //关闭文件流对象
    1346 zipin.close();
    1347 fos.close();
    1348 fis.close();
    1349 }
    1350 catch(IOException e) {
    1351 e.printStackTrace();
    1352 }
    1353 
    1354 41.获得应用程序完整路径
    1355 String %%1=System.getProperty("user.dir");
    1356 
    1357 42.递归删除目录中的文件
    1358 /*
    1359 import java.io.*;
    1360 import java.util.*;
    1361 */
    1362 ArrayList<String> folderList = new ArrayList<String>();
    1363 folderList.add(%%1);
    1364 for (int j = 0; j < folderList.size(); j++) {
    1365 File file = new File(folderList.get(j));
    1366 File[] files = file.listFiles();
    1367 ArrayList<File> fileList = new ArrayList<File>();
    1368 for (int i = 0; i < files.length; i++) {
    1369 if (files[i].isDirectory()) {
    1370 folderList.add(files[i].getPath());
    1371 } else {
    1372 fileList.add(files[i]);
    1373 }
    1374 }
    1375 for (File f : fileList) {
    1376 f.delete();
    1377 }
    1378 }
    1379 
    1380 43.ZIP压缩文件夹
    1381 /*
    1382 import java.io.*;
    1383 import java.util.*;
    1384 import java.util.zip.*;
    1385 */
    1386 public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {
    1387 ArrayList fileNames = new ArrayList();
    1388 ArrayList files = new ArrayList();
    1389 FileOutputStream fileOut = null;
    1390 ZipOutputStream outputStream = null;
    1391 FileInputStream fileIn = null;
    1392 StringBuffer sb = new StringBuffer(outputZipNameAndPath);
    1393 // FileInputStream fileIn =null;
    1394 try {
    1395 if (outputZipNameAndPath.indexOf(".zip") != -1) {
    1396 outputZipNameAndPath = outputZipNameAndPath;
    1397 } else {
    1398 sb.append(".zip");
    1399 outputZipNameAndPath = sb.toString();
    1400 }
    1401 fileOut = new FileOutputStream(outputZipNameAndPath);
    1402 outputStream = new ZipOutputStream(fileOut);
    1403 int outputZipFileNameListSize = 0;
    1404 if (outputZipFileNameList != null) {
    1405 outputZipFileNameListSize = outputZipFileNameList.size();
    1406 }
    1407 for (int i = 0; i < outputZipFileNameListSize; i++) {
    1408 File rootFile = new File(outputZipFileNameList.get(i).toString());
    1409 listFile(rootFile, fileNames, files, "");
    1410 }
    1411 for (int loop = 0; loop < files.size(); loop++) {
    1412 fileIn = new FileInputStream((File) files.get(loop));
    1413 outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
    1414 byte[] buffer = new byte[1024];
    1415 while (fileIn.read(buffer) != -1) {
    1416 outputStream.write(buffer);
    1417 }
    1418 outputStream.closeEntry();
    1419 fileIn.close();
    1420 }
    1421 return outputZipNameAndPath;
    1422 } catch (IOException ioe) {
    1423 return null;
    1424 } finally {
    1425 if (outputStream != null) {
    1426 try {
    1427 outputStream.close();
    1428 } catch (IOException e) {
    1429 }
    1430 }
    1431 if (fileIn != null) {
    1432 try {
    1433 fileIn.close();
    1434 } catch (IOException e) {
    1435 }
    1436 }
    1437 }
    1438 }
    1439 private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {
    1440 if (parentFile.isDirectory()) {
    1441 File[] files = parentFile.listFiles();
    1442 for (int loop = 0; loop < files.length; loop++) {
    1443 listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");
    1444 }
    1445 } else {
    1446 fileList.add(parentFile);
    1447 nameList.add(directoryName + parentFile.getName());
    1448 }
    1449 }
    1450 String savePath=%%1;
    1451 ArrayList<String> outputZipFileName=new ArrayList<String>();
    1452 outputZipFileName.add(%%2);
    1453 zipFileProcess(outputZipFileName,savePath);
    1454 
    1455 44.IDEA加密算法
    1456 private byte[] bytekey;
    1457 public byte[] getKey(String key){
    1458 int len1 =key.length();
    1459 if (len1>=16) {
    1460 key=key.substring(0, 16);
    1461 } else {
    1462 for (int i=0;i<16-len1;i++){
    1463 key=key.concat("0");
    1464 }
    1465 }
    1466 bytekey=key.getBytes();
    1467 return bytekey;
    1468 }
    1469 /**
    1470 * 加密String明文输入,String密文输出
    1471 * @param strMing
    1472 * @return
    1473 */
    1474 public String getEncString(String strMing) {
    1475 byte[] byteMi = null;
    1476 byte[] byteMing = null;
    1477 String strMi = "";
    1478 try {
    1479 return byte2hex(IdeaEncrypt(bytekey,strMing.getBytes(),true) );
    1480 }
    1481 catch(Exception e){
    1482 e.printStackTrace();
    1483 }
    1484 finally {
    1485 byteMing = null;
    1486 byteMi = null;
    1487 }
    1488 return strMi;
    1489 }
    1490 /**
    1491 * 解密 以String密文输入,String明文输出
    1492 * @param strMi
    1493 * @return
    1494 */
    1495 public String getDesString(String strMi) {
    1496 byte[] byteMing = null;
    1497 byte[] byteMi = null;
    1498 String strMing = "";
    1499 try {
    1500 String tmp= new String(IdeaEncrypt(bytekey,hex2byte(strMi.getBytes()),false ));
    1501 int len1=tmp.length();
    1502 return tmp.substring(0, len1-6);
    1503 }
    1504 catch(Exception e) {
    1505 e.printStackTrace();
    1506 }
    1507 finally {
    1508 byteMing = null;
    1509 byteMi = null;
    1510 }
    1511 return strMing;
    1512 }
    1513 private byte[] Encrypt(byte[] bytekey, byte[] inputBytes, boolean flag) {
    1514 byte[] encryptCode = new byte[8];
    1515 // 分解子密钥
    1516 int[] key = get_subkey(flag, bytekey);
    1517 // 进行加密操作
    1518 encrypt(key, inputBytes, encryptCode);
    1519 // 返回加密数据
    1520 return encryptCode;
    1521 }
    1522 
    1523 private int bytesToInt(byte[] inBytes, int startPos) {
    1524 return ((inBytes[startPos] << 8) & 0xff00) +
    1525 (inBytes[startPos + 1] & 0xff);
    1526 }
    1527 
    1528 private void intToBytes(int inputInt, byte[] outBytes, int startPos) {
    1529 outBytes[startPos] = (byte) (inputInt >>> 8);
    1530 outBytes[startPos + 1] = (byte) inputInt;
    1531 }
    1532 
    1533 private int x_multiply_y(int x, int y) {
    1534 if (x == 0) {
    1535 x = 0x10001 - y;
    1536 } else if (y == 0) {
    1537 x = 0x10001 - x;
    1538 } else {
    1539 int tmp = x * y;
    1540 y = tmp & 0xffff;
    1541 x = tmp >>> 16;
    1542 x = (y - x) + ((y < x) ? 1 : 0);
    1543 }
    1544 
    1545 return x & 0xffff;
    1546 }
    1547 
    1548 private void encrypt(int[] key, byte[] inbytes, byte[] outbytes) {
    1549 int k = 0;
    1550 int a = bytesToInt(inbytes, 0);
    1551 int b = bytesToInt(inbytes, 2);
    1552 int c = bytesToInt(inbytes, 4);
    1553 int d = bytesToInt(inbytes, 6);
    1554 
    1555 for (int i = 0; i < 8; i++) {
    1556 a = x_multiply_y(a, key[k++]);
    1557 b += key[k++];
    1558 b &= 0xffff;
    1559 c += key[k++];
    1560 c &= 0xffff;
    1561 d = x_multiply_y(d, key[k++]);
    1562 
    1563 int tmp1 = b;
    1564 int tmp2 = c;
    1565 c ^= a;
    1566 b ^= d;
    1567 c = x_multiply_y(c, key[k++]);
    1568 b += c;
    1569 b &= 0xffff;
    1570 b = x_multiply_y(b, key[k++]);
    1571 c += b;
    1572 c &= 0xffff;
    1573 a ^= b;
    1574 d ^= c;
    1575 b ^= tmp2;
    1576 c ^= tmp1;
    1577 }
    1578 
    1579 intToBytes(x_multiply_y(a, key[k++]), outbytes, 0);
    1580 intToBytes(c + key[k++], outbytes, 2);
    1581 intToBytes(b + key[k++], outbytes, 4);
    1582 intToBytes(x_multiply_y(d, key[k]), outbytes, 6);
    1583 }
    1584 
    1585 private int[] encrypt_subkey(byte[] byteKey) {
    1586 int[] key = new int[52];
    1587 
    1588 if (byteKey.length < 16) {
    1589 byte[] tmpkey = new byte[16];
    1590 System.arraycopy(byteKey, 0, tmpkey,
    1591 tmpkey.length - byteKey.length, byteKey.length);
    1592 byteKey = tmpkey;
    1593 }
    1594 
    1595 for (int i = 0; i < 8; i++) {
    1596 key[i] = bytesToInt(byteKey, i * 2);
    1597 }
    1598 
    1599 for (int j = 8; j < 52; j++) {
    1600 if ((j & 0x7) < 6) {
    1601 key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 6] >> 7)) &
    1602 0xffff;
    1603 } else if ((j & 0x7) == 6) {
    1604 key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 14] >> 7)) &
    1605 0xffff;
    1606 } else {
    1607 key[j] = (((key[j - 15] & 0x7f) << 9) | (key[j - 14] >> 7)) &
    1608 0xffff;
    1609 }
    1610 }
    1611 
    1612 return key;
    1613 }
    1614 
    1615 private int fun_a(int a) {
    1616 if (a < 2) {
    1617 return a;
    1618 }
    1619 
    1620 int b = 1;
    1621 int c = 0x10001 / a;
    1622 
    1623 for (int i = 0x10001 % a; i != 1;) {
    1624 int d = a / i;
    1625 a %= i;
    1626 b = (b + (c * d)) & 0xffff;
    1627 
    1628 if (a == 1) {
    1629 return b;
    1630 }
    1631 d = i / a;
    1632 i %= a;
    1633 c = (c + (b * d)) & 0xffff;
    1634 }
    1635 
    1636 return (1 - c) & 0xffff;
    1637 }
    1638 
    1639 private int fun_b(int b) {
    1640 return (0 - b) & 0xffff;
    1641 }
    1642 
    1643 private int[] uncrypt_subkey(int[] key) {
    1644 int dec = 52;
    1645 int asc = 0;
    1646 int[] unkey = new int[52];
    1647 int aa = fun_a(key[asc++]);
    1648 int bb = fun_b(key[asc++]);
    1649 int cc = fun_b(key[asc++]);
    1650 int dd = fun_a(key[asc++]);
    1651 unkey[--dec] = dd;
    1652 unkey[--dec] = cc;
    1653 unkey[--dec] = bb;
    1654 unkey[--dec] = aa;
    1655 
    1656 for (int k1 = 1; k1 < 8; k1++) {
    1657 aa = key[asc++];
    1658 bb = key[asc++];
    1659 unkey[--dec] = bb;
    1660 unkey[--dec] = aa;
    1661 aa = fun_a(key[asc++]);
    1662 bb = fun_b(key[asc++]);
    1663 cc = fun_b(key[asc++]);
    1664 dd = fun_a(key[asc++]);
    1665 unkey[--dec] = dd;
    1666 unkey[--dec] = bb;
    1667 unkey[--dec] = cc;
    1668 unkey[--dec] = aa;
    1669 }
    1670 
    1671 aa = key[asc++];
    1672 bb = key[asc++];
    1673 unkey[--dec] = bb;
    1674 unkey[--dec] = aa;
    1675 aa = fun_a(key[asc++]);
    1676 bb = fun_b(key[asc++]);
    1677 cc = fun_b(key[asc++]);
    1678 dd = fun_a(key[asc]);
    1679 unkey[--dec] = dd;
    1680 unkey[--dec] = cc;
    1681 unkey[--dec] = bb;
    1682 unkey[--dec] = aa;
    1683 
    1684 return unkey;
    1685 }
    1686 
    1687 private int[] get_subkey(boolean flag, byte[] bytekey) {
    1688 if (flag) {
    1689 return encrypt_subkey(bytekey);
    1690 } else {
    1691 return uncrypt_subkey(encrypt_subkey(bytekey));
    1692 }
    1693 }
    1694 
    1695 private byte[] ByteDataFormat(byte[] data, int unit) {
    1696 int len = data.length;
    1697 int padlen = unit - (len % unit);
    1698 int newlen = len + padlen;
    1699 byte[] newdata = new byte[newlen];
    1700 System.arraycopy(data, 0, newdata, 0, len);
    1701 
    1702 for (int i = len; i < newlen; i++)
    1703 newdata[i] = (byte) padlen;
    1704 
    1705 return newdata;
    1706 }
    1707 
    1708 public byte[] IdeaEncrypt(byte[] idea_key, byte[] idea_data, boolean flag) {
    1709 byte[] format_key = ByteDataFormat(idea_key, 16);
    1710 byte[] format_data = ByteDataFormat(idea_data, 8);
    1711 
    1712 int datalen = format_data.length;
    1713 int unitcount = datalen / 8;
    1714 byte[] result_data = new byte[datalen];
    1715 
    1716 for (int i = 0; i < unitcount; i++) {
    1717 byte[] tmpkey = new byte[16];
    1718 byte[] tmpdata = new byte[8];
    1719 System.arraycopy(format_key, 0, tmpkey, 0, 16);
    1720 System.arraycopy(format_data, i * 8, tmpdata, 0, 8);
    1721 
    1722 byte[] tmpresult = Encrypt(tmpkey, tmpdata, flag);
    1723 System.arraycopy(tmpresult, 0, result_data, i * 8, 8);
    1724 }
    1725 
    1726 return result_data;
    1727 }
    1728 
    1729 /**
    1730 * 二行制转字符串
    1731 * @param b
    1732 * @return
    1733 */
    1734 public static String byte2hex(byte[] b) { //一个字节的数,
    1735 // 转成16进制字符串
    1736 String hs = "";
    1737 String stmp = "";
    1738 for (int n = 0; n < b.length; n++) {
    1739 //整数转成十六进制表示
    1740 stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
    1741 if (stmp.length() == 1)
    1742 hs = hs + "0" + stmp;
    1743 else
    1744 hs = hs + stmp;
    1745 }
    1746 return hs.toUpperCase(); //转成大写
    1747 }
    1748 
    1749 public static byte[] hex2byte(byte[] b) {
    1750 if((b.length%2)!=0)
    1751 throw new IllegalArgumentException("长度不是偶数");
    1752 byte[] b2 = new byte[b.length/2];
    1753 for (int n = 0; n < b.length; n+=2) {
    1754 String item = new String(b,n,2);
    1755 // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
    1756 b2[n/2] = (byte)Integer.parseInt(item,16);
    1757 }
    1758 
    1759 return b2;
    1760 }
    1761 
    1762 public static void main(String[] args) {
    1763 
    1764 
    1765 IDEA idea = new IDEA();
    1766 
    1767 idea.getKey("aadd");//生成密匙
    1768 
    1769 String strEnc = idea.getEncString("1234567890");//加密字符串,返回String的密文
    1770 System.out.println(strEnc);
    1771 
    1772 String strDes = idea.getDesString(strEnc);//把String 类型的密文解密
    1773 System.out.println(strDes);
    1774 
    1775 
    1776 // String key = "0000000000000000";
    1777 // String data = "11111111冯";
    1778 // byte[] bytekey = key.getBytes();
    1779 // byte[] bytedata = data.getBytes();
    1780 //
    1781 // IDEA idea = new IDEA();
    1782 // byte[] encryptdata = idea.IdeaEncrypt(bytekey, bytedata, true);
    1783 // byte[] decryptdata = idea.IdeaEncrypt(bytekey, encryptdata, false);
    1784 //
    1785 // System.out.println("--------------------------------");
    1786 //
    1787 // for (int i = 0; i < bytedata.length; i++) {
    1788 // System.out.print(" " + bytedata[i] + " ");
    1789 // }
    1790 //
    1791 // System.out.println("");
    1792 //
    1793 // for (int i = 0; i < encryptdata.length; i++) {
    1794 // System.out.print(" " + encryptdata[i] + " ");
    1795 // }
    1796 //
    1797 // System.out.println("");
    1798 //
    1799 // for (int i = 0; i < decryptdata.length; i++) {
    1800 // System.out.print(" " + decryptdata[i] + " ");
    1801 // }
    1802 
    1803 }
    1804 
    1805 45.验证Schema
    1806 /*
    1807 import javax.xml.*;
    1808 import javax.xml.transform.stream.*;
    1809 import javax.xml.validation.*;
    1810 import org.xml.sax.*;
    1811 */
    1812 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    1813 StreamSource ss = new StreamSource(%%1); //"mySchema.xsd"
    1814 try {
    1815 Schema schema = factory.newSchema(ss);
    1816 } catch (SAXException e) {
    1817 e.printStackTrace();
    1818 }
    1819 
    1820 46.Grep
    1821 /*
    1822 import java.util.regex.*;
    1823 import java.io.*;
    1824 */
    1825 throws Exception
    1826 Pattern pattern = Pattern.compile(%%1); // 第一个参数为需要匹配的字符串
    1827 Matcher matcher = pattern.matcher("");
    1828 String file = %%2;
    1829 BufferedReader br = null;
    1830 String line;
    1831 try {
    1832 br = new BufferedReader (new FileReader (file)); // 打开文件
    1833 } catch (IOException e) {
    1834 // 没有打开文件,则产生异常
    1835 System.err.println ("Cannot read '" + file
    1836 + "': " + e.getMessage());
    1837 }
    1838 while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
    1839 matcher.reset (line); // 匹配字符串
    1840 if (matcher.find()) { // 如果有匹配的字符串,则输出
    1841 //line
    1842 }
    1843 }
    1844 br.close(); // 关闭文件
    1845 
    1846 47.直接创建多级目录
    1847 //import java.io.*;
    1848 File f=new File(%%1);
    1849 f.mkdirs();
    1850 
    1851 48.批量重命名
    1852 //import java.io.*;
    1853 File target = new File("%%1");
    1854 String[] files = target.list();
    1855 File f = null;
    1856 String filename = null;
    1857 for (String file : files) {
    1858 f = new File(target, file);
    1859 filename = f.getName();
    1860 if (filename.substring(filename.lastIndexOf('.')).equalsIgnoreCase(
    1861 "%%2")) {
    1862 f.renameTo(new File(target.getAbsolutePath(), filename.replace(
    1863 "%%2", "%%3")));
    1864 // 这里可以反复使用replace替换,当然也可以使用正则表达式来替换了 ".txt" ".bat"
    1865 }
    1866 }
    1867 
    1868 49.文本查找替换
    1869 //import java.nio.*;
    1870 String s1=%%1;
    1871 String s2=%%2;
    1872 String s3=%%3;
    1873 int pos=%%4;
    1874 /*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/
    1875 int i,j,k=0;
    1876 i = pos;
    1877 j = 0;
    1878 //将s1转化成StringBuffer型进行操作
    1879 repStr = new StringBuffer(s1);
    1880 while(i<repStr.length()&&j<s2.length())
    1881 {
    1882 if(repStr.charAt(i) == s2.charAt(j))
    1883 {
    1884 ++i; ++j;
    1885 if(j==s2.length())
    1886 {
    1887 /*j=s2.length()表示字符串匹配成功,匹配次数加1,此外对主串进行字符串替换*/
    1888 k = k+1;
    1889 repStr.replace(i-j,i,s3);
    1890 //将j进行重新赋值开始新的比较
    1891 j = 0;
    1892 }
    1893 }
    1894 else {i = i-j+1; j = 0;}
    1895 }
    1896 return k;
    1897 
    1898 50.文件关联
    1899 //import java.io.*;
    1900 try {
    1901 Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]"
    1902 } catch (IOException e) {
    1903 e.printStackTrace();
    1904 }
    1905 
    1906 51.批量转换编码从GB2312到Unicode
    1907 
    1908 
    1909 52.设置JDK环境变量
    1910 @echo off
    1911 IF EXIST %1injava.exe (
    1912 rem 如输入正确的 Java2SDK 安装目录,开始设置环境变量
    1913 @setx JAVA_HOME %1
    1914 @setx path %path%;%JAVA_HOME%in
    1915 @setx classpath %classpath%;.
    1916 @setx classpath %classpath%;%JAVA_HOME%lib	ools.jar
    1917 @setx classpath %classpath%;%JAVA_HOME%libdt.jar
    1918 @setx classpath %classpath%;%JAVA_HOME%jrelib
    t.jar
    1919 @echo on
    1920 @echo Java 2 SDK 环境参数设置完毕,正常退出。
    1921 ) ELSE (
    1922 IF "%1"=="" (
    1923 rem 如没有提供安装目录,提示之后退出
    1924 @echo on
    1925 @echo 没有提供 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
    1926 ) ELSE (
    1927 rem 如果提供非空的安装目录但没有binjava.exe,则指定的目录为错误的目录
    1928 @echo on
    1929 @echo 非法的 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
    1930 )
    1931 )
    1932 //http://sourceforge.net/projects/jregistrykey/
    1933 //import ca.beq.util.win32.registry.*;
    1934 //import java.util.*;
    1935 1.打开键
    1936 RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
    1937 2.添加键
    1938 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\BEQ Technologies");
    1939 r.create();
    1940 9.写入字符串值
    1941 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\BEQ Technologies");
    1942 RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data");
    1943 r.setValue(v);
    1944 6.获取DWORD值
    1945 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\BEQ Technologies");
    1946 if(r.hasValue("myValue")) {
    1947 RegistryValue v = r.getValue("myValue");
    1948 v.setType(ValueType.REG_DWORD);
    1949 } // if
    1950 
    1951 
    1952 53.批量转换编码从Unicode到GB2312
    1953 
    1954 54.删除空文件夹
    1955 //import java.io.*;
    1956 File f=new File(%%1);
    1957 if (isFolerNull(f)) {
    1958 for (File file :f.listFiles()) {
    1959 if (file.list().length == 0)
    1960 file.delete();
    1961 }
    1962 }
    1963 
    1964 55.GB2312文件转UTF-8格式
    1965 //import java.io.*;
    1966 public class CharsetConvertor {
    1967 public static void main(String[] args) {
    1968 String str = "This is a test for *中网!@#$。,?";
    1969 try {
    1970 File f = new File("D:/test.txt");
    1971 FileOutputStream fio = new FileOutputStream(f);
    1972 String s = gbToUtf8(str);
    1973 fio.write(s.getBytes("UTF-8"));
    1974 fio.close();
    1975 }
    1976 catch (Exception e) {
    1977 e.printStackTrace();
    1978 }
    1979 }
    1980 
    1981 public static String gbToUtf8(String str) throws UnsupportedEncodingException {
    1982 StringBuffer sb = new StringBuffer();
    1983 for (int i = 0; i < str.length(); i++) {
    1984 String s = str.substring(i, i + 1);
    1985 if (s.charAt(0) > 0x80) {
    1986 byte[] bytes = s.getBytes("Unicode");
    1987 String binaryStr = "";
    1988 for (int j = 2; j < bytes.length; j += 2) {
    1989 // the first byte
    1990 String hexStr = getHexString(bytes[j + 1]);
    1991 String binStr = getBinaryString(Integer.valueOf(hexStr, 16));
    1992 binaryStr += binStr;
    1993 // the second byte
    1994 hexStr = getHexString(bytes[j]);
    1995 binStr = getBinaryString(Integer.valueOf(hexStr, 16));
    1996 binaryStr += binStr;
    1997 }
    1998 // convert unicode to utf-8
    1999 String s1 = "1110" + binaryStr.substring(0, 4);
    2000 String s2 = "10" + binaryStr.substring(4, 10);
    2001 String s3 = "10" + binaryStr.substring(10, 16);
    2002 byte[] bs = new byte[3];
    2003 bs[0] = Integer.valueOf(s1, 2).byteValue();
    2004 bs[1] = Integer.valueOf(s2, 2).byteValue();
    2005 bs[2] = Integer.valueOf(s3, 2).byteValue();
    2006 String ss = new String(bs, "UTF-8");
    2007 sb.append(ss);
    2008 } else {
    2009 sb.append(s);
    2010 }
    2011 }
    2012 return sb.toString();
    2013 }
    2014 
    2015 private static String getHexString(byte b) {
    2016 String hexStr = Integer.toHexString(b);
    2017 int m = hexStr.length();
    2018 if (m < 2) {
    2019 hexStr = "0" + hexStr;
    2020 } else {
    2021 hexStr = hexStr.substring(m - 2);
    2022 }
    2023 return hexStr;
    2024 }
    2025 
    2026 private static String getBinaryString(int i) {
    2027 String binaryStr = Integer.toBinaryString(i);
    2028 int length = binaryStr.length();
    2029 for (int l = 0; l < 8 - length; l++) {
    2030 binaryStr = "0" + binaryStr;
    2031 }
    2032 return binaryStr;
    2033 }
    2034 }
    2035 
    2036 
    2037 56.UTF-8文件转GB2312格式
    2038 private String utf8Togb2312(String str){
    2039 StringBuffer sb = new StringBuffer();
    2040 for(int i=0; i<str.length(); i++) {
    2041 char c = str.charAt(i);
    2042 switch (c) {
    2043 case '+':
    2044 sb.append(' ');
    2045 break;
    2046 case '%':
    2047 try {
    2048 sb.append((char)Integer.parseInt(
    2049 str.substring(i+1,i+3),16));
    2050 }
    2051 catch (NumberFormatException e) {
    2052 throw new IllegalArgumentException();
    2053 }
    2054 i += 2;
    2055 break;
    2056 default:
    2057 sb.append(c);
    2058 break;
    2059 }
    2060 }
    2061 // Undo conversion to external encoding
    2062 String result = sb.toString();
    2063 String res=null;
    2064 try{
    2065 byte[] inputBytes = result.getBytes("8859_1");
    2066 res= new String(inputBytes,"UTF-8");
    2067 }
    2068 catch(Exception e){}
    2069 return res;
    2070 }
    2071 
    2072 57.获取文件路径的父路径
    2073 String %%2=%%1.substring(0,%%1.lastIndexOf("\"));
    2074 
    2075 58.Unicode文件转UTF-8格式
    2076 try {
    2077 // Convert from Unicode to UTF-8
    2078 String string = "abcu5639u563b";
    2079 byte[] utf8 = string.getBytes("UTF-8");
    2080 // Convert from UTF-8 to Unicode
    2081 string = new String(utf8, "UTF-8");
    2082 } catch (UnsupportedEncodingException e) {
    2083 }
    2084 /**
    2085 * unicode 转换成 utf-8
    2086 * @author fanhui
    2087 * 2007-3-15
    2088 * @param theString
    2089 * @return
    2090 */
    2091 public static String unicodeToUtf8(String theString) {
    2092 char aChar;
    2093 int len = theString.length();
    2094 StringBuffer outBuffer = new StringBuffer(len);
    2095 for (int x = 0; x < len;) {
    2096 aChar = theString.charAt(x++);
    2097 if (aChar == '\') {
    2098 aChar = theString.charAt(x++);
    2099 if (aChar == 'u') {
    2100 // Read the xxxx
    2101 int value = 0;
    2102 for (int i = 0; i < 4; i++) {
    2103 aChar = theString.charAt(x++);
    2104 switch (aChar) {
    2105 case '0':
    2106 case '1':
    2107 case '2':
    2108 case '3':
    2109 case '4':
    2110 case '5':
    2111 case '6':
    2112 case '7':
    2113 case '8':
    2114 case '9':
    2115 value = (value << 4) + aChar - '0';
    2116 break;
    2117 case 'a':
    2118 case 'b':
    2119 case 'c':
    2120 case 'd':
    2121 case 'e':
    2122 case 'f':
    2123 value = (value << 4) + 10 + aChar - 'a';
    2124 break;
    2125 case 'A':
    2126 case 'B':
    2127 case 'C':
    2128 case 'D':
    2129 case 'E':
    2130 case 'F':
    2131 value = (value << 4) + 10 + aChar - 'A';
    2132 break;
    2133 default:
    2134 throw new IllegalArgumentException(
    2135 "Malformed \uxxxx encoding.");
    2136 }
    2137 }
    2138 outBuffer.append((char) value);
    2139 } else {
    2140 if (aChar == 't')
    2141 aChar = '	';
    2142 else if (aChar == 'r')
    2143 aChar = '
    ';
    2144 else if (aChar == 'n')
    2145 aChar = '
    ';
    2146 else if (aChar == 'f')
    2147 aChar = 'f';
    2148 outBuffer.append(aChar);
    2149 }
    2150 } else
    2151 outBuffer.append(aChar);
    2152 }
    2153 return outBuffer.toString();
    2154 }
    2155 
    2156 59.CRC循环冗余校验
    2157 /*
    2158 import java.nio.*;
    2159 import java.util.zip.*;
    2160 */
    2161 try {
    2162 FileInputStream in = new FileInputStream(%%1);
    2163 FileChannel channel = in.getChannel();
    2164 CRC32 crc = new CRC32();
    2165 int length = (int)channel.size();
    2166 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
    2167 for(int i = 0;i<length;i++)
    2168 {
    2169 int c = buffer.get(i);
    2170 crc.update(c);
    2171 }
    2172 System.out.println("crc校验和:"+(Long.toHexString(crc.getValue())).toUpperCase());
    2173 } catch (Exception e) {
    2174 e.printStackTrace();
    2175 }
    2176 
    2177 60.判断是否为空文件
    2178 //import java.io.*;
    2179 FileReader fr=new FileReader(%%1);
    2180 if(fr.read()==1)
    2181 //空白文件
    2182 
    2183 61.终止程序
    2184 Runtime.exec("taskkill /F /IM %%1.exe");
    2185 
    2186 62.定时关机
    2187 import java.awt.*;
    2188 import java.awt.event.*;
    2189 import java.awt.geom.*;
    2190 import java.util.*;
    2191 import javax.swing.*;
    2192 
    2193 public class ClockFrame extends JFrame {
    2194 private JComboBox hourBox, minuteBox, secondBox;
    2195 
    2196 private int hour, minute, second, totalSeconds, currentSeconds;
    2197 
    2198 private long argue;
    2199 
    2200 private GregorianCalendar calendar;
    2201 
    2202 private boolean change = true;
    2203 
    2204 private static final int WIDTH = 200;
    2205 
    2206 private static final int HEIGHT = 150;
    2207 
    2208 public ClockFrame() {
    2209 
    2210 setTitle("关机定时");
    2211 setSize(200, 150);
    2212 
    2213 Container contentPanel = getContentPane();
    2214 
    2215 JPanel timePanel = new JPanel();
    2216 timePanel.setLayout(new GridLayout(4, 2));
    2217 
    2218 JLabel minuteLable = new JLabel("设置分钟");
    2219 timePanel.add(minuteLable);
    2220 minuteBox = new JComboBox();
    2221 timePanel.add(minuteBox);
    2222 for (int i = 0; i < 60; i++) {
    2223 minuteBox.addItem(i);
    2224 }
    2225 minuteBox.addActionListener(new ActionListener() {
    2226 public void actionPerformed(ActionEvent evt) {
    2227 minute = ((Integer) minuteBox.getSelectedItem()).intValue();
    2228 }
    2229 });
    2230 
    2231 JLabel secondLable = new JLabel("设置秒钟");
    2232 timePanel.add(secondLable);
    2233 secondBox = new JComboBox();
    2234 timePanel.add(secondBox);
    2235 for (int i = 0; i < 60; i++) {
    2236 secondBox.addItem(i);
    2237 }
    2238 secondBox.addActionListener(new ActionListener() {
    2239 public void actionPerformed(ActionEvent evt) {
    2240 second = ((Integer) secondBox.getSelectedItem()).intValue();
    2241 }
    2242 });
    2243 contentPanel.add(timePanel, BorderLayout.CENTER);
    2244 
    2245 JButton check = new JButton("确定");
    2246 contentPanel.add(check, BorderLayout.SOUTH);
    2247 check.addActionListener(new ActionListener() {
    2248 public void actionPerformed(ActionEvent evt) {
    2249 JButton check=(JButton) evt.getSource();
    2250 if (check.getText().equals("确定")) {
    2251 calendar = new GregorianCalendar();
    2252 int currentSeconds = calendar.get(Calendar.HOUR_OF_DAY)
    2253 * 3600 + calendar.get(Calendar.MINUTE) * 60
    2254 + calendar.get(Calendar.SECOND);
    2255 totalSeconds = hour * 3600 + minute * 60 + second;
    2256 
    2257 if (totalSeconds - currentSeconds >= 0) {
    2258 argue = (totalSeconds - currentSeconds) * 1000;
    2259 JOptionPane.showMessageDialog(ClockFrame.this,
    2260 "您设置的时间为 " + hour + ":" + minute + ":" + second
    2261 + "
    程序将在后台运行,并在此时自动关闭计算机!", "设置成功",
    2262 JOptionPane.INFORMATION_MESSAGE);
    2263 hideFrame();
    2264 }
    2265 try {
    2266 // Thread.sleep(argue);//这句没用
    2267 Runtime.getRuntime().exec(
    2268 "shutdown.exe -s -c "我要关机了噢!不好意思!" -t "
    2269 + totalSeconds);
    2270 check.setText("取消");
    2271 } catch (Exception e) {
    2272 e.printStackTrace();
    2273 }
    2274 }else{
    2275 try {
    2276 Runtime.getRuntime().exec("shutdown.exe -a");
    2277 check.setText("确定");
    2278 } catch (Exception e) {
    2279 e.printStackTrace();
    2280 }
    2281 }
    2282 }
    2283 });
    2284 }
    2285 
    2286 private void hideFrame() {
    2287 this.setVisible(false);
    2288 }
    2289 
    2290 public static void main(String[] args) {
    2291 JFrame frame = new ClockFrame();
    2292 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    2293 frame.setLocationByPlatform(true);
    2294 frame.show();
    2295 }
    2296 }
    2297 
    2298 63.显示进程列表
    2299 //import java.io.*;
    2300 BufferedReader br=null;
    2301 try {
    2302 Process proc=Runtime.getRuntime().exec("tasklist");
    2303 br=new BufferedReader(new InputStreamReader(proc.getInputStream()));
    2304 @SuppressWarnings("unused")
    2305 String line=null;
    2306 while((line=br.readLine())!=null){
    2307 //br.readLine()
    2308 }
    2309 } catch (IOException e) {
    2310 e.printStackTrace();
    2311 }finally{
    2312 if(br!=null){
    2313 try {
    2314 br.close();
    2315 } catch (Exception e) {
    2316 e.printStackTrace();
    2317 }
    2318 }
    2319 }
    2320 
    2321 64.遍历文件夹列出文件大小
    2322 
    2323 65.目录下所有文件移动到整合操作
    2324 /*
    2325 import java.io.*;
    2326 import java.util.*;
    2327 import javax.swing.*;
    2328 */
    2329 JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
    2330 Jfc.showDialog(null, %%1);
    2331 if (!Jfc.getSelectedFile() != null) {
    2332 return;
    2333 }
    2334 String %%1 = Jfc.getSelectedFile().getParent();
    2335 Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
    2336 Jfc.showDialog(null, %%1);
    2337 if (!Jfc.getSelectedFile() != null) {
    2338 return;
    2339 }
    2340 String %%2 = Jfc.getSelectedFile().getParent();
    2341 
    2342 66.对目标压缩文件解压缩到指定文件夹
    2343 /*
    2344 import java.io.*;
    2345 import java.util.zip.*;
    2346 */
    2347 String zipFileName=%%1;
    2348 String extPlace=%%2;
    2349 File myFolderPath = new File(extPlace);
    2350 try {
    2351 if (!myFolderPath.exists()) {
    2352 myFolderPath.mkdir();
    2353 }
    2354 } catch (Exception e) {
    2355 //新建目录操作出错
    2356 e.printStackTrace();
    2357 return;
    2358 }
    2359 try {
    2360 ZipInputStream in = new ZipInputStream(new FileInputStream(
    2361 zipFileName));
    2362 ZipEntry entry = null;
    2363 while ((entry = in.getNextEntry()) != null) {
    2364 String entryName = entry.getName();
    2365 File file = new File(extPlace , entryName);
    2366 if (entry.isDirectory()) {
    2367 file.mkdirs();
    2368 } else {
    2369 FileOutputStream os = new FileOutputStream(file);
    2370 // Transfer bytes from the ZIP file to the output
    2371 // file
    2372 byte[] buf = new byte[10240];
    2373 int len;
    2374 while ((len = in.read(buf)) > 0) {
    2375 os.write(buf, 0, len);
    2376 }
    2377 os.close();
    2378 in.closeEntry();
    2379 }
    2380 }
    2381 } catch (IOException e) {
    2382 e.printStackTrace();
    2383 }
    2384 
    2385 67.创建目录副本整合操作
    2386 /*
    2387 import java.io.*;
    2388 import java.util.*;
    2389 import javax.swing.*;
    2390 */
    2391 JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
    2392 Jfc.showDialog(null, %%1);
    2393 if (!Jfc.getSelectedFile() != null) {
    2394 return;
    2395 }
    2396 String %%1 = Jfc.getSelectedFile().getParent();
    2397 Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
    2398 Jfc.showDialog(null, %%1);
    2399 if (!Jfc.getSelectedFile() != null) {
    2400 return;
    2401 }
    2402 String %%2 = Jfc.getSelectedFile().getParent();
    2403 
    2404 68.打开网页
    2405 //import java.io.*;
    2406 try{
    2407 String command = "C:\Program Files\Internet Explorer\Iexplore.exe "+%%1;
    2408 Runtime.getRuntime().exec(command);
    2409 } catch (IOException ex) {
    2410 ex.printStackTrace();
    2411 }
    2412 
    2413 69.删除空文件夹整合操作
    2414 /*
    2415 import java.io.*;
    2416 import java.util.*;
    2417 import javax.swing.*;
    2418 */
    2419 
    2420 70.获取磁盘所有分区,把结果放在数组drives中
    2421 String root; //root代表盘符路径
    2422 for(i=0;i<20;i++) //0-20代表最大的盘符数
    2423 {
    2424 root.Format("%c:\",allfenqu[i]);
    2425 if(GetDriveType(root)==5)
    2426 allfenqu[i]='';
    2427 }
    2428 
    2429 但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符:
    2430 String root;
    2431 for(i=0;i<20;i++)
    2432 {
    2433 root=allfenqu[i]+":\";
    2434 if(GetDriveType(root)==5)
    2435 allfenqu[i]='';
    2436 }
    2437 
    2438 71.激活一个程序或程序关联的文件
    2439 //import java.io.*;
    2440 try {
    2441 Runtime.getRuntime().exec(%%1);
    2442 } catch (IOException e) {
    2443 e.printStackTrace();
    2444 }
    2445 
    2446 72.MP3播放
    2447 //必须下载 jmf包
    2448 //import javax.media.bean.playerbean.MediaPlayer; //必须下载 jmf 媒体播放包
    2449 MediaPlayer player;
    2450 player = new MediaPlayer();
    2451 setLayout(new FlowLayout());
    2452 try{
    2453 player.setMediaLocation("file:/F:\音乐\mp3\黑白配.mp3");// <<file:/>>不能删除 音频文件路径
    2454 } catch (Exception e) {
    2455 System.err.println("文件不存在");
    2456 }
    2457 player.start();
    2458 player.stop();
    2459 
    2460 73.WAV播放
    2461 /*
    2462 import javax.sound.sampled.*;
    2463 import java.io.*;
    2464 */
    2465 private AudioFormat format;
    2466 private byte[] samples;
    2467 private String filename;
    2468 try {
    2469 // open the audio input stream
    2470 AudioInputStream stream =AudioSystem.getAudioInputStream(new File(filename));
    2471 format = stream.getFormat();
    2472 // get the audio samples
    2473 samples = getSamples(stream);
    2474 }
    2475 catch (UnsupportedAudioFileException ex) {
    2476 ex.printStackTrace();
    2477 }
    2478 catch (IOException ex) {
    2479 ex.printStackTrace();
    2480 }
    2481 
    2482 private byte[] getSamples(AudioInputStream audioStream) {
    2483 // get the number of bytes to read
    2484 int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
    2485 
    2486 // read the entire stream
    2487 byte[] samples = new byte[length];
    2488 DataInputStream is = new DataInputStream(audioStream);
    2489 try {
    2490 is.readFully(samples);
    2491 }
    2492 catch (IOException ex) {
    2493 ex.printStackTrace();
    2494 }
    2495 
    2496 // return the samples
    2497 return samples;
    2498 }
    2499 
    2500 public void play(InputStream source) {
    2501 
    2502 // use a short, 100ms (1/10th sec) buffer for real-time
    2503 // change to the sound stream
    2504 int bufferSize = format.getFrameSize() *
    2505 Math.round(format.getSampleRate() / 10);
    2506 byte[] buffer = new byte[bufferSize];
    2507 
    2508 // create a line to play to
    2509 SourceDataLine line;
    2510 try {
    2511 DataLine.Info info =
    2512 new DataLine.Info(SourceDataLine.class, format);
    2513 line = (SourceDataLine)AudioSystem.getLine(info);
    2514 line.open(format, bufferSize);
    2515 }
    2516 catch (LineUnavailableException ex) {
    2517 ex.printStackTrace();
    2518 return;
    2519 }
    2520 
    2521 // start the line
    2522 line.start();
    2523 
    2524 // copy data to the line
    2525 try {
    2526 int numBytesRead = 0;
    2527 while (numBytesRead != -1) {
    2528 numBytesRead =
    2529 source.read(buffer, 0, buffer.length);
    2530 if (numBytesRead != -1) {
    2531 line.write(buffer, 0, numBytesRead);
    2532 }
    2533 }
    2534 }
    2535 catch (IOException ex) {
    2536 ex.printStackTrace();
    2537 }
    2538 
    2539 // wait until all data is played, then close the line
    2540 line.drain();
    2541 line.close();
    2542 }
    2543 
    2544 throws Exception
    2545 String filename=%%1;
    2546 InputStream stream =new ByteArrayInputStream(sound.getSamples());
    2547 // play the sound
    2548 sound.play(stream);
    2549 
    2550 74.写图像到剪切板
    2551 /*
    2552 import java.awt.*;
    2553 import java.awt.datatransfer.*;
    2554 import java.io.*;
    2555 private final Image image;
    2556 */
    2557 Transferable trans = new Transferable() {
    2558 public DataFlavor[] getTransferDataFlavors() {
    2559 return new DataFlavor[] { DataFlavor.imageFlavor };
    2560 }
    2561 
    2562 public boolean isDataFlavorSupported(DataFlavor flavor) {
    2563 return DataFlavor.imageFlavor.equals(flavor);
    2564 }
    2565 
    2566 public Object getTransferData(DataFlavor flavor)
    2567 throws UnsupportedFlavorException, IOException {
    2568 if (isDataFlavorSupported(flavor))
    2569 return image;
    2570 throw new UnsupportedFlavorException(flavor);
    2571 }
    2572 };
    2573 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
    2574 null);
    2575 
    2576 75.从剪贴板复制图像到窗体
    2577 
    2578 76.删除文件夹下的所有文件且不删除文件夹下的文件夹
    2579 /*
    2580 import java.io.*;
    2581 import java.util.*;
    2582 */
    2583 LinkedList<String> folderList = new LinkedList<String>();
    2584 folderList.add(%%1);
    2585 while (folderList.size() > 0) {
    2586 File file = new File((String)folderList.poll());
    2587 File[] files = file.listFiles();
    2588 ArrayList<File> fileList = new ArrayList<File>();
    2589 for (int i = 0; i < files.length; i++) {
    2590 if (files[i].isDirectory()) {
    2591 folderList.add(files[i].getPath());
    2592 } else {
    2593 fileList.add(files[i]);
    2594 }
    2595 }
    2596 for (File f : fileList) {
    2597 f.delete();
    2598 }
    2599 }
    2600 
    2601 78.Unicode文件转GB2312格式
    2602 private static boolean isNeedConvert(char para){
    2603 return ((para&(0x00FF))!=para);
    2604 }
    2605 String dataStr=%%1;"\u9009 \u5173";
    2606 int index = 0;
    2607 StringBuffer buffer = new StringBuffer();
    2608 while(index<dataStr.length()) {
    2609 if(!"\u".equals(dataStr.substring(index,index+2))){
    2610 buffer.append(dataStr.charAt(index));
    2611 index++;
    2612 continue;
    2613 }
    2614 String charStr = "";
    2615 charStr = dataStr.substring(index+2,index+6);
    2616 char letter = (char) Integer.parseInt(charStr, 16 );
    2617 buffer.append(letter);
    2618 index+=6;
    2619 }
    2620 String %%2=buffer.toString();
    2621 
    2622 79.开源程序库Xercesc-C++代码工程中内联
    2623 import java.io.*;
    2624 import java.util.*;
    2625 import java.util.regex.*;
    2626 public class InlineXercesc {
    2627 private final String filter = ".cpp";
    2628 
    2629 private ArrayList<String> all = new ArrayList<String>();
    2630 
    2631 private LinkedList<String> fal2 = new LinkedList<String>();
    2632 
    2633 private static String CurDir = System.getProperty("user.dir");
    2634 
    2635 private void doSearch(String path) {
    2636 File filepath = new File(path);
    2637 if (filepath.exists() && filepath.isDirectory()) {
    2638 File[] fileArray = filepath.listFiles();
    2639 for (File f : fileArray) {
    2640 if (f.isDirectory()) {
    2641 doSearch(f.getPath());
    2642 } else {
    2643 if (f.getName().indexOf(filter) >= 0) {
    2644 for (String file : all) {
    2645 if (file.substring(file.lastIndexOf("\") + 1)
    2646 .equals(f.getName())) {
    2647 fal2.add(f.getAbsolutePath());
    2648 }
    2649 }
    2650 }
    2651 }
    2652 }
    2653 }
    2654 }
    2655 
    2656 public InlineXercesc(String lib) throws IOException {
    2657 String SourceLib = "D:\Desktop\大项目\xerces-c-3.0.1\src";
    2658 Pattern pattern = Pattern.compile("include.*?" + lib + ".*?>"); // 第一个参数为需要匹配的字符串
    2659 Matcher matcher = pattern.matcher("");
    2660 LinkedList<String> fal = new LinkedList<String>();
    2661 File delfile = new File(CurDir);
    2662 File[] files2 = delfile.listFiles();
    2663 for (int l = 0; l < files2.length; l++) {
    2664 if (files2[l].isDirectory()) {
    2665 String enumDir = CurDir + "\" + files2[l].getName() + "\";
    2666 LinkedList<String> folderList = new LinkedList<String>();
    2667 folderList.add(files2[l].getAbsolutePath());
    2668 while (folderList.size() > 0) {
    2669 File file = new File((String)folderList.poll());
    2670 File[] files = file.listFiles();
    2671 for (int i = 0; i < files.length; i++) {
    2672 if (files[i].isDirectory()) {
    2673 folderList.add(files[i].getPath());
    2674 } else {
    2675 String fileStr = files[i].getAbsolutePath(); // 第2个参数开始,均为文件名。
    2676 BufferedReader br = null;
    2677 String line;
    2678 try {
    2679 br = new BufferedReader(new FileReader(fileStr)); // 打开文件
    2680 } catch (IOException e) {
    2681 // 没有打开文件,则产生异常
    2682 System.err.println("Cannot read '" + fileStr
    2683 + "': " + e.getMessage());
    2684 continue;
    2685 }
    2686 StringBuilder sb = new StringBuilder(2048);
    2687 while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
    2688 matcher.reset(line); // 匹配字符串
    2689 if (matcher.find()) { // 如果有匹配的字符串,则输出
    2690 sb.append(line.replace(
    2691 line.substring(line.indexOf("<"),
    2692 line.lastIndexOf("/") + 1),
    2693 """).replace('>', '"'));
    2694 line = line.substring(
    2695 line.indexOf("<") + 1,
    2696 line.lastIndexOf(">")).replace('/',
    2697 '\');
    2698 fal.add(SourceLib + "\" + line);
    2699 } else {
    2700 sb.append(line);
    2701 }
    2702 sb.append("
    ");
    2703 }
    2704 br.close(); // 关闭文件
    2705 FileWriter fw2 = new FileWriter(fileStr);
    2706 fw2.write(sb.toString());
    2707 fw2.flush();
    2708 fw2.close();
    2709 }
    2710 }
    2711 }
    2712 while (fal.size() > 0) {
    2713 String file = fal.poll(); // 第2个参数开始,均为文件名。
    2714 String targetPath = enumDir
    2715 + file.substring(file.lastIndexOf("\") + 1);
    2716 if (!new File(targetPath).exists()) {
    2717 BufferedReader br = null;
    2718 String line;
    2719 try {
    2720 br = new BufferedReader(new FileReader(file)); // 打开文件
    2721 } catch (IOException e) {
    2722 // 没有打开文件,则产生异常
    2723 System.err.println("Cannot read '" + file + "': "
    2724 + e.getMessage());
    2725 continue;
    2726 }
    2727 FileWriter fw = new FileWriter(targetPath);
    2728 while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
    2729 matcher.reset(line); // 匹配字符串
    2730 if (matcher.find()) { // 如果有匹配的字符串,则输出
    2731 fal.add(SourceLib
    2732 + "\"
    2733 + line.substring(line.indexOf("<") + 1,
    2734 line.lastIndexOf(">")).replace(
    2735 '/', '\'));
    2736 line = line.replace(line.substring(line
    2737 .indexOf("<"),
    2738 line.lastIndexOf("/") + 1), """);
    2739 line = line.replace(">", """);
    2740 
    2741 }
    2742 fw.write(line + "
    ");
    2743 }
    2744 fw.flush();
    2745 fw.close();
    2746 br.close(); // 关闭文件
    2747 
    2748 }
    2749 }
    2750 LinkedList<String> folderListArr = new LinkedList<String>();
    2751 folderListArr.add(CurDir);
    2752 while (folderListArr.size() > 0) {
    2753 File file = new File(folderListArr.poll());
    2754 File[] files = file.listFiles();
    2755 for (int i = 0; i < files.length; i++) {
    2756 if (files[i].isDirectory()) {
    2757 folderListArr.add(files[i].getPath());
    2758 } else {
    2759 if (files[i].getName().substring(
    2760 files[i].getName().lastIndexOf('.'))
    2761 .equals(".hpp"))
    2762 all.add(files[i].getAbsoluteFile().toString()
    2763 .replace(".hpp", ".cpp"));
    2764 }
    2765 }
    2766 }
    2767 int count = 1;
    2768 while (count > 0) {
    2769 doSearch(SourceLib);
    2770 all.clear();
    2771 while (fal2.size() > 0) {
    2772 String file1 = fal2.poll(); // 第2个参数开始,均为文件名。
    2773 String targetPath = enumDir
    2774 + file1.substring(file1.lastIndexOf("\") + 1);
    2775 if (!new File(targetPath).exists()) {
    2776 BufferedReader br = null;
    2777 String line;
    2778 try {
    2779 br = new BufferedReader(new FileReader(file1)); // 打开文件
    2780 } catch (IOException e) {
    2781 // 没有打开文件,则产生异常
    2782 System.err.println("Cannot read '" + file1
    2783 + "': " + e.getMessage());
    2784 continue;
    2785 }
    2786 FileWriter fw;
    2787 try {
    2788 fw = new FileWriter(targetPath);
    2789 while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
    2790 matcher.reset(line); // 匹配字符串
    2791 if (matcher.find()) { // 如果有匹配的字符串,则输出
    2792 fal2.add(SourceLib
    2793 + "\"
    2794 + line.substring(
    2795 line.indexOf('<') + 1,
    2796 line.lastIndexOf('>'))
    2797 .replace('/', '\'));
    2798 all.add(fal2.getLast().replace(".hpp",
    2799 ".cpp"));
    2800 line = line.replace(line.substring(line
    2801 .indexOf('<'), line
    2802 .lastIndexOf('/') + 1), """);
    2803 line = line.replace('>', '"');
    2804 }
    2805 fw.write(line + "
    ");
    2806 }
    2807 fw.flush();
    2808 fw.close();
    2809 br.close(); // 关闭文件
    2810 } catch (IOException e) {
    2811 e.printStackTrace();
    2812 }
    2813 }
    2814 }
    2815 count = all.size();
    2816 }
    2817 }
    2818 }
    2819 }
    2820 
    2821 public static void main(String[] args) {
    2822 try {
    2823 new InlineXercesc("xercesc");
    2824 // 将数据写入文件
    2825 try {
    2826 FileWriter fw = new FileWriter(CurDir + "\DetailCpp.cmd");
    2827 fw.write("copy StdAfx.cpp+*.c+*.cpp " + CurDir
    2828 + "\StdAfx.cpp && del *.c && del *.cpp");
    2829 fw.flush();
    2830 fw.close();
    2831 } catch (IOException e) {
    2832 e.printStackTrace();
    2833 }
    2834 } catch (IOException e) {
    2835 }
    2836 }
    2837 }
    2838 
    2839 80.提取包含头文件列表
    2840 import java.io.*;
    2841 import java.util.regex.*;
    2842 import java.util.*;
    2843 public class InlineExt {
    2844 private String CurDir = System.getProperty("user.dir");
    2845 public InlineExt() {
    2846 Pattern pattern = Pattern.compile("include.*?".*?.hpp""); // 第一个参数为需要匹配的字符串
    2847 Matcher matcher = pattern.matcher("");
    2848 File delfile = new File(CurDir);
    2849 File[] files2 = delfile.listFiles();
    2850 for (int l = 0; l < files2.length; l++) {
    2851 if (files2[l].isDirectory()) {
    2852 Set<String> ts = new LinkedHashSet<String>();
    2853 File file = new File(files2[l].getPath(), "StdAfx.cpp");
    2854 BufferedReader br = null;
    2855 FileWriter fw = null;
    2856 String line;
    2857 try {
    2858 br = new BufferedReader(new FileReader(file)); // 打开文件
    2859 while ((line = br.readLine()) != null) {
    2860 matcher.reset(line); // 匹配字符串
    2861 if (matcher.find()) { // 如果有匹配的字符串,则输出
    2862 ts.add(line.substring(line.indexOf('"') + 1, line
    2863 .lastIndexOf('"')));
    2864 }
    2865 }
    2866 Iterator<String> it = ts.iterator();
    2867 File file2 = new File(files2[l], "ReadMe.txt");
    2868 if (file2.exists()) {
    2869 fw = new FileWriter(file2);
    2870 while (it.hasNext()) {
    2871 fw.write("#include "" + it.next() + ""
    ");
    2872 }
    2873 }
    2874 } catch (IOException e) {
    2875 // 没有打开文件,则产生异常
    2876 System.err.println("Cannot read '" + file + "': "
    2877 + e.getMessage());
    2878 continue;
    2879 } finally {
    2880 try {
    2881 if (br != null)
    2882 br.close();
    2883 if (fw != null)
    2884 fw.close();
    2885 } catch (IOException e) {
    2886 e.printStackTrace();
    2887 }
    2888 }
    2889 }
    2890 }
    2891 }
    2892 public static void main(String[] args) {
    2893 new InlineExt();
    2894 }
    2895 }
    2896 
    2897 81.GB2312文件转Unicode格式
    2898 
    2899 
    2900 82.Java程序打包
    2901 /*
    2902 import java.io.*;
    2903 import java.util.*;
    2904 private static String className;
    2905 private static File myFilePath;
    2906 */
    2907 String path=%%1;
    2908 ProcessBuilder pb = null;
    2909 myFilePath = new File(path, "conf.txt");
    2910 LinkedList<String> folderList = new LinkedList<String>();
    2911 folderList.add(path);
    2912 while (folderList.size() > 0) {
    2913 File file = new File((String)folderList.poll());
    2914 File[] files = file.listFiles();
    2915 for (int i = 0; i < files.length; i++) {
    2916 if (files[i].isDirectory()) {
    2917 folderList.add(files[i].getPath());
    2918 } else {
    2919 if (files[i].getName().substring(2).contains(".")
    2920 && files[i].getName().substring(
    2921 files[i].getName().lastIndexOf('.'))
    2922 .equals(".java")) {
    2923 
    2924 try {
    2925 className = files[i].getName().substring(0,
    2926 files[i].getName().lastIndexOf('.'));
    2927 if (!myFilePath.exists())
    2928 myFilePath.createNewFile();
    2929 FileWriter resultFile = new FileWriter(myFilePath);
    2930 PrintWriter myFile = new PrintWriter(resultFile);
    2931 myFile.println("Main-Class:" + className);
    2932 myFile.flush();
    2933 myFile.close();
    2934 resultFile.close();
    2935 pb = new ProcessBuilder("javac", files[i]
    2936 .getAbsolutePath()
    2937 + " && jar cmf "
    2938 + myFilePath.getAbsolutePath()
    2939 + " "
    2940 + className
    2941 + ".jar "
    2942 + className
    2943 + ".class");
    2944 pb.start();
    2945 } catch (IOException e) {
    2946 e.printStackTrace();
    2947 }
    2948 }
    2949 }
    2950 }
    2951 }
    2952 folderList = new LinkedList<String>();
    2953 folderList.add(path);
    2954 while (folderList.size() > 0) {
    2955 File file = new File((String)folderList.poll());
    2956 File[] files = file.listFiles();
    2957 for (int i = 0; i < files.length; i++) {
    2958 if (files[i].isDirectory()) {
    2959 folderList.add(files[i].getPath());
    2960 } else {
    2961 if (files[i].getName().substring(2).contains(".")
    2962 && files[i].getName().substring(
    2963 files[i].getName().lastIndexOf('.'))
    2964 .equals(".class")) {
    2965 files[i].delete();
    2966 }
    2967 }
    2968 }
    2969 }
    2970 
    2971 83.UTF-8文件转Unicode格式
    2972 /**
    2973 * utf-8 转换成 unicode
    2974 * @author fanhui
    2975 * 2007-3-15
    2976 * @param inStr
    2977 * @return
    2978 */
    2979 public static String utf8ToUnicode(String inStr) {
    2980 char[] myBuffer = inStr.toCharArray();
    2981 
    2982 StringBuffer sb = new StringBuffer();
    2983 for (int i = 0; i < inStr.length(); i++) {
    2984 UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
    2985 if(ub == UnicodeBlock.BASIC_LATIN){
    2986 //英文及数字等
    2987 sb.append(myBuffer[i]);
    2988 }else if(ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS){
    2989 //全角半角字符
    2990 int j = (int) myBuffer[i] - 65248;
    2991 sb.append((char)j);
    2992 }else{
    2993 //汉字
    2994 short s = (short) myBuffer[i];
    2995 String hexS = Integer.toHexString(s);
    2996 String unicode = "\u"+hexS;
    2997 sb.append(unicode.toLowerCase());
    2998 }
    2999 }
    3000 return sb.toString();
    3001 }
    3002 
    3003 84.创建PDF文档
    3004 /*
    3005 http://www.lowagie.com/iText/
    3006 http://jaist.dl.sourceforge.net/sourceforge/itext/itext-1.4.jar
    3007 http://itextdocs.lowagie.com/downloads/iTextAsian.jar
    3008 http://itextdocs.lowagie.com/downloads/iTextAsianCmaps.jar
    3009 import java.io.*;
    3010 import com.lowagie.text.*;
    3011 import com.lowagie.text.pdf.PdfWriter;
    3012 */
    3013 Document document = new Document();
    3014 try
    3015 {
    3016 PdfWriter.getInstance(document, new FileOutputStream(%%1)); //"HelloWorld.pdf"
    3017 // 添加PDF文档的一些信息
    3018 document.addTitle("Hello World example");
    3019 document.addAuthor("Bruno Lowagie");
    3020 document.addSubject("This example explains how to add metadata.");
    3021 document.addKeywords("iText, Hello World, step 3, metadata");
    3022 document.addCreator("My program using iText");
    3023 document.open();
    3024 // 插入一个段落
    3025 document.add(new Paragraph("Hello World!"));
    3026 
    3027 }
    3028 catch (DocumentException de)
    3029 {
    3030 System.err.println(de.getMessage());
    3031 }
    3032 catch (IOException ioe)
    3033 {
    3034 System.err.println(ioe.getMessage());
    3035 }
    3036 
    3037 // 关闭打开的文档
    3038 document.close();
    3039 
    3040 三、中文问题:
    3041 
    3042 由于iText不支持东亚语言,我们下载了iTextAsian.jar 以后,就可以在PDF里面写中文:
    3043 
    3044 /**
    3045 * AsianTest.java
    3046 */
    3047 import java.io.*;
    3048 import com.lowagie.text.*;
    3049 import com.lowagie.text.pdf.*;
    3050 import java.awt.*;
    3051 
    3052 public class AsianTest{
    3053 
    3054 public static void main(String[] args) {
    3055 
    3056 // 创建一个Document对象
    3057 Document document = new Document();
    3058 
    3059 try
    3060 {
    3061 
    3062 // 生成名为 AsianTest.pdf 的文档
    3063 PdfWriter.getInstance(document, new FileOutputStream("AsianTest.pdf"));
    3064 
    3065 /** 新建一个字体,iText的方法
    3066 * STSongStd-Light 是字体,在iTextAsian.jar 中以property为后缀
    3067 * UniGB-UCS2-H 是编码,在iTextAsian.jar 中以cmap为后缀
    3068 * H 代表文字版式是 横版, 相应的 V 代表 竖版
    3069 */
    3070 BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
    3071 
    3072 Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.GREEN);
    3073 
    3074 // 打开文档,将要写入内容
    3075 document.open();
    3076 
    3077 // 插入一个段落
    3078 Paragraph par = new Paragraph("我们",fontChinese);
    3079 
    3080 document.add(par);
    3081 
    3082 }
    3083 catch (DocumentException de)
    3084 {
    3085 System.err.println(de.getMessage());
    3086 }
    3087 catch (IOException ioe)
    3088 {
    3089 System.err.println(ioe.getMessage());
    3090 }
    3091 
    3092 // 关闭打开的文档
    3093 document.close();
    3094 }
    3095 }
    3096 
    3097 就可以显示中文了。
    3098 
    3099 
    3100 四、其他问题:(应导入相应的包)
    3101 
    3102 1. 换页:
    3103 
    3104 document.newPage();
    3105 
    3106 2. 表格:
    3107 
    3108 // 设置 Table
    3109 Table aTable = new Table(3);
    3110 int width[] = {25,25,50};
    3111 aTable.setWidths(width);
    3112 aTable.setWidth(80); // 占页面宽度 80%
    3113 
    3114 aTable.setDefaultHorizontalAlignment(Element.ALIGN_LEFT);
    3115 aTable.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);
    3116 aTable.setAutoFillEmptyCells(true); //自动填满
    3117 aTable.setPadding(1);
    3118 aTable.setSpacing(1);
    3119 aTable.setDefaultCellBorder(0);
    3120 aTable.setBorder(0);
    3121 
    3122 Cell cell = new Cell(new Phrase("这是一个测试的 3*3 Table 数据", fontChinese ));
    3123 cell.setVerticalAlignment(Element.ALIGN_TOP);
    3124 cell.setRowspan(3);
    3125 aTable.addCell(cell);
    3126 
    3127 aTable.addCell(new Cell("#1"));
    3128 aTable.addCell(new Cell("#2"));
    3129 aTable.addCell(new Cell("#3"));
    3130 
    3131 aTable.addCell(new Cell("#4"));
    3132 aTable.addCell(new Cell("#5"));
    3133 aTable.addCell(new Cell("#6"));
    3134 
    3135 document.add(aTable);
    3136 
    3137 3. 图片:
    3138 
    3139 // 可以是绝对路径,也可以是URL
    3140 Image img = Image.getInstance("logo.gif");
    3141 
    3142 // Image image = Image.getInstance(new URL(http://xxx.com/logo.jpg));
    3143 
    3144 img.setAbsolutePosition(0, 0);
    3145 
    3146 document.add(img);
    3147 
    3148 五、参考文档:
    3149 
    3150 iText
    3151 http://www.lowagie.com/iText/
    3152 
    3153 iText API:
    3154 http://itext.sourceforge.net/docs/
    3155 
    3156 http://www.sentom.net/list.asp?id=42
    3157 
    3158 85.创建Word文档
    3159 /*
    3160 import java.awt.*;
    3161 import java.io.*;
    3162 import com.lowagie.text.*;
    3163 import com.lowagie.text.pdf.*;
    3164 import com.lowagie.text.rtf.*;
    3165 */
    3166 public void createDocContext(String file) throws DocumentException,
    3167 IOException {
    3168 // 设置纸张大小
    3169 Document document = new Document(PageSize.A4);
    3170 // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    3171 RtfWriter2.getInstance(document, new FileOutputStream(file));
    3172 document.open();
    3173 // 设置中文字体
    3174 BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
    3175 "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    3176 // 标题字体风格
    3177 Font titleFont = new Font(bfChinese, 12, Font.BOLD);
    3178 // 正文字体风格
    3179 Font contextFont = new Font(bfChinese, 10, Font.NORMAL);
    3180 Paragraph title = new Paragraph("标题");
    3181 // 设置标题格式对齐方式
    3182 title.setAlignment(Element.ALIGN_CENTER);
    3183 title.setFont(titleFont);
    3184 document.add(title);
    3185 
    3186 String contextString = "iText是一个能够快速产生PDF文件的java类库。"
    3187 + " 
    "// 换行
    3188 + "iText的java类对于那些要产生包含文本,"
    3189 + "表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。"
    3190 + "使用iText与PDF能够使你正确的控制Servlet的输出。";
    3191 Paragraph context = new Paragraph(contextString);
    3192 // 正文格式左对齐
    3193 context.setAlignment(Element.ALIGN_LEFT);
    3194 context.setFont(contextFont);
    3195 // 离上一段落(标题)空的行数
    3196 context.setSpacingBefore(5);
    3197 // 设置第一行空的列数
    3198 context.setFirstLineIndent(20);
    3199 document.add(context);
    3200 
    3201 //利用类FontFactory结合Font和Color可以设置各种各样字体样式
    3202 /**
    3203 * Font.UNDERLINE 下划线,Font.BOLD 粗体
    3204 */
    3205 Paragraph underline = new Paragraph("下划线的实现", FontFactory.getFont(
    3206 FontFactory.HELVETICA_BOLDOBLIQUE, 18, Font.UNDERLINE,
    3207 new Color(0, 0, 255)));
    3208 document.add(underline);
    3209 
    3210 // 设置 Table 表格
    3211 Table aTable = new Table(3);
    3212 int width[] = {25,25,50};
    3213 aTable.setWidths(width);//设置每列所占比例
    3214 aTable.setWidth(90); // 占页面宽度 90%
    3215 
    3216 aTable.setAlignment(Element.ALIGN_CENTER);//居中显示
    3217 aTable.setAlignment(Element.ALIGN_MIDDLE);//纵向居中显示
    3218 aTable.setAutoFillEmptyCells(true); //自动填满
    3219 aTable.setBorderWidth(1); //边框宽度
    3220 aTable.setBorderColor(new Color(0, 125, 255)); //边框颜色
    3221 aTable.setPadding(2);//衬距,看效果就知道什么意思了
    3222 aTable.setSpacing(3);//即单元格之间的间距
    3223 aTable.setBorder(2);//边框
    3224 
    3225 //设置表头
    3226 /**
    3227 * cell.setHeader(true);是将该单元格作为表头信息显示;
    3228 * cell.setColspan(3);指定了该单元格占3列;
    3229 * 为表格添加表头信息时,要注意的是一旦表头信息添加完了之后,
    3230 * 必须调用 endHeaders()方法,否则当表格跨页后,表头信息不会再显示
    3231 */
    3232 Cell haderCell = new Cell("表格表头");
    3233 haderCell.setHeader(true);
    3234 haderCell.setColspan(3);
    3235 aTable.addCell(haderCell);
    3236 aTable.endHeaders();
    3237 
    3238 Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.GREEN);
    3239 Cell cell = new Cell(new Phrase("这是一个测试的 3*3 Table 数据", fontChinese ));
    3240 cell.setVerticalAlignment(Element.ALIGN_TOP);
    3241 cell.setBorderColor(new Color(255, 0, 0));
    3242 cell.setRowspan(2);
    3243 aTable.addCell(cell);
    3244 
    3245 aTable.addCell(new Cell("#1"));
    3246 aTable.addCell(new Cell("#2"));
    3247 aTable.addCell(new Cell("#3"));
    3248 aTable.addCell(new Cell("#4"));
    3249 Cell cell3 = new Cell(new Phrase("一行三列数据", fontChinese ));
    3250 cell3.setColspan(3);
    3251 cell3.setVerticalAlignment(Element.ALIGN_CENTER);
    3252 aTable.addCell(cell3);
    3253 
    3254 document.add(aTable);
    3255 document.add(new Paragraph("
    "));
    3256 //添加图片
    3257 Image img=Image.getInstance("d:\img01800.jpg");
    3258 img.setAbsolutePosition(0, 0);
    3259 img.setAlignment(Image.RIGHT);//设置图片显示位置
    3260 img.scaleAbsolute(12,35);//直接设定显示尺寸
    3261 img.scalePercent(50);//表示显示的大小为原尺寸的50%
    3262 img.scalePercent(25, 12);//图像高宽的显示比例
    3263 img.setRotation(30);//图像旋转一定角度
    3264 document.add(img);
    3265 
    3266 document.close();
    3267 }
    3268 
    3269 /**
    3270 * @param args
    3271 */
    3272 public static void main(String[] args) {
    3273 CreateWordDemo word = new CreateWordDemo();
    3274 String file = "c:/demo1.doc";
    3275 try {
    3276 word.createDocContext(file);
    3277 } catch (DocumentException e) {
    3278 e.printStackTrace();
    3279 } catch (IOException e) {
    3280 e.printStackTrace();
    3281 }
    3282 }
    3283 
    3284 /* 内部线程类 */
    3285 class Son extends Thread
    3286 {
    3287 private ICallBack event;
    3288 public Son(ICallBack callback)
    3289 {
    3290 event=callback;
    3291 }
    3292 public void run()
    3293 {
    3294 try
    3295 {
    3296 java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    3297 while(true)
    3298 {
    3299 Thread.currentThread().sleep(3000);
    3300 event.output(fmt.format(new java.util.Date()));
    3301 Thread.currentThread().sleep(3000);
    3302 }
    3303 }
    3304 catch (Exception e)
    3305 {
    3306 }
    3307 }
    3308 }
    3309 
    3310 /* 回调接口 */
    3311 interface ICallBack
    3312 {
    3313 public void output();
    3314 }
    3315 
    3316 86.快速高效的文件加密
    3317 /*
    3318 import java.util.*;
    3319 import java.io.*;
    3320 import javax.swing.*;
    3321 */
    3322 private static final String CharSet = "0123456789ABCDEF";
    3323 private static final int a[] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    3324 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
    3325 private static final int b[] = { 3, 3, 3, 5, 5, 3, 3, 3, 5, 3, 5, 3, 7, 3,
    3326 11, 7, 11, 3, 5, 3, 3, 3, 7, 5, 5, 3, 7, 3, 11, 13, 3 };
    3327 private static final int c[] = { 3, 5, 7, 5, 7, 11, 13, 19, 17, 29, 19, 31,
    3328 17, 41, 11, 19, 13, 47, 29, 53, 59, 67, 29, 41, 43, 71, 31, 73, 23,
    3329 23, 101 };
    3330 private static final int d[] = { 5, 7, 11, 13, 17, 17, 19, 29, 43, 43, 47,
    3331 47, 59, 61, 61, 67, 71, 71, 73, 79, 89, 101, 101, 103, 107, 107,
    3332 109, 109, 127, 149, 151 };
    3333 private static int ka, kb, kc, kd;
    3334 
    3335 private static void init() {
    3336 Date t1 = new Date();
    3337 Date t2 = new Date(79, 8, 23, 8, 30, 0); // "9-23-1979 8:30"
    3338 int GetDays = 0;
    3339 int result = 0;
    3340 Calendar start = new GregorianCalendar();
    3341 Calendar end = new GregorianCalendar();
    3342 start.setTime(t2);
    3343 end.setTime(t1);
    3344 Calendar startCalendar = start;
    3345 int startYear = start.get(Calendar.YEAR);
    3346 int startMonth = start.get(Calendar.MONTH);
    3347 int startDayOfM = start.get(Calendar.DAY_OF_MONTH);
    3348 int startDayOfY = start.get(Calendar.DAY_OF_YEAR);
    3349 
    3350 Calendar endCalendar = end;
    3351 int endYear = end.get(Calendar.YEAR);
    3352 int endMonth = end.get(Calendar.MONTH);
    3353 int endDayOfM = end.get(Calendar.DAY_OF_MONTH);
    3354 int endDayOfY = end.get(Calendar.DAY_OF_YEAR);
    3355 int startLastYear = 0, startLastDayOfY = 0;
    3356 if (endYear == startYear) {
    3357 startLastYear = endDayOfY < startDayOfY ? startYear : endYear;
    3358 startLastDayOfY = endDayOfY < startDayOfY ? startDayOfY : endDayOfY;
    3359 } else if (endYear < startYear) {
    3360 startLastYear = startYear;
    3361 startLastDayOfY = startDayOfY;
    3362 } else {
    3363 startLastYear = endYear;
    3364 startLastDayOfY = endDayOfY;
    3365 }
    3366 
    3367 if ((endYear == startYear && endDayOfY == startDayOfY)
    3368 || (startLastYear == startYear && startLastDayOfY == startDayOfY)) {
    3369 GetDays = result;
    3370 } else if (startYear == endYear) {
    3371 GetDays = endDayOfY - startDayOfY;
    3372 } else {
    3373 Calendar tmp = Calendar.getInstance();
    3374 result = startCalendar.getActualMaximum(Calendar.DAY_OF_YEAR)
    3375 - startDayOfY;
    3376 for (int i = startYear + 1; i < endYear; i++) {
    3377 tmp.set(i, tmp.get(Calendar.MONTH), tmp
    3378 .get(Calendar.DAY_OF_MONTH));
    3379 result += tmp.getActualMaximum(Calendar.DAY_OF_YEAR);
    3380 }
    3381 result += end.get(Calendar.DAY_OF_YEAR);
    3382 GetDays = result;
    3383 }
    3384 Random rand = new Random(GetDays * 8 - 55);
    3385 int r = rand.nextInt(GetDaysInMoths(t2.getMonth() + 1));
    3386 r=0;
    3387 ka = a[r];
    3388 kb = b[r];
    3389 kc = c[r];
    3390 kd = d[r];
    3391 }
    3392 
    3393 private static int GetDaysInMoths(int nMoths) {
    3394 switch (nMoths) {
    3395 case 2: {
    3396 int nYear = new Date().getYear() + 1900;
    3397 if ((nYear % 4 == 0) && (nYear % 400) != 0) {
    3398 return 29;
    3399 } else {
    3400 return 28;
    3401 }
    3402 }
    3403 case 1:
    3404 case 3:
    3405 case 5:
    3406 case 7:
    3407 case 8:
    3408 case 10:
    3409 case 12:
    3410 return 31;
    3411 case 4:
    3412 case 6:
    3413 case 9:
    3414 case 11:
    3415 return 30;
    3416 default:
    3417 return -1;
    3418 }
    3419 }
    3420 
    3421 private static int niyuan(int m, int n) {
    3422 int a, b, c, d, t, yu = 0, shang, mod;
    3423 a = m;
    3424 b = n;
    3425 mod = a;
    3426 c = 0;
    3427 d = 1;
    3428 while (b < 0)
    3429 b += a;
    3430 if (a % b == 0 || b % 2 == 0)
    3431 return 0;
    3432 while (b != 1) {
    3433 t = a % b;
    3434 shang = a / b;
    3435 a = b;
    3436 b = t;
    3437 yu = c - shang * d;
    3438 c = d;
    3439 d = yu;
    3440 }
    3441 if (yu < 0)
    3442 yu += mod;
    3443 return yu;
    3444 }
    3445 JFileChooser chooser = new JFileChooser();
    3446 chooser.setCurrentDirectory(new File("E:"));
    3447 chooser
    3448 .addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
    3449 public boolean accept(File f) {
    3450 return f.getName().toLowerCase().endsWith(".zip")
    3451 || f.isDirectory();
    3452 }
    3453 
    3454 public String getDescription() {
    3455 return "Compress Files(*.zip)";
    3456 }
    3457 });
    3458 chooser
    3459 .addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
    3460 public boolean accept(File f) {
    3461 return f.getName().toLowerCase().endsWith(".txt")
    3462 || f.isDirectory();
    3463 }
    3464 
    3465 public String getDescription() {
    3466 return "Text Files(*.txt)";
    3467 }
    3468 });
    3469 chooser
    3470 .addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
    3471 public boolean accept(File f) {
    3472 return f.getName().toLowerCase().endsWith(".exe")
    3473 || f.isDirectory();
    3474 }
    3475 
    3476 public String getDescription() {
    3477 return "Executeable Files(*.exe)";
    3478 }
    3479 });
    3480 if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    3481 String name = chooser.getSelectedFile().getPath();
    3482 JFileChooser chooser2 = new JFileChooser();
    3483 chooser2.setCurrentDirectory(new File("E:"));
    3484 if (name.substring(name.lastIndexOf('.')).equals(".txt")) {
    3485 char[] sRead = new char[10240];
    3486 char[] hexstr = new char[10240];
    3487 char[] pbuf = new char[20480];
    3488 char[] rRead = new char[20480];
    3489 char[] out2 = new char[10240];
    3490 chooser2
    3491 .addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
    3492 public boolean accept(File f) {
    3493 return f.getName().toLowerCase().endsWith(
    3494 ".zip")
    3495 || f.isDirectory();
    3496 }
    3497 
    3498 public String getDescription() {
    3499 return "Compress Files(*.zip)";
    3500 }
    3501 });
    3502 chooser2
    3503 .addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
    3504 public boolean accept(File f) {
    3505 return f.getName().toLowerCase().endsWith(
    3506 ".exe")
    3507 || f.isDirectory();
    3508 }
    3509 
    3510 public String getDescription() {
    3511 return "Executeable Files(*.exe)";
    3512 }
    3513 });
    3514 if (chooser2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    3515 init();
    3516 FileOutputStream fw = null;
    3517 try {
    3518 FileInputStream fis = new FileInputStream(chooser
    3519 .getSelectedFile());
    3520 fw = new FileOutputStream(chooser2.getSelectedFile());
    3521 byte[] buffer = new byte[20480];
    3522 int js = 0, tmp;
    3523 int aany, ddny;
    3524 int r00 = ka * kc * kd;
    3525 int r01 = -ka * kb * kc;
    3526 int r10 = -kb * kc * kc;
    3527 int r11 = ka * kb * kc;
    3528 int x00 = ka * ka * kc * kd - ka * kb * kc * kc;
    3529 int x11 = ka * kb * kc * kd - kb * kb * kc * kc;
    3530 while (x00 % 2 == 0) {
    3531 x00 /= 2;
    3532 r00 /= 2;
    3533 r01 /= 2;
    3534 }
    3535 while (x11 % 2 == 0) {
    3536 x11 /= 2;
    3537 r10 /= 2;
    3538 r11 /= 2;
    3539 }
    3540 aany = x00;
    3541 ddny = x11;
    3542 if (niyuan(1024, aany) != 0 && niyuan(1024, ddny) != 0) {
    3543 int kn00 = r00 * niyuan(1024, x00);
    3544 int kn01 = r01 * niyuan(1024, x00);
    3545 int kn10 = r10 * niyuan(1024, x11);
    3546 int kn11 = r11 * niyuan(1024, x11);
    3547 ka = kn00;
    3548 kb = kn01;
    3549 kc = kn10;
    3550 kd = kn11;
    3551 } else {
    3552 JOptionPane.showMessageDialog(null, "无逆矩阵!");
    3553 System.exit(0);
    3554 }
    3555 while (ka < 0)
    3556 ka += 1024;
    3557 while (kb < 0)
    3558 kb += 1024;
    3559 while (kc < 0)
    3560 kc += 1024;
    3561 while (kd < 0)
    3562 kd += 1024;
    3563 ka %= 1024;
    3564 kb %= 1024;
    3565 kc %= 1024;
    3566 kd %= 1024;
    3567 try {
    3568 int byteread;
    3569 while ((byteread = fis.read(buffer)) != -1) {
    3570 int nLen = byteread / 2;
    3571 byte[] sming = new byte[nLen];
    3572 String chs = new String(buffer, "US-ASCII");
    3573 for (int i = 0; i < nLen; i++) {
    3574 byte bTmp;
    3575 if (byteread < 2)
    3576 bTmp = -1;
    3577 bTmp = (byte) (CharSet.indexOf(chs
    3578 .substring(i * 2, i * 2 + 1)) * 16 + CharSet
    3579 .indexOf(chs.substring(i * 2 + 1,
    3580 i * 2 + 2)));
    3581 sming[i] = bTmp;
    3582 }
    3583 if (nLen % 2 != 0)
    3584 js = 1;
    3585 for (int i = 0; i < nLen - 1; i += 2) {
    3586 char c1 = (char) sming[i];
    3587 char c2 = (char) sming[i + 1];
    3588 tmp = ka * c1 + kc * c2;
    3589 while (tmp < 0)
    3590 tmp += 1024;
    3591 char s1 = (char) (tmp % 1024);
    3592 fw.write(s1);
    3593 tmp = kb * c1 + kd * c2;
    3594 while (tmp < 0)
    3595 tmp += 1024;
    3596 char s2 = (char) (tmp % 1024);
    3597 fw.write(s2);
    3598 }
    3599 if (js == 1) {
    3600 char c3 = (char) ((sming[nLen - 1] - 4) % 1024);
    3601 fw.write(c3);
    3602 }
    3603 }
    3604 fw.flush();
    3605 } catch (IOException e) {
    3606 e.printStackTrace();
    3607 } finally {
    3608 try {
    3609 fis.close();
    3610 fw.close();
    3611 } catch (IOException e) {
    3612 e.printStackTrace();
    3613 }
    3614 }
    3615 } catch (FileNotFoundException e1) {
    3616 e1.printStackTrace();
    3617 }
    3618 if(!chooser2.getFileFilter().accept(chooser2.getSelectedFile())){
    3619 if(chooser2.getFileFilter().getDescription().equals("Compress Files(*.zip)"))
    3620 chooser2.getSelectedFile().renameTo(new File(chooser2.getSelectedFile().getAbsolutePath()+".zip"));
    3621 else if(chooser2.getFileFilter().getDescription().equals("Executeable Files(*.exe)"))
    3622 chooser2.getSelectedFile().renameTo(new File(chooser2.getSelectedFile().getAbsolutePath()+".exe"));
    3623 }
    3624 
    3625 }
    3626 } else {
    3627 chooser2
    3628 .setFileFilter(new javax.swing.filechooser.FileFilter() {
    3629 public boolean accept(File f) {
    3630 return f.getName().toLowerCase().endsWith(
    3631 ".txt")
    3632 || f.isDirectory();
    3633 }
    3634 
    3635 public String getDescription() {
    3636 return "Text Files";
    3637 }
    3638 });
    3639 if (chooser2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    3640 
    3641 if (chooser2.getSelectedFile() != null) {
    3642 init();
    3643 File oldfile = chooser.getSelectedFile();
    3644 FileInputStream inStream = null;
    3645 FileWriter fw = null;
    3646 try {
    3647 if (oldfile.exists()) {
    3648 inStream = new FileInputStream(oldfile);
    3649 fw = new FileWriter(chooser2.getSelectedFile());
    3650 byte[] sRead = new byte[10240];
    3651 int byteread;
    3652 while ((byteread = inStream.read(sRead)) != -1) {
    3653 StringBuilder smi = new StringBuilder(
    3654 byteread * 2);
    3655 int js = 0;
    3656 if (byteread % 2 != 0)
    3657 js = 1;
    3658 for (int i = 0; i < byteread - 1; i += 2) {
    3659 char c1 = (char) sRead[i];
    3660 char c2 = (char) sRead[i + 1];
    3661 int tmp = ka * c1 + kc * c2;
    3662 while (tmp < 0)
    3663 tmp += 1024;
    3664 byte s1 = (byte) (tmp % 1024);
    3665 int js1 = (int) s1 >> 4 & 0xf;
    3666 smi.append(CharSet.substring(js1,
    3667 js1 + 1));
    3668 int ks1 = s1 & 0xf;
    3669 smi.append(CharSet.substring(ks1,
    3670 ks1 + 1));
    3671 tmp = kb * c1 + kd * c2;
    3672 while (tmp < 0)
    3673 tmp += 1024;
    3674 byte s2 = (byte) (tmp % 1024);
    3675 int js2 = (int) s2 >> 4 & 0xf;
    3676 smi.append(CharSet.substring(js2,
    3677 js2 + 1));
    3678 int ks2 = s2 & 0xf;
    3679 smi.append(CharSet.substring(ks2,
    3680 ks2 + 1));
    3681 }
    3682 if (js == 1) {
    3683 byte s3 = (byte) ((sRead[byteread - 1] - 4) % 1024);
    3684 int js3 = (int) s3 >> 4 & 0xf;
    3685 smi.append(CharSet.substring(js3,
    3686 js3 + 1));
    3687 int ks3 = (int) s3 & 0xf;
    3688 smi.append(CharSet.substring(ks3,
    3689 ks3 + 1));
    3690 }
    3691 fw.write(smi.toString());
    3692 }
    3693 fw.flush();
    3694 }
    3695 } catch (IOException e) {
    3696 e.printStackTrace();
    3697 } finally {
    3698 try {
    3699 fw.close();
    3700 inStream.close();
    3701 } catch (IOException e) {
    3702 e.printStackTrace();
    3703 }
    3704 }
    3705 if(!chooser2.getFileFilter().accept(chooser2.getSelectedFile()))
    3706 chooser2.getSelectedFile().renameTo(new File(chooser2.getSelectedFile().getAbsolutePath()+".txt"));
    3707 }
    3708 }
    3709 }
    3710 }
    3711 
    3712 87.菜单勾选/取消开机自启动程序
    3713 
    3714 88.菜单勾选/取消自动登录系统
    3715 
    3716 89.模拟键盘输入字符串
    3717 /*
    3718 import java.awt.*;
    3719 import java.awt.event.*;
    3720 throws Exception{
    3721 */
    3722 static Robot robot;
    3723 static{
    3724 try {
    3725 robot = new Robot();
    3726 } catch (AWTException e) {}
    3727 }
    3728 
    3729 static void sendKey(String ks){
    3730 KeyStore k = KeyStore.findKeyStore(ks);
    3731 if(k!=null){
    3732 if(k.upCase)
    3733 upCase(k.v);
    3734 else
    3735 sendKey(k.v);
    3736 }
    3737 else{
    3738 for(int i=0; i<ks.length(); i++){
    3739 char c = ks.charAt(i);
    3740 if(c>='0'&&c<='9'){
    3741 sendKey(c);
    3742 }
    3743 else if(c>='a'&&c<='z'){
    3744 sendKey(c-32);
    3745 }
    3746 else if(c>='A'&&c<='Z'){
    3747 upCase(c);
    3748 }
    3749 }
    3750 }
    3751 }
    3752 private static void upCase(int kc){
    3753 robot.keyPress(KeyEvent.VK_SHIFT);
    3754 robot.keyPress(kc);
    3755 robot.keyRelease(kc);
    3756 robot.keyRelease(KeyEvent.VK_SHIFT);
    3757 }
    3758 private static void sendKey(int kc){
    3759 robot.keyPress(kc);
    3760 robot.keyRelease(kc);
    3761 }
    3762 static class KeyStore{
    3763 //special keys
    3764 final static KeyStore[] sp = {
    3765 new KeyStore("{Tab}",KeyEvent.VK_TAB),//tab
    3766 new KeyStore("{Enter}",KeyEvent.VK_ENTER),//enter
    3767 new KeyStore("{PUp}",KeyEvent.VK_PAGE_UP),//page up
    3768 new KeyStore("{<}",KeyEvent.VK_LESS),//<
    3769 new KeyStore("{Up}",KeyEvent.VK_UP),//up key
    3770 new KeyStore("{At}",KeyEvent.VK_AT,true),//@
    3771 new KeyStore("{Dollar}",KeyEvent.VK_DOLLAR,true),//$
    3772 };
    3773 
    3774 String k;
    3775 int v;
    3776 boolean upCase;
    3777 KeyStore(String k,int v){
    3778 this(k,v,false);
    3779 }
    3780 
    3781 KeyStore(String s,int i,boolean up){
    3782 k=s;
    3783 v=i;
    3784 upCase=up;
    3785 }
    3786 static KeyStore findKeyStore(String k){
    3787 for(int i=0; i<sp.length; i++){
    3788 if(sp[i].k.equals(k))
    3789 return sp[i];
    3790 }
    3791 return null;
    3792 }
    3793 }
    3794 Thread.sleep(1000);
    3795 sendKey("{Tab}");//tab
    3796 sendKey("{<}");//<
    3797 sendKey("abcd123AHahahAA");//abcd123AHahahAA
    3798 sendKey("{At}");//@
    3799 sendKey("{Dollar}");//$
    3800 sendKey("{Up}");//up arrow
    3801 
    3802 90.提取PDF文件中的文本
    3803 //http://incubator.apache.org/pdfbox/
    3804 /*
    3805 import java.io.*;
    3806 import org.pdfbox.pdfparser.*;
    3807 import org.pdfbox.pdmodel.*;
    3808 import org.pdfbox.util.*;
    3809 */
    3810 public class SimplePDFReader {
    3811 /**
    3812 * simply reader all the text from a pdf file.
    3813 * You have to deal with the format of the output text by yourself.
    3814 * 2008-2-25
    3815 * @param pdfFilePath file path
    3816 * @return all text in the pdf file
    3817 */
    3818 public static String getTextFromPDF(String pdfFilePath) {
    3819 String result = null;
    3820 FileInputStream is = null;
    3821 PDDocument document = null;
    3822 try {
    3823 is = new FileInputStream(pdfFilePath);
    3824 PDFParser parser = new PDFParser(is);
    3825 parser.parse();
    3826 document = parser.getPDDocument();
    3827 PDFTextStripper stripper = new PDFTextStripper();
    3828 result = stripper.getText(document);
    3829 } catch (FileNotFoundException e) {
    3830 // TODO Auto-generated catch block
    3831 e.printStackTrace();
    3832 } catch (IOException e) {
    3833 // TODO Auto-generated catch block
    3834 e.printStackTrace();
    3835 } finally {
    3836 if (is != null) {
    3837 try {
    3838 is.close();
    3839 } catch (IOException e) {
    3840 // TODO Auto-generated catch block
    3841 e.printStackTrace();
    3842 }
    3843 }
    3844 if (document != null) {
    3845 try {
    3846 document.close();
    3847 } catch (IOException e) {
    3848 // TODO Auto-generated catch block
    3849 e.printStackTrace();
    3850 }
    3851 }
    3852 }
    3853 return result;
    3854 }
    3855 }
    3856 得到PDF的文本内容之后,自己根据文件的格式,取得想要的文本(这里我找的就是文章的标题,在文本中恰巧都是文件的第一行的内容),然后通过java的File相关api,对文件进行更名操作。
    3857 import java.io.File;
    3858 import java.io.FilenameFilter;
    3859 
    3860 public class PaperNameMender {
    3861 public static void changePaperName(String filePath) {
    3862 //使用SimplePDFReader得到pdf文本
    3863 String ts = SimplePDFReader.getTextFromPDF(filePath);
    3864 //取得一行内容
    3865 String result = ts.substring(0, ts.indexOf('
    '));
    3866 //得到源文件名中的最后一个逗点.的位置
    3867 int index = filePath.indexOf('.');
    3868 int nextIndex = filePath.indexOf('.', index + 1);
    3869 while(nextIndex != -1) {
    3870 index = nextIndex;
    3871 nextIndex = filePath.indexOf('.', index + 1);
    3872 }
    3873 //合成新文件名
    3874 String newFilename = filePath.substring(0, index) + " " +
    3875 result.trim() + ".pdf";
    3876 File originalFile = new File(filePath);
    3877 //修改文件名
    3878 originalFile.renameTo(new File(newFilename));
    3879 }
    3880 }
    3881 
    3882 
    3883 91.操作内存映射文件
    3884 /*
    3885 import java.io.*;
    3886 import java.nio.*;
    3887 import java.nio.channels.*;
    3888 */
    3889 private static int length = 0x8FFFFFF; // 128 Mb
    3890 MappedByteBuffer out =
    3891 new RandomAccessFile("test.dat", "rw").getChannel()
    3892 .map(FileChannel.MapMode.READ_WRITE, 0, length);
    3893 for(int i = 0; i < length; i++)
    3894 out.put((byte)'x');
    3895 for(int i = length/2; i < length/2 + 6; i++)
    3896 //(char)out.get(i);
    3897 
    3898 92.重定向windows控制台程序的输出信息
    3899 92.1 取得Runtime.getRuntime().exec("cmd /c dir")的输入输出
    3900 //import java.io.*;
    3901 try {
    3902 String command = "cmd /c dir";
    3903 Process proc = Runtime.getRuntime().exec(command);
    3904 InputStreamReader ir = new InputStreamReader(proc.getInputStream());
    3905 LineNumberReader lnr = new LineNumberReader(ir);
    3906 String line;
    3907 while( (line = lnr.readLine()) != null)
    3908 {
    3909 //line
    3910 }
    3911 } catch (IOException e) {
    3912 e.printStackTrace();
    3913 }
    3914 
    3915 92.2 利用ProcessBuilder来创建Process对象,执行外部可执行程序
    3916 // //Eg1:
    3917 // String address = null;
    3918 //
    3919 // String os = System.getProperty("os.name");
    3920 // System.out.println(os);
    3921 //
    3922 // if (os != null) {
    3923 // if (os.startsWith("Windows")) {
    3924 // try {
    3925 // ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
    3926 // Process p = pb.start();
    3927 //
    3928 // BufferedReader br = new BufferedReader(
    3929 // new InputStreamReader(p.getInputStream()));
    3930 //
    3931 // String line;
    3932 // while ((line = br.readLine()) != null) {
    3933 // if (line.indexOf("Physical Address") != -1) {
    3934 // int index = line.indexOf(":");
    3935 // address = line.substring(index + 1);
    3936 // break;
    3937 // }
    3938 // }
    3939 // br.close();
    3940 // address = address.trim();
    3941 // } catch (IOException e) {
    3942 // // TODO Auto-generated catch block
    3943 // e.printStackTrace();
    3944 // }
    3945 // } else if (os.startsWith("Linux")) {
    3946 // try {
    3947 // ProcessBuilder pb = new ProcessBuilder(
    3948 //
    3949 // "ifconfig", "/all");
    3950 //
    3951 // Process p = pb.start();
    3952 // BufferedReader br = new BufferedReader(
    3953 // new InputStreamReader(p.getInputStream()));
    3954 // String line;
    3955 // while ((line = br.readLine()) != null) {
    3956 // int index = line.indexOf("硬件地址");
    3957 // if (index != -1) {
    3958 // address = line.substring(index + 4);
    3959 // break;
    3960 // }
    3961 // }
    3962 // br.close();
    3963 // address = address.trim();
    3964 // } catch (IOException e) {
    3965 // e.printStackTrace();
    3966 // }
    3967 // }
    3968 // }
    3969 
    3970 // //Eg2:
    3971 // try {
    3972 // Process proc;
    3973 // proc = Runtime.getRuntime().exec("cmd.exe");
    3974 // BufferedReader read = new BufferedReader(new InputStreamReader(proc
    3975 // .getInputStream()));
    3976 // new Thread(new Echo(read)).start();
    3977 //
    3978 // PrintWriter out = new PrintWriter(new OutputStreamWriter(proc
    3979 // .getOutputStream()));
    3980 // BufferedReader in = new BufferedReader(new InputStreamReader(
    3981 // System.in));
    3982 // String instr = in.readLine();
    3983 // while (!"exit".equals(instr)) {
    3984 // instr = in.readLine();
    3985 // out.println(instr);
    3986 // out.flush();
    3987 // }
    3988 //
    3989 // in.readLine();
    3990 // read.close();
    3991 // out.close();
    3992 // } catch (IOException e) {
    3993 // // TODO Auto-generated catch block
    3994 // e.printStackTrace();
    3995 // }
    3996 
    3997 }
    3998 }
    3999 
    4000 class Echo implements Runnable {
    4001 private BufferedReader read;
    4002 
    4003 public Echo(BufferedReader read) {
    4004 read = read;
    4005 }
    4006 
    4007 public void run() {
    4008 try {
    4009 String line = read.readLine();
    4010 while (line != null) {
    4011 //line
    4012 line = read.readLine();
    4013 }
    4014 } catch (IOException ex) {
    4015 ex.printStackTrace();
    4016 }
    4017 }
    4018 }
    4019 
    4020 93.序列化
    4021 //import java.io.*;
    4022 class tree implements Serializable{
    4023 public tree left;
    4024 public tree right;
    4025 public int id;
    4026 public int level;
    4027 
    4028 private static int count = 0 ;
    4029 
    4030 public tree( int depth) {
    4031 id = count ++ ;
    4032 level = depth;
    4033 if (depth > 0 ) {
    4034 left = new tree(depth - 1 );
    4035 right = new tree(depth - 1 );
    4036 }
    4037 }
    4038 
    4039 public void print( int levels) {
    4040 for ( int i = 0 ; i < level; i ++ )
    4041 System.out.print( " " );
    4042 System.out.println( " node " + id);
    4043 
    4044 if (level <= levels && left != null )
    4045 left.print(levels);
    4046 
    4047 if (level <= levels && right != null )
    4048 right.print(levels);
    4049 }
    4050 }
    4051 try {
    4052 /**/ /* 创建一个文件写入序列化树。 */
    4053 FileOutputStream ostream = new FileOutputStream(%%1);
    4054 /**/ /* 创建输出流 */
    4055 ObjectOutputStream p = new ObjectOutputStream(ostream);
    4056 
    4057 /**/ /* 创建一个二层的树。 */
    4058 tree base = new tree( 2 );
    4059 
    4060 p.writeObject(base); // 将树写入流中。
    4061 p.writeObject( " LiLy is 惠止南国 " );
    4062 p.flush();
    4063 ostream.close(); // 关闭文件。
    4064 } catch (Exception ex) {
    4065 ex.printStackTrace();
    4066 }
    4067 }
    4068 
    4069 94.反序列化
    4070 //import java.io.*;
    4071 class tree implements Serializable{
    4072 public tree left;
    4073 public tree right;
    4074 public int id;
    4075 public int level;
    4076 
    4077 private static int count = 0 ;
    4078 
    4079 public tree( int depth) {
    4080 id = count ++ ;
    4081 level = depth;
    4082 if (depth > 0 ) {
    4083 left = new tree(depth - 1 );
    4084 right = new tree(depth - 1 );
    4085 }
    4086 }
    4087 
    4088 public void print( int levels) {
    4089 for ( int i = 0 ; i < level; i ++ )
    4090 System.out.print( " " );
    4091 System.out.println( " node " + id);
    4092 
    4093 if (level <= levels && left != null )
    4094 left.print(levels);
    4095 
    4096 if (level <= levels && right != null )
    4097 right.print(levels);
    4098 }
    4099 }
    4100 try {
    4101 FileInputStream istream = new FileInputStream(%%1);
    4102 ObjectInputStream q = new ObjectInputStream(istream);
    4103 
    4104 /**/ /* 读取树对象,以及所有子树 */
    4105 tree new_tree = (tree)q.readObject();
    4106 
    4107 new_tree.print( 2 ); // 打印出树形结构的最上面 2级
    4108 String name = (String)q.readObject();
    4109 System.out.println( " 
     " + name);
    4110 } catch (Exception ex) {
    4111 ex.printStackTrace();
    4112 }
    4113 }
    4114 
    4115 95.报表相关
    4116 //http://www.jfree.org/jfreechart/
    4117 /*
    4118 import java.io.*;
    4119 import java.awt.*;
    4120 import org.jfree.chart.*;
    4121 import org.jfree.chart.title.TextTitle;
    4122 import org.jfree.data.general.*;
    4123 */
    4124 String title = "梦泽科技员工学历情况统计";
    4125 DefaultPieDataset piedata = new DefaultPieDataset();
    4126 piedata.setValue("大专", 8.1);
    4127 piedata.setValue("大学", 27.6);
    4128 piedata.setValue("硕士", 53.2);
    4129 piedata.setValue("博士及以上", 19.2);
    4130 piedata.setValue("大专以下", 1.9);
    4131 JFreeChart chart = ChartFactory.createPieChart(title, piedata, true, true, true);
    4132 chart.setTitle(new TextTitle(title, new Font("宋体", Font.BOLD, 25)));
    4133 chart.addSubtitle(new TextTitle("最后更新日期:2005年5月19日", new Font("楷书", Font.ITALIC, 18)));
    4134 chart.setBackgroundPaint(Color.white);
    4135 try {
    4136 ChartUtilities.saveChartAsJPEG(new File("PieChart.jpg"), chart, 360, 300);
    4137 } catch (IOException exz) {
    4138 System.err.print("....Cant′t Create image File");
    4139 }
    4140 
    4141 96.全屏幕截取
    4142 /*
    4143 import java.awt.*;
    4144 import java.awt.image.*;
    4145 import java.io.*;
    4146 import javax.imageio.*;
    4147 */
    4148 try{
    4149 Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    4150 BufferedImage screenshot = (new Robot())
    4151 .createScreenCapture(new Rectangle(0, 0,
    4152 (int) d.getWidth(), (int) d.getHeight()));
    4153 // 根据文件前缀变量和文件格式变量,自动生成文件名
    4154 String name = %%1 + "."
    4155 + %%2; //"png"
    4156 File f = new File(name);
    4157 ImageIO.write(screenshot, %%2, f);
    4158 } catch (Exception ex) {
    4159 ex.printStackTrace();
    4160 }
    4161 
    4162 97.区域截屏
    4163 /*
    4164 import java.awt.*;
    4165 import java.awt.image.*;
    4166 import java.io.*;
    4167 import java.util.*;
    4168 import javax.imageio.*;
    4169 */
    4170 interface ImageType {
    4171 public final static String JPG = "JPG";
    4172 public final static String PNG = "PNG";
    4173 public final static String GIF = "GIF";
    4174 }
    4175 public class ScreenDumpHelper {
    4176 /** ScreenDumpHelper 静态对象 */
    4177 private static ScreenDumpHelper defaultScreenDumpHelper;
    4178 public static ScreenDumpHelper getDefaultScreenDumpHelper() {
    4179 if (defaultScreenDumpHelper == null)
    4180 return new ScreenDumpHelper();
    4181 return defaultScreenDumpHelper;
    4182 }
    4183 public ScreenDumpHelper() {
    4184 Dimension dime = Toolkit.getDefaultToolkit().getScreenSize();
    4185 setScreenArea(new Rectangle(dime));
    4186 }
    4187 private Rectangle screenArea;
    4188 
    4189 public Rectangle getScreenArea() {
    4190 return screenArea;
    4191 }
    4192 
    4193 public void setScreenArea(Rectangle screenArea) {
    4194 screenArea = screenArea;
    4195 }
    4196 
    4197 public void setScreenArea(int x, int y, int width, int height) {
    4198 screenArea = new Rectangle(x, y, width, height);
    4199 }
    4200 private BufferedImage getBufferedImage() throws AWTException {
    4201 BufferedImage imgBuf = null;
    4202 ;
    4203 imgBuf = (new Robot()).createScreenCapture(getScreenArea());
    4204 return imgBuf;
    4205 }
    4206 
    4207 /**
    4208 * 将 图像数据写到 输出流中去,方便再处理
    4209 *
    4210 * @param fileFormat
    4211 * @param output
    4212 * @return
    4213 */
    4214 public boolean saveToOutputStream(String fileFormat, OutputStream output) {
    4215 try {
    4216 ImageIO.write(getBufferedImage(), fileFormat, output);
    4217 } catch (AWTException e) {
    4218 return false;
    4219 // e.printStackTrace();
    4220 } catch (IOException e) {
    4221 return false;
    4222 // e.printStackTrace();
    4223 }
    4224 return true;
    4225 }
    4226 
    4227 /**
    4228 * 根据文件格式 返回随机文件名称
    4229 *
    4230 * @param fileFormat
    4231 * @return
    4232 */
    4233 public String getRandomFileName(String fileFormat) {
    4234 return "screenDump_" + (new Date()).getTime() + "." + fileFormat;
    4235 }
    4236 
    4237 /**
    4238 * 抓取 指定区域的截图 到指定格式的文件中 -- 这个函数是核心,所有的都是围绕它来展开的 * 图片的编码并不是以后缀名来判断: 比如s.jpg
    4239 * 如果其采用png编码,那么这个图片就是png格式的
    4240 *
    4241 * @param fileName
    4242 * @param fileFormat
    4243 * @return boolean
    4244 */
    4245 public boolean saveToFile(String fileName, String fileFormat) {
    4246 if (fileName == null)
    4247 fileName = getRandomFileName(fileFormat);
    4248 try {
    4249 FileOutputStream fos = new FileOutputStream(fileName);
    4250 saveToOutputStream(fileFormat, fos);
    4251 } catch (FileNotFoundException e) {
    4252 System.err.println("非常规文件或不能创建抑或覆盖此文件: " + fileName);
    4253 }
    4254 return true;
    4255 }
    4256 
    4257 /**
    4258 * 抓取 指定 Rectangle 区域的截图 到指定格式的文件中
    4259 *
    4260 * @param fileName
    4261 * @param fileFormat
    4262 * @param screenArea
    4263 * @return
    4264 */
    4265 public boolean saveToFile(String fileName, String fileFormat,
    4266 Rectangle screenArea) {
    4267 setScreenArea(screenArea);
    4268 return saveToFile(fileName, fileFormat);
    4269 }
    4270 
    4271 /**
    4272 * 抓取 指定区域的截图 到指定格式的文件中
    4273 *
    4274 * @param fileName
    4275 * @param fileFormat
    4276 * @param x
    4277 * @param y
    4278 * @param width
    4279 * @param height
    4280 */
    4281 public boolean saveToFile(String fileName, String fileFormat, int x, int y,
    4282 int width, int height) {
    4283 setScreenArea(x, y, width, height);
    4284 return saveToFile(fileName, fileFormat);
    4285 }
    4286 
    4287 /**
    4288 * 将截图使用 JPG 编码
    4289 *
    4290 * @param fileName
    4291 */
    4292 public void saveToJPG(String fileName) {
    4293 saveToFile(fileName, ImageType.JPG);
    4294 }
    4295 
    4296 public void saveToJPG(String fileName, Rectangle screenArea) {
    4297 saveToFile(fileName, ImageType.JPG, screenArea);
    4298 }
    4299 
    4300 public void saveToJPG(String fileName, int x, int y, int width, int height) {
    4301 saveToFile(fileName, ImageType.JPG, x, y, width, height);
    4302 }
    4303 
    4304 /**
    4305 * 将截图使用 PNG 编码
    4306 *
    4307 * @param fileName
    4308 */
    4309 public void saveToPNG(String fileName) {
    4310 saveToFile(fileName, ImageType.PNG);
    4311 }
    4312 
    4313 public void saveToPNG(String fileName, Rectangle screenArea) {
    4314 saveToFile(fileName, ImageType.PNG, screenArea);
    4315 }
    4316 
    4317 public void saveToPNG(String fileName, int x, int y, int width, int height) {
    4318 saveToFile(fileName, ImageType.PNG, x, y, width, height);
    4319 }
    4320 
    4321 public void saveToGIF(String fileName) {
    4322 throw new UnsupportedOperationException("不支持保存到GIF文件");
    4323 // saveToFile(fileName, ImageType.GIF);
    4324 }
    4325 
    4326 /**
    4327 * @param args
    4328 */
    4329 public static void main(String[] args) {
    4330 for (int i = 0; i < 5; i++)
    4331 ScreenDumpHelper.getDefaultScreenDumpHelper().saveToJPG(null,
    4332 i * 150, i * 150, 400, 300);
    4333 }
    4334 }
    4335 
    4336 98.计算文件MD5值
    4337 /*
    4338 import java.io.*;
    4339 import java.math.*;
    4340 import java.security.*;
    4341 import java.util.*;
    4342 */
    4343 File file=new File(%%1);
    4344 if (!file.isFile()){
    4345 return null;
    4346 }
    4347 MessageDigest digest = null;
    4348 FileInputStream in=null;
    4349 byte buffer[] = new byte[1024];
    4350 int len;
    4351 try {
    4352 digest = MessageDigest.getInstance("MD5");
    4353 in = new FileInputStream(file);
    4354 while ((len = in.read(buffer, 0, 1024)) != -1) {
    4355 digest.update(buffer, 0, len);
    4356 }
    4357 in.close();
    4358 } catch (Exception e) {
    4359 e.printStackTrace();
    4360 return null;
    4361 }
    4362 BigInteger bigInt = new BigInteger(1, digest.digest());
    4363 return bigInt.toString(16);
    4364 }
    4365 
    4366 99.计算获取文件夹中文件的MD5值
    4367 /*
    4368 import java.io.*;
    4369 import java.math.*;
    4370 import java.security.*;
    4371 import java.util.*;
    4372 */
    4373 public static String getFileMD5(File file) {
    4374 if (!file.isFile()){
    4375 return null;
    4376 }
    4377 MessageDigest digest = null;
    4378 FileInputStream in=null;
    4379 byte buffer[] = new byte[1024];
    4380 int len;
    4381 try {
    4382 digest = MessageDigest.getInstance("MD5");
    4383 in = new FileInputStream(file);
    4384 while ((len = in.read(buffer, 0, 1024)) != -1) {
    4385 digest.update(buffer, 0, len);
    4386 }
    4387 in.close();
    4388 } catch (Exception e) {
    4389 e.printStackTrace();
    4390 return null;
    4391 }
    4392 BigInteger bigInt = new BigInteger(1, digest.digest());
    4393 return bigInt.toString(16);
    4394 }
    4395 /**
    4396 * 获取文件夹中文件的MD5值
    4397 * @param file
    4398 * @param listChild ;true递归子目录中的文件
    4399 * @return
    4400 */
    4401 public static Map<String, String> getDirMD5(File file,boolean listChild) {
    4402 if(!file.isDirectory()){
    4403 return null;
    4404 }
    4405 //<filepath,md5>
    4406 Map<String, String> map=new HashMap<String, String>();
    4407 String md5;
    4408 File files[]=file.listFiles();
    4409 for(int i=0;i<files.length;i++){
    4410 File f=files[i];
    4411 if(f.isDirectory()&&listChild){
    4412 map.putAll(getDirMD5(f, listChild));
    4413 } else {
    4414 md5=getFileMD5(f);
    4415 if(md5!=null){
    4416 map.put(f.getPath(), md5);
    4417 }
    4418 }
    4419 }
    4420 return map;
    4421 }
    4422 getDirMD5(%%1,%%2);
    4423 
    4424 100.复制一个目录下所有文件到一个文件夹中
    4425 /*
    4426 import java.io.*;
    4427 import java.util.*;
    4428 */
    4429 LinkedList<String> folderList = new LinkedList<String>();
    4430 folderList.add(%%1);
    4431 LinkedList<String> folderList2 = new LinkedList<String>();
    4432 folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\")));
    4433 while (folderList.size() > 0) {
    4434 File folders = new File(folderList.peek());
    4435 String[] file = folders.list();
    4436 File temp = null;
    4437 try {
    4438 for (int i = 0; i < file.length; i++) {
    4439 if (folderList.peek().endsWith(File.separator)) {
    4440 temp = new File(folderList.peek() + File.separator
    4441 + file[i]);
    4442 } else {
    4443 temp = new File(folderList.peek() + File.separator
    4444 + file[i]);
    4445 }
    4446 if (temp.isFile()) {
    4447 FileInputStream input = new FileInputStream(temp);
    4448 FileOutputStream output = new FileOutputStream(
    4449 new File(%%2,temp.getName()));
    4450 byte[] b = new byte[10240];
    4451 int len;
    4452 while ((len = input.read(b)) != -1) {
    4453 output.write(b, 0, len);
    4454 }
    4455 output.flush();
    4456 output.close();
    4457 input.close();
    4458 }
    4459 if (temp.isDirectory()) {// 如果是子文件夹
    4460 for (File f : temp.listFiles()) {
    4461 if (f.isDirectory()) {
    4462 folderList.add(f.getPath());
    4463 folderList2.add(folderList2.peek()
    4464 + File.separator + f.getName());
    4465 }
    4466 }
    4467 }
    4468 }
    4469 } catch (IOException e) {
    4470 System.err.println("复制整个文件夹内容操作出错");
    4471 }
    4472 folderList.removeFirst();
    4473 folderList2.removeFirst();
    4474 }
    4475 
    4476 101.移动一个目录下所有文件到一个文件夹中
    4477 /*
    4478 import java.io.*;
    4479 import java.util.*;
    4480 */
    4481 LinkedList<String> folderList = new LinkedList<String>();
    4482 folderList.add(%%1);
    4483 LinkedList<String> folderList2 = new LinkedList<String>();
    4484 folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\")));
    4485 while (folderList.size() > 0) {
    4486 File folders = new File(folderList.peek());
    4487 String[] file = folders.list();
    4488 File temp = null;
    4489 try {
    4490 for (int i = 0; i < file.length; i++) {
    4491 if (folderList.peek().endsWith(File.separator)) {
    4492 temp = new File(folderList.peek() + File.separator
    4493 + file[i]);
    4494 } else {
    4495 temp = new File(folderList.peek() + File.separator
    4496 + file[i]);
    4497 }
    4498 if (temp.isFile()) {
    4499 FileInputStream input = new FileInputStream(temp);
    4500 FileOutputStream output = new FileOutputStream(
    4501 new File(%%2,temp.getName()));
    4502 byte[] b = new byte[10240];
    4503 int len;
    4504 while ((len = input.read(b)) != -1) {
    4505 output.write(b, 0, len);
    4506 }
    4507 output.flush();
    4508 output.close();
    4509 input.close();
    4510 if (!temp.delete())
    4511 //删除单个文件操作出错
    4512 }
    4513 if (temp.isDirectory()) {// 如果是子文件夹
    4514 for (File f : temp.listFiles()) {
    4515 if (f.isDirectory()) {
    4516 folderList.add(f.getPath());
    4517 folderList2.add(folderList2.peek()
    4518 + File.separator + f.getName());
    4519 }
    4520 }
    4521 }
    4522 }
    4523 } catch (Exception e) {
    4524 //复制整个文件夹内容操作出错
    4525 e.printStackTrace();
    4526 }
    4527 folderList.removeFirst();
    4528 folderList2.removeFirst();
    4529 }
    4530 File f = new File(%%1);
    4531 if (!f.delete()) {
    4532 for (File file : f.listFiles()) {
    4533 if (file.list().length == 0) {
    4534 file.delete();
    4535 }
    4536 }
    4537 }
    4538 
    4539 102.文件RSA高级加密
    4540 /*
    4541 import javax.crypto.*;
    4542 import java.security.*;
    4543 import java.security.spec.*;
    4544 import java.security.interfaces.*;
    4545 import java.io.*;
    4546 import java.math.BigInteger;
    4547 */
    4548 /**
    4549 
    4550 * 生成密钥对
    4551 
    4552 * @return KeyPair
    4553 
    4554 * @throws EncryptException
    4555 
    4556 */
    4557 
    4558 public static KeyPair generateKeyPair() throws EncryptException {
    4559 
    4560 try {
    4561 
    4562 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
    4563 
    4564 new org.bouncycastle.jce.provider.BouncyCastleProvider());
    4565 
    4566 final int KEY_SIZE = 1024;//没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
    4567 
    4568 keyPairGen.initialize(KEY_SIZE, new SecureRandom());
    4569 
    4570 KeyPair keyPair = keyPairGen.genKeyPair();
    4571 
    4572 return keyPair;
    4573 
    4574 } catch (Exception e) {
    4575 
    4576 throw new EncryptException(e.getMessage());
    4577 
    4578 }
    4579 
    4580 }
    4581 
    4582 /**
    4583 
    4584 * 生成公钥
    4585 
    4586 * @param modulus
    4587 
    4588 * @param publicExponent
    4589 
    4590 * @return RSAPublicKey
    4591 
    4592 * @throws EncryptException
    4593 
    4594 */
    4595 
    4596 public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws EncryptException {
    4597 
    4598 KeyFactory keyFac = null;
    4599 
    4600 try {
    4601 
    4602 keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    4603 
    4604 } catch (NoSuchAlgorithmException ex) {
    4605 
    4606 throw new EncryptException(ex.getMessage());
    4607 
    4608 }
    4609 
    4610 RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
    4611 
    4612 try {
    4613 
    4614 return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
    4615 
    4616 } catch (InvalidKeySpecException ex) {
    4617 
    4618 throw new EncryptException(ex.getMessage());
    4619 
    4620 }
    4621 
    4622 }
    4623 /**
    4624 
    4625 * 生成私钥
    4626 
    4627 * @param modulus
    4628 
    4629 * @param privateExponent
    4630 
    4631 * @return RSAPrivateKey
    4632 
    4633 * @throws EncryptException
    4634 
    4635 */
    4636 
    4637 public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws EncryptException {
    4638 
    4639 KeyFactory keyFac = null;
    4640 
    4641 try {
    4642 
    4643 keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    4644 
    4645 } catch (NoSuchAlgorithmException ex) {
    4646 
    4647 throw new EncryptException(ex.getMessage());
    4648 
    4649 }
    4650 
    4651 RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
    4652 
    4653 try {
    4654 
    4655 return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
    4656 
    4657 } catch (InvalidKeySpecException ex) {
    4658 
    4659 throw new EncryptException(ex.getMessage());
    4660 
    4661 }
    4662 
    4663 }
    4664 
    4665 /**
    4666 
    4667 * 加密
    4668 
    4669 * @param key 加密的密钥
    4670 
    4671 * @param data 待加密的明文数据
    4672 
    4673 * @return 加密后的数据
    4674 
    4675 * @throws EncryptException
    4676 
    4677 */
    4678 
    4679 public static byte[] encrypt(Key key, byte[] data) throws EncryptException {
    4680 
    4681 try {
    4682 
    4683 Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    4684 
    4685 cipher.init(Cipher.ENCRYPT_MODE, key);
    4686 
    4687 int blockSize = cipher.getBlockSize();//获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte;因此共有2个加密块,第一个127 byte第二个为1个byte
    4688 
    4689 int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小
    4690 
    4691 int leavedSize = data.length % blockSize;
    4692 
    4693 int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
    4694 
    4695 byte[] raw = new byte[outputSize * blocksSize];
    4696 
    4697 int i = 0;
    4698 
    4699 while (data.length - i * blockSize > 0) {
    4700 
    4701 if (data.length - i * blockSize > blockSize)
    4702 
    4703 cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
    4704 
    4705 else
    4706 
    4707 cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
    4708 //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。
    4709 
    4710 i++;
    4711 
    4712 }
    4713 
    4714 return raw;
    4715 
    4716 } catch (Exception e) {
    4717 
    4718 throw new EncryptException(e.getMessage());
    4719 
    4720 }
    4721 
    4722 }
    4723 
    4724 /**
    4725 
    4726 * 解密
    4727 
    4728 * @param key 解密的密钥
    4729 
    4730 * @param raw 已经加密的数据
    4731 
    4732 * @return 解密后的明文
    4733 
    4734 * @throws EncryptException
    4735 
    4736 */
    4737 
    4738 public static byte[] decrypt(Key key, byte[] raw) throws EncryptException {
    4739 
    4740 try {
    4741 
    4742 Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    4743 
    4744 cipher.init(cipher.DECRYPT_MODE, key);
    4745 
    4746 int blockSize = cipher.getBlockSize();
    4747 
    4748 ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
    4749 
    4750 int j = 0;
    4751 
    4752 while (raw.length - j * blockSize > 0) {
    4753 
    4754 bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
    4755 
    4756 j++;
    4757 
    4758 }
    4759 
    4760 return bout.toByteArray();
    4761 
    4762 } catch (Exception e) {
    4763 
    4764 throw new EncryptException(e.getMessage());
    4765 
    4766 }
    4767 
    4768 }
    4769 
    4770 
    4771 File file = new File("test.html");
    4772 
    4773 FileInputStream in = new FileInputStream(file);
    4774 
    4775 ByteArrayOutputStream bout = new ByteArrayOutputStream();
    4776 
    4777 byte[] tmpbuf = new byte[1024];
    4778 
    4779 int count = 0;
    4780 
    4781 while ((count = in.read(tmpbuf)) != -1) {
    4782 
    4783 bout.write(tmpbuf, 0, count);
    4784 
    4785 tmpbuf = new byte[1024];
    4786 
    4787 }
    4788 
    4789 in.close();
    4790 
    4791 byte[] orgData = bout.toByteArray();
    4792 
    4793 KeyPair keyPair = RSAUtil.generateKeyPair();
    4794 
    4795 RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
    4796 
    4797 RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
    4798 
    4799 byte[] pubModBytes = pubKey.getModulus().toByteArray();
    4800 
    4801 byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
    4802 
    4803 byte[] priModBytes = priKey.getModulus().toByteArray();
    4804 
    4805 byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
    4806 
    4807 RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
    4808 
    4809 RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);
    4810 
    4811 byte[] raw = RSAUtil.encrypt(priKey, orgData);
    4812 
    4813 file = new File("encrypt_result.dat");
    4814 
    4815 OutputStream out = new FileOutputStream(file);
    4816 
    4817 out.write(raw);
    4818 
    4819 out.close();
    4820 
    4821 byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
    4822 
    4823 file = new File("decrypt_result.html");
    4824 
    4825 out = new FileOutputStream(file);
    4826 
    4827 out.write(data);
    4828 
    4829 out.flush();
    4830 
    4831 out.close();
    4832 
    4833 103.计算文件大小
    4834 /*
    4835 import java.io.*;
    4836 private final long KB=1024;
    4837 private final long MB=1024*KB;
    4838 private final long GB=1024*MB;
    4839 */
    4840 //文件属性
    4841 File file=new File(%%1);
    4842 //如果文件存在而且是文件,直接返回文件大小
    4843 if(file.exists()&&file.isFile())
    4844 {
    4845 long filesize= file.length();
    4846 String showsize;
    4847 if(filesize>=GB)
    4848 showsize=filesize/GB+" GB";
    4849 else if(filesize>=MB)
    4850 showsize=filesize/MB+" MB";
    4851 else if(filesize>=KB)
    4852 showsize=filesize/KB+" KB";
    4853 else if(filesize>1)
    4854 showsize=filesize/GB+" Bytes";
    4855 else
    4856 showsize="1 Byte";
    4857 String %%2=showsize;
    4858 }
    4859 
    4860 104.计算文件夹的大小
    4861 /*
    4862 import java.io.*;
    4863 import java.math.*;
    4864 //bt字节参考量
    4865 private static final long SIZE_BT=1024L;
    4866 //KB字节参考量
    4867 private static final long SIZE_KB=SIZE_BT*1024L;
    4868 //MB字节参考量
    4869 private static final long SIZE_MB=SIZE_KB*1024L;
    4870 //GB字节参考量
    4871 private static final long SIZE_GB=SIZE_MB*1024L;
    4872 //TB字节参考量
    4873 private static final long SIZE_TB=SIZE_GB*1024L;
    4874 private static final int SACLE=2;
    4875 //文件大小属性
    4876 private static long longSize;
    4877 */
    4878 private void getFileSize(File file) {
    4879 // 获得文件目录下文件对象数组
    4880 File[] fileArray = file.listFiles();
    4881 // 如果文件目录数组不为空或者length!=0,即目录为空目录
    4882 if (fileArray != null && fileArray.length != 0) {
    4883 // 遍历文件对象数组
    4884 for (int i = 0; i < fileArray.length; i++) {
    4885 File fileSI = fileArray[i];
    4886 // 如果是目录递归遍历
    4887 if (fileSI.isDirectory()) {
    4888 // 递归遍历
    4889 getFileSize(fileSI);
    4890 }
    4891 // 如果是文件
    4892 if (fileSI.isFile()) {
    4893 longSize += fileSI.length();
    4894 }
    4895 }
    4896 } else {
    4897 // 如果文件目录数组为空或者length==0,即目录为空目录
    4898 longSize = 0;
    4899 }
    4900 }
    4901 // 文件存在而且是目录,递归遍历文件目录计算文件大小
    4902 File file = new File(folderPath);
    4903 if (file.exists() && file.isDirectory()) {
    4904 getFileSize(file);// 递归遍历
    4905 }
    4906 String %%2="0 Byte";
    4907 if (longSize == 1) {
    4908 %%2="1 Byte";
    4909 } else if (longSize >= 2 && longSize < SIZE_BT) {
    4910 %%2=longSize + " Bytes";
    4911 } else if (longSize >= SIZE_BT && longSize < SIZE_KB) {
    4912 %%2=longSize / SIZE_BT + " KB";
    4913 } else if (longSize >= SIZE_KB && longSize < SIZE_MB) {
    4914 %%2=longSize / SIZE_KB + " MB";
    4915 } else if (longSize >= SIZE_MB && longSize < SIZE_GB) {
    4916 BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")
    4917 .toString());
    4918 BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "")
    4919 .toString());
    4920 String result = longs.divide(sizeMB, SACLE,
    4921 BigDecimal.ROUND_HALF_UP).toString();
    4922 // double result=longSize/(double)SIZE_MB;
    4923 %%2=result + " GB";
    4924 } else {
    4925 BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")
    4926 .toString());
    4927 BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "")
    4928 .toString());
    4929 String result = longs.divide(sizeMB, SACLE,
    4930 BigDecimal.ROUND_HALF_UP).toString();
    4931 %%2=result + " TB";
    4932 }
    4933 
    4934 105.快速获得当前程序的驱动器、路径、文件名和扩展名
    4935 String %%2=%%1.substring(0,%%1.lastIndexOf(":"));
    4936 String %%5=%%1.substring(0,%%1.lastIndexOf("\"));
    4937 String %%4=%%1.substring(%%1.lastIndexOf("\")+1);
    4938 String %%3=%%1.substring(%%1.lastIndexOf('.'));
    4939 
    4940 106.磁盘剩余空间计算
    4941 //import java.io.*;
    4942 File file = new File(%%1); //"C:"
    4943 long %%2 = file.getFreeSpace(); //file.getTotalSpace()
    4944 
    4945 107.获取当前程序进程ID
    4946 java是在jvm上跑的,jvm本身作为系统的一个进程在跑,
    4947 所以平时见到的都是java多线程,没有进程间通信,
    4948 为什么呢,就是因为java中没有进程这一说法,
    4949 除非指的是程序本身这个进程。这个进程的话需要用到系统命令或者底层c语言才能够得到。呃,本人jni不是太熟悉,可以参考
    4950 http://hi.baidu.com/lff0305/blog/item/4f301a7b20d3d3f20bd187e3.html,
    4951 linux下直接调用ps-ef再用管道提取吧。
    4952 
    4953 108.全盘搜索文件
    4954 import java.io.*;
    4955 //ArrayList fileNames=new ArrayList();
    4956 void listDirectory(String dir)
    4957 {
    4958 File f=new File(dir);
    4959 File[] files=f.listFiles();
    4960 if(files==null)
    4961 return;
    4962 for(int i=0;i<files.length;i++)
    4963 {
    4964 if(files[i].isDirectory())
    4965 {
    4966 System.out.println("-----------"+files[i]+" is a directory has more files bellow:");
    4967 listDirectory(files[i].getAbsolutePath());
    4968 //listDirectory(files[i].getName());
    4969 //listDirectory(files[i].toString());
    4970 }
    4971 
    4972 else
    4973 {
    4974 System.out.println(files[i]);
    4975 }
    4976 }
    4977 }
    4978 File[] roots=File.listRoots();
    4979 for(int i=0;i<roots.length;i++)
    4980 {
    4981 System.out.println(roots[i]);
    4982 }
    4983 }
    4984 lrt.listDirectory("D:"+File.separator);
  • 相关阅读:
    判断字符串是否为数字
    Javascript to validate HKID number
    ServiceNow 中Reference 的 dynamic creation script
    Dynamic CRM 中修改实体中主字段的长度
    字符串的压缩与解压
    JDBC中重要的类/接口-Connection、DriverManager、ResultSet、Statement及常用方法
    java读取指定package下的所有class
    mybatis由JDBC的演化过程分析
    Java类与对象初始化的过程(一道经典的面试题)
    StringBuffer和StringBuilder区别?
  • 原文地址:https://www.cnblogs.com/lr393993507/p/5702986.html
Copyright © 2020-2023  润新知