Java最全文件操作实例汇总
本文实例汇总了Java文件操作。分享给大家供大家参考,具体如下:
1.创建文件夹
//importjava.io.*; FilemyFolderPath=newFile(%%1); try{ if(!myFolderPath.exists()){ myFolderPath.mkdir(); } } catch(Exceptione){ System.out.println("新建目录操作出错"); e.printStackTrace(); }
2.创建文件
//importjava.io.*; FilemyFilePath=newFile(%%1); try{ if(!myFilePath.exists()){ myFilePath.createNewFile(); } FileWriterresultFile=newFileWriter(myFilePath); PrintWritermyFile=newPrintWriter(resultFile); myFile.println(%%2); resultFile.close(); } catch(Exceptione){ System.out.println("新建文件操作出错"); e.printStackTrace(); }
3.删除文件
//importjava.io.*; FilemyDelFile=newFile(%%1); try{ myDelFile.delete(); } catch(Exceptione){ System.out.println("删除文件操作出错"); e.printStackTrace(); }
4.删除文件夹
//importjava.io.*; FiledelFolderPath=newFile(%%1); try{ delFolderPath.delete();//删除空文件夹 } catch(Exceptione){ System.out.println("删除文件夹操作出错"); e.printStackTrace(); }
5.删除一个文件下夹所有的文件夹
//importjava.io.*; Filedelfile=newFile(%%1); File[]files=delfile.listFiles(); for(inti=0;i<files.length;i++){ if(files[i].isDirectory()){ files[i].delete(); } }
6.清空文件夹
//importjava.io.*; Filedelfilefolder=newFile(%%1); try{ if(!delfilefolder.exists()){ delfilefolder.delete(); } delfilefolder.mkdir(); } catch(Exceptione){ System.out.println("清空目录操作出错"); e.printStackTrace(); }
7.读取文件
//importjava.io.*; //逐行读取数据 FileReaderfr=newFileReader(%%1); BufferedReaderbr=newBufferedReader(fr); String%%2=br.readLine(); while(%%2!=null){ %%3 %%2=br.readLine(); } br.close(); fr.close();
8.写入文件
//importjava.io.*; //将数据写入文件 try{ FileWriterfw=newFileWriter(%%1); fw.write(%%2); fw.flush(); fw.close(); }catch(IOExceptione){ e.printStackTrace(); }
9.写入随机文件
//importjava.io.*; try{ RandomAcessFilelogFile=newRandomAcessFile(%%1,"rw"); longlg=logFile.length(); logFile.seek(%%2); logFile.writeByte(%%3); }catch(IOExceptionioe){ System.out.println("无法写入文件:"+ioe.getMessage()); }
10.读取文件属性
//importjava.io.*; //文件属性的取得 Fileaf=newFile(%%1); if(af.exists()){ System.out.println(f.getName()+"的属性如下:文件长度为:"+f.length()); System.out.println(f.isFile()?"是文件":"不是文件"); System.out.println(f.isDirectory()?"是目录":"不是目录"); System.out.println(f.canRead()?"可读取":"不"); System.out.println(f.canWrite()?"是隐藏文件":""); System.out.println("文件夹的最后修改日期为:"+newDate(f.lastModified())); }else{ System.out.println(f.getName()+"的属性如下:"); System.out.println(f.isFile()?"是文件":"不是文件"); System.out.println(f.isDirectory()?"是目录":"不是目录"); System.out.println(f.canRead()?"可读取":"不"); System.out.println(f.canWrite()?"是隐藏文件":""); System.out.println("文件的最后修改日期为:"+newDate(f.lastModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 }
11.写入属性
//importjava.io.*; Filefilereadonly=newFile(%%1); try{ booleanb=filereadonly.setReadOnly(); } catch(Exceptione){ System.out.println("拒绝写访问:"+e.printStackTrace()); }
12.枚举一个文件夹中的所有文件
//importjava.io.*; //importjava.util.*; LinkedList<String>folderList=newLinkedList<String>(); folderList.add(%%1); while(folderList.size()>0){ Filefile=newFile(folderList.peek()); folderList.removeLast(); File[]files=file.listFiles(); ArrayList<File>fileList=newArrayList<File>(); for(inti=0;i<files.length;i++){ if(files[i].isDirectory()){ folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ %%2=f.getAbsoluteFile(); %%3 } }
13.复制文件夹
//importjava.io.*; //importjava.util.*; LinkedList<String>folderList=newLinkedList<String>(); folderList.add(%%1); LinkedList<String>folderList2=newLinkedList<String>(); folderList2.add(%%2+%%1.substring(%%1.lastIndexOf("//"))); while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.peek()); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.peek().endsWith(File.separator)){ temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp); FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator +(temp.getName()).toString()); byte[]b=newbyte[5120]; intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); }
14.复制一个文件夹下所有的文件夹到另一个文件夹下
//importjava.io.*; //importjava.util.*; Filecopyfolders=newFile(%%1); File[]copyfoldersList=copyfolders.listFiles(); for(intk=0;k<copyfoldersList.length;k++){ if(copyfoldersList[k].isDirectory()){ ArrayList<String>folderList=newArrayList<String>(); folderList.add(copyfoldersList[k].getPath()); ArrayList<String>folderList2=newArrayList<String>(); folderList2.add(%%2+"/"+copyfoldersList[k].getName()); for(intj=0;j<folderList.length;j++){ (newFile(folderList2.get(j))).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.get(j)); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.get(j).endsWith(File.separator)){ temp=newFile(folderList.get(j)+"/"+file[i]); } else{ temp=newFile(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStreaminput=newFileInputStream(temp); if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp); FileOutputStreamoutput=newFileOutputStream(folderList2.get(j)+"/"+ (temp.getName()).toString()); byte[]b=newbyte[5120]; intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch(Exceptione){ System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } } }
15.移动文件夹
//importjava.io.*; //importjava.util.*; LinkedList<String>folderList=newLinkedList<String>(); folderList.add(%%1); LinkedList<String>folderList2=newLinkedList<String>(); folderList2.add(%%2+%%1.substring(%%1.lastIndexOf("//"))); while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.peek()); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.peek().endsWith(File.separator)){ temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp); FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator +(temp.getName()).toString()); byte[]b=newbyte[5120]; intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush(); output.close(); input.close(); if(!temp.delete()) System.out.println("删除单个文件操作出错!"); } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } Filef=newFile(%%1); if(!f.delete()){ for(Filefile:f.listFiles()){ if(file.list().length==0){ System.out.println(file.getPath()); file.delete(); } } }
16.移动一个文件夹下所有的文件夹到另一个目录下
//importjava.io.*; //importjava.util.*; Filemovefolders=newFile(%%1); File[]movefoldersList=movefolders.listFiles(); for(intk=0;k<movefoldersList.length;k++){ if(movefoldersList[k].isDirectory()){ ArrayList<String>folderList=newArrayList<String>(); folderList.add(movefoldersList[k].getPath()); ArrayList<String>folderList2=newArrayList<String>(); folderList2.add(%%2+"/"+movefoldersList[k].getName()); for(intj=0;j<folderList.length;j++){ (newFile(folderList2.get(j))).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.get(j)); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.get(j).endsWith(File.separator)){ temp=newFile(folderList.get(j)+"/"+file[i]); } else{ temp=newFile(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStreaminput=newFileInputStream(temp); if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp); FileOutputStreamoutput=newFileOutputStream(folderList2.get(j)+"/"+ (temp.getName()).toString()); byte[]b=newbyte[5120]; intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush(); output.close(); input.close(); temp.delete(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch(Exceptione){ System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } movefoldersList[k].delete(); } }
17.以一个文件夹的框架在另一个目录创建文件夹和空文件
//importjava.io.*; //importjava.util.*; booleanb=false;//不创建空文件 ArrayList<String>folderList=newArrayList<String>(); folderList.add(%%1); ArrayList<String>folderList2=newArrayList<String>(); folderList2.add(%%2); for(intj=0;j<folderList.length;j++){ (newFile(folderList2.get(j))).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.get(j)); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.get(j).endsWith(File.separator)){ temp=newFile(folderList.get(j)+"/"+file[i]); } else{ temp=newFile(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStreaminput=newFileInputStream(temp); if(temp.isFile()){ if(b)temp.createNewFile(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch(Exceptione){ System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } }
18.复制文件
//importjava.io.*; intbytesum=0; intbyteread=0; Fileoldfile=newFile(%%1); try{ if(oldfile.exists()){//文件存在时 FileInputStreaminStream=newFileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,oldfile.getName())); byte[]buffer=newbyte[5120]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小 System.out.println(bytesum); fs.write(buffer,0,byteread); } inStream.close(); } } catch(Exceptione){ System.out.println("复制单个文件操作出错"); e.printStackTrace(); }
19.复制一个文件夹下所有的文件到另一个目录
//importjava.io.*; Filecopyfiles=newFile(%%1); File[]files=copyfiles.listFiles(); for(inti=0;i<files.length;i++){ if(!files[i].isDirectory()){ intbytesum=0; intbyteread=0; try{ InputStreaminStream=newFileInputStream(files[i]);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,files[i].getName()); byte[]buffer=newbyte[5120]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小 System.out.println(bytesum); fs.write(buffer,0,byteread); } inStream.close(); }catch(Exceptione){ System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } }
20.提取扩展名
String%%2=%%1.substring(%%1.lastIndexOf(".")+1);
21.提取文件名
String%%2=%%1.substring(%%1.lastIndexOf("//")+1);
22.提取文件路径
String%%2=%%1.substring(0,%%1.lastIndexOf("//"));
23.替换扩展名
//importjava.io.*; FilereplaceExt=newFile(%%1); replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);
24.追加路径
finalStringpath=%%1.endsWith("//")?%%1:%%1+"//"; %%3=path+%%2;
25.移动文件
//importjava.io.*; intbytesum=0; intbyteread=0; Fileoldfile=newFile(%%1); try{ if(oldfile.exists()){//文件存在时 InputStreaminStream=newFileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,oldfile.getName())); byte[]buffer=newbyte[5120]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小 //System.out.println(bytesum); fs.write(buffer,0,byteread); } inStream.close(); oldfile.delete(); } } catch(Exceptione){ System.out.println("复制单个文件操作出错"); e.printStackTrace(); }
26.移动一个文件夹下所有文件到另一个目录
//importjava.io.*; Filemovefile=newFile(%%1); File[]movefiles=movefile.listFiles(); for(inti=0;i<movefiles.length;i++){ if(movefiles[i].isFile()){ intbytesum=0; intbyteread=0; Fileoldfile=newFile(movefiles[i]); try{ if(oldfile.exists()){//文件存在时 InputStreaminStream=newFileInputStream(oldfile);//读入原文件 FileOutputStreamfs=newFileOutputStream(newFile(%%2,oldfile.getName())); byte[]buffer=newbyte[5120]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread;//字节数文件大小 //System.out.println(bytesum); fs.write(buffer,0,byteread); } inStream.close(); oldfile.delete(); } } catch(Exceptione){ System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } }
27.指定目录下搜索文件
//importjava.io.*; Stringfilter="*.*"; Stringpath=%%1; Filefile=newFile(path); if(file.exists()){ if(file.isDirectory()){ File[]fileArray=file.listFiles(); for(Filef:fileArray){ if(f.isDirectory()){ doSearch(filter,f.getPath()); }else{ if(f.getName().indexOf(filter)>=0){ countFiles++; result.append(f.getPath()+"/r/n"); } } statusShow1.setText(f.getPath()); } statusShow2.setText("Thenumbersoffileshadbeenfound:"+countFiles); }else{ System.out.println("Couldn'topenthepath!"); } }else{ System.out.println("ThepathhadbeenapointedwasnotExist!"); }
28.打开对话框
//importjava.io.*; //importjavax.swing.*; JFileChooserJfc=newJFileChooser();//建立选择档案对话方块盒Jfc if(Jfc.isFileSelectionEnabled()){ File%%1=Jfc.getSelectedFile(); }
29.文件分割
//importjava.io.* try{ Filef=newFile(%%1); FileInputStreamfileInputStream=newFileInputStream(f); byte[]buffer=newbyte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); StringstrFileName=f.getName(); FileOutputStreamfileOutputStream=newFileOutputStream(newFile(%%2+"//"+strFileName+"1")); fileOutputStream.write(buffer,0,buffer.length/2); fileOutputStream.close(); fileOutputStream=newFileOutputStream(newFile(%%2+"//"+strFileName+"2")); fileOutputStream.write(buffer,buffer.length/2,buffer.length-buffer.length/2); fileOutputStream.close(); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.print("usingFileStreamDemosrcdes"); e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); }
30.文件合并
//importjava.io.* StringstrFileName=%%1.substring(%%1.LastIndexOf("//")+1); try{ FileInputStreamfileInputStream1=newFileInputStream(newFile(%%2+strFileName+"1")); FileInputStreamfileInputStream2=newFileInputStream(newFile(%%2+strFileName+"2")); byte[]buffer=newbyte[fileInputStream1.available()+fileInputStream2.available()]; FileInputStream.read(buffer,0,fileInputStream1.available()); FileInputStream2.read(buffer,fileInputStream1.available(),fileInputStream2.available()); fileInputStream.close(); fileInputStream2.close(); FileOutputStreamfileOutputStream=newFileOutputStream(newFile(%%2+"//"+strFileName)); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); catch(IOExceptione){ e.printStackTrace(); }
31.文件简单加密
//importjava.io.* try{ Filef=newFile((newFile(%%1)).getPath()+"//enc_"+(newFile(%%1)).getName().split("//")[1]); StringstrFileName=f.getName(); FileInputStreamfileInputStream=newFileInputStream(%%2+"//"+strFilename); byte[]buffer=newbyte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(inti=0;i<buffer.length;i++) { intibt=buffer[i]; ibt+=100; ibt%=256; buffer[i]=(byte)ibt; } FileOutputStreamfileOutputStream=newFileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundExceptione){ e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); }
32.文件简单解密
//importjava.io.* try{ Filef=newFile(%%1); StringstrFileName=f.getName(); FileInputStreamfileInputStream=newFileInputStream(%%2+"//enc_"+strFilename); byte[]buffer=newbyte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(inti=0;i<buffer.length;i++) { intibt=buffer[i]; ibt-=100; ibt+=256; ibt%=256; buffer[i]=(byte)ibt; } FileOutputStreamfileOutputStream=newFileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundExceptione){ e.printStackTrace(); } catch(IOExceptione){ e.printStackTrace(); }
33.写入ini文件属性
//importjava.io.*; //importjava.util.*; //importjava.util.regex.*; if(configMap==null){ StringWriteBuffer=""; configMap=newHashMap<String,Serializable>(); StringstrLine=null; StringcurrentNode=null; StringpreviousNode=null; Vector<Properties>vec=newVector<Properties>(); introw=0; FileReaderfileReader=null; try{ fileReader=newFileReader("Config.ini"); }catch(FileNotFoundExceptione1){ e1.printStackTrace(); } BufferedReaderbufferedReader=newBufferedReader(fileReader); try{ while((strLine=bufferedReader.readLine())!=null){ StringoneLine=strLine.trim(); if(oneLine.length()>=1){ Patternp=Pattern.compile("//[//s*.*//s*//]"); intnodelen=oneLine.split("[;]").length; String[]strArray1=newString[4]; if(nodelen==1){ oneLine=oneLine.split("[;]")[0].trim(); }elseif(nodelen==2){ strArray1[3]=oneLine.split("[;]")[1].trim(); oneLine=oneLine.split("[;]")[0].trim(); } Matcherm=p.matcher(oneLine); if(m.matches()){ strArray1[0]="@Node"; strArray1[1]=oneLine; strArray1[2]=""; }else{ intkeylen=oneLine.split("=").length; if(keylen==1){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=""; }elseif(keylen==2){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=oneLine.split("=")[1]; }else{ strArray1[0]="@ElementError"; strArray1[1]=""; strArray1[2]=""; strArray1[3]=""; } } if(strArray1[0].equals("@Node")){ previousNode=currentNode; currentNode=strArray1[1]; if(row>0){ configMap.put(previousNode,vec.elementAt(0)); vec.clear(); row=0; } WriteBuffer+=(oneLine+"/r/n"); }elseif(strArray1[0].equals("@Key")&&row==0){ Propertiesht=newProperties(); ht.setProperty(strArray1[1],strArray1[2]); if(strArray1[1].equals(%%1)){ WriteBuffer+=(%%1+"="+%%2+"/r/n"); }else WriteBuffer+=(oneLine+"/r/n"); vec.add(0,ht); row++; }elseif(strArray1[0].equals("@Key")&&row>0){ Propertiesht2=newProperties(); ht2.put(strArray1[1],strArray1[2]); vec.clear(); vec.add(0,ht2); WriteBuffer+=(oneLine+"/r/n"); row++; } } } configMap.put(currentNode,vec.elementAt(0)); }catch(FileNotFoundExceptione){ configMap=null; e.printStackTrace(); }catch(IOExceptione){ configMap=null; e.printStackTrace(); }finally{ vec.clear(); try{ bufferedReader.close(); fileReader.close(); }catch(IOExceptione){ e.printStackTrace(); } try{ FileWriterfw=newFileWriter("Config.ini"); fw.write(WriteBuffer); fw.flush(); fw.close(); }catch(IOExceptione){ e.printStackTrace(); } } }
34.读取ini文件属性
//importjava.io.*; //importjava.util.*; //importjava.util.regex.*; //privateHashMapconfigMap=null; privateMap<String,Serializable>configMap=null; String%%2=null; if(configMap==null){ configMap=newHashMap<String,Serializable>(); StringstrLine=null; StringcurrentNode=null; StringpreviousNode=null; Vector<Properties>vec=newVector<Properties>(); introw=0; FileReaderfileReader=null; try{ fileReader=newFileReader("Config.ini"); }catch(FileNotFoundExceptione1){ e1.printStackTrace(); } BufferedReaderbufferedReader=newBufferedReader(fileReader); try{ while((strLine=bufferedReader.readLine())!=null){ StringoneLine=strLine.trim(); if(oneLine.length()>=1){ Patternp=Pattern.compile("//[//s*.*//s*//]"); intnodelen=oneLine.split("[;]").length; String[]strArray1=newString[4]; if(nodelen==1){ oneLine=oneLine.split("[;]")[0].trim(); }elseif(nodelen==2){ strArray1[3]=oneLine.split("[;]")[1].trim(); oneLine=oneLine.split("[;]")[0].trim(); } Matcherm=p.matcher(oneLine); if(m.matches()){ strArray1[0]="@Node"; strArray1[1]=oneLine; strArray1[2]=""; }else{ intkeylen=oneLine.split("=").length; if(keylen==1){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=""; }elseif(keylen==2){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=oneLine.split("=")[1]; }else{ strArray1[0]="@ElementError"; strArray1[1]=""; strArray1[2]=""; strArray1[3]=""; } } if(strArray1[0].equals("@Node")){ previousNode=currentNode; currentNode=strArray1[1]; if(row>0){ configMap.put(previousNode,vec.elementAt(0)); vec.clear(); row=0; } }elseif(strArray1[0].equals("@Key")&&row==0){ Propertiesht=newProperties(); ht.setProperty(strArray1[1],strArray1[2]); if(strArray1[1].equals(%%1)) { %%2=strArray1[2]; return; } vec.add(0,ht); row++; }elseif(strArray1[0].equals("@Key")&&row>0){ Propertiesht2=newProperties(); ht2.put(strArray1[1],strArray1[2]); vec.clear(); vec.add(0,ht2); row++; } } } configMap.put(currentNode,vec.elementAt(0)); }catch(FileNotFoundExceptione){ configMap=null; e.printStackTrace(); }catch(IOExceptione){ configMap=null; e.printStackTrace(); }finally{ vec.clear(); try{ bufferedReader.close(); fileReader.close(); }catch(IOExceptione){ e.printStackTrace(); } } }
35.合并一个文件下所有的文件
Filecombinefiles=newFile(%%1); File[]files=combinefiles.listFiles(); FileOutputStreamfs; try{ fs=newFileOutputStream(newFile(%%2)); } catch(IOExceptione){ e.printStackTrace(); } for(inti=0;i<files.length;i++){ if(files[i].isFile()){ intbytesum=0; intbyteread=0; try{ FileInputStreaminStream=newFileInputStream(files[i]); byte[]buffer=newbyte[5120]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread; fs.write(buffer,0,byteread); } inStream.close(); } catch(Exceptione){ //复制文件出错 e.printStackTrace(); } } } try{ fs.close(); } catch(IOExceptione){ { e.printStackTrace(); }
36.写入ini文件属性
//importjava.io.*; //importjava.util.*; //importjava.util.regex.*; //privateHashMapconfigMap=null; privateMap<String,Serializable>configMap=null; if(configMap==null){ StringstrLine=null; StringcurrentNode=null; StringpreviousNode=null; Vector<Properties>vec=newVector<Properties>(); introw=0; FileReaderfileReader=null; try{ fileReader=newFileReader(%%1); }catch(FileNotFoundExceptione1){ e1.printStackTrace(); } BufferedReaderbufferedReader=newBufferedReader(fileReader); try{ while((strLine=bufferedReader.readLine())!=null){ StringoneLine=strLine.trim(); if(oneLine.length()>=1){ Patternp=Pattern.compile("//[//s*.*//s*//]"); intnodelen=oneLine.split("[;]").length; String[]strArray1=newString[4]; if(nodelen==1){ oneLine=oneLine.split("[;]")[0].trim(); } elseif(nodelen==2){ strArray1[3]=oneLine.split("[;]")[1].trim(); oneLine=oneLine.split("[;]")[0].trim(); } Matcherm=p.matcher(oneLine); if(m.matches()){ strArray1[0]="@Node"; strArray1[1]=oneLine; strArray1[2]=""; }else{ intkeylen=oneLine.split("=").length; if(keylen==1){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=""; }elseif(keylen==2){ strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=oneLine.split("=")[1]; }else{ strArray1[0]="@ElementError"; strArray1[1]=""; strArray1[2]=""; strArray1[3]=""; } } if(strArray1[0].equals("@Node")){ previousNode=currentNode; currentNode=strArray1[1]; if(row>0){ configMap.put(previousNode,vec.elementAt(0)); //"size:"+configMap.size() vec.clear(); row=0; } }elseif(strArray1[0].equals("@Key")&&row==0){ Propertiesht=newProperties(); ht.setProperty(strArray1[1],strArray1[2]); vec.add(0,ht); row++; }elseif(strArray1[0].equals("@Key")&&row>0){ Propertiesht2=newProperties(); ht2.put(strArray1[1],strArray1[2]); vec.clear(); vec.add(0,ht2); row++; } } } configMap.put(currentNode,vec.elementAt(0)); }catch(FileNotFoundExceptione){ configMap=null; e.printStackTrace(); }catch(IOExceptione){ configMap=null; e.printStackTrace(); }finally{ vec.clear(); try{ bufferedReader.close(); fileReader.close(); }catch(IOExceptione){ e.printStackTrace(); } } } StringnodeKey="["+%%2+"]"; Propertiesht=null; if(configMap.containsKey(nodeKey)){ ht=(Properties)configMap.get(nodeKey); }else{ ht=(Properties)configMap.put(nodeKey,%%3); } try{ ht.setProperty(%%3,%%4); }catch(NullPointExceptione){ e.printStackTrace(); } FileWriterfw=null; BufferedWriterbw=null; try{ fw=newFileWriter(%%1); bw=newBufferedWriter(fw); }catch(IOExceptione){ e.printStackTrace(); } Setkeys=configMap.keySet(); Iteratorite=keys.iterator(); while(ite.hasNext()){ StringoneKey=(String)ite.next(); try{ bw.write(oneKey+"/n"); }catch(IOExceptione){ e.printStackTrace(); } ht=(Properties)configMap.get(oneKey); ht.list(newPrintWriter(bw,true)); }
37.获得当前路径
String%%1=this.getClass().getResource("/").getPath();
38.读取XML数据库
//importjava.io.*; //importjavax.xml.parsers.*; //importorg.xml.sax.*; //importorg.w3c.dom.*; privateDocumentdocument; Filexml_file=newFile(%%1); DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance(); try{ DocumentBuilderbuilder=factory.newDocumentBuilder(); document=builder.parse(xml_file); }catch(Exceptione){ e.printStackTrace(); } StringsubNodeTag=%%2; ElementrootNode=document.getDocumentElement(); //%%2="serverList"//%%4="id"//%%6="port" //%%3="server"//%%5="ipaddr" NodeListnlist=rootNode.getElementsByTagName(subNodeTag); intlen=nlist.getLength(); Nodex=null; for(inti=0;i<len;i++){ x=nlist.item(i); StringgetNodeAttrValue=null; NamedNodeMapattrList=node.getAttributes(); for(intj=0;j<attrList.getLength();j++){ if(attrList.item(j).getNodeName().compareTo(%%7)==0){ getNodeAttrValue=attrList.item(j).getNodeValue(); break; } } if(getNodeAttrValue.compareTo(%%8)==0) break; } String%%9=null; if(x!=null){ NodeListnlist=node.getChildNodes(); intlen=nlist.getLength(); NodecurrentNode; StringnodeName; for(inti=0;i<len;i++){ currentNode=nlist.item(i); nodeName=currentNode.getNodeName(); if(nodeName.equals(%%5)==0){ %%9=document.getElementValue(currentNode); break; } } }
39.写入XML数据库
//importjava.io.*; //importjavax.xml.parsers.*; //importorg.xml.sax.*; //importorg.w3c.dom.*; //importjavax.xml.transform.*; //importjavax.xml.transform.dom.*; //importjavax.xml.transform.stream.*; privateDocumentdocument; privateElementnode; Filexml_file=newFile(%%1); DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance(); try{ DocumentBuilderbuilder=factory.newDocumentBuilder(); document=builder.parse(xml_file); }catch(Exceptione){ e.printStackTrace(); } StringsubNodeTag=%%2; ElementrootNode=document.getDocumentElement(); //%%2="serverList"//%%4="id"//%%6="port" //%%3="server"//%%5="ipaddr" NodeListnlist=rootNode.getElementByTagName(subNodeTag); node=document.createElement(%%3); node.setAttribute(%%4,nlist.getLength()+1).toString()); node.appendChild(document.createTextNode("/n"); ElementipNode=document.createElement(%%5); ipNode.appendChild(document.createTextNode(%%8)); node.appendChild(ipNode); node.appendChild(document,createTextNode("/n"); Elementport=document.createElement(%%6); port.appendChild(document.createTextNode(%%9)); node.appendChild(port); node.appendChild(document,createTextNode("/n"); nlist.appendChild(node); TransformerFactorytFactory=TransformerFactory.newInstance(); Transformertransformer=null; try{ transformer=tFactory.newTransformer(); DOMSourcesource=newDOMSource(document); StreamResultresult=newStreamResult(xml_file); transformer.transform(source,result); }catch(Exceptione){ e.printStackTrace(); }
40.ZIP压缩文件
//importjava.io.*; //importjava.util.zip.*; //创建文件输入流对象 FileInputStreamfis=newFileInputStream(%%1); //创建文件输出流对象 FileOutputStreamfos=newFileOutputStream(%%2); //创建ZIP数据输出流对象 ZipOutputStreamzipOut=newZipOutputStream(fos); //创建指向压缩原始文件的入口 ZipEntryentry=newZipEntry(args[0]); zipOut.putNextEntry(entry); //向压缩文件中输出数据 intnNumber; byte[]buffer=newbyte[1024]; while((nNumber=fis.read(buffer))!=-1) zipOut.write(buffer,0,nNumber); //关闭创建的流对象 zipOut.close(); fos.close(); fis.close(); } catch(IOExceptione) { System.out.println(e); }
41.获得应用程序完整路径
String%%1=System.getProperty("user.dir");
42.ZIP解压缩
//importjava.io.*; //importjava.util.zip.*; try{ //创建文件输入流对象实例 FileInputStreamfis=newFileInputStream(%%1); //创建ZIP压缩格式输入流对象实例 ZipInputStreamzipin=newZipInputStream(fis); //创建文件输出流对象实例 FileOutputStreamfos=newFileOutputStream(%%2); //获取Entry对象实例 ZipEntryentry=zipin.getNextEntry(); byte[]buffer=newbyte[1024]; intnNumber; while((nNumber=zipin.read(buffer,0,buffer.length))!=-1) fos.write(buffer,0,nNumber); //关闭文件流对象 zipin.close(); fos.close(); fis.close(); } catch(IOExceptione){ System.out.println(e); }
43.递归删除目录中的文件
//importjava.io.*; //importjava.util.*; ArrayList<String>folderList=newArrayList<String>(); folderList.add(%%1); for(intj=0;j<folderList.size();j++){ Filefile=newFile(folderList.get(j)); File[]files=file.listFiles(); ArrayList<File>fileList=newArrayList<File>(); for(inti=0;i<files.length;i++){ if(files[i].isDirectory()){ folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } }
43.ZIP压缩文件夹
//importjava.io.*; //importorg.apache.tools.zip.ZipOutputStream; //这个包在ant.jar里,要到官方网下载 //importjava.util.zip.*; try{ StringzipFileName=%%2;//打包后文件名字 Filef=newFile(%%1); ZipOutputStreamout=newZipOutputStream(newFileOutputStream(zipFileName)); Stringbase=""; if(f.isDirectory()){ File[]fl=f.listFiles(); out.putNextEntry(neworg.apache.tools.zip.ZipEntry(base+"/")); base=base.length()==0?"":base+"/"; for(inti=0;i<fl.length;i++){ zip(out,fl[i],base+fl[i].getName()); } }else{ out.putNextEntry(neworg.apache.tools.zip.ZipEntry(base)); FileInputStreamin=newFileInputStream(f); intb; while((b=in.read())!=-1){ out.write(b); } in.close(); } out.close(); }catch(Exceptionex){ ex.printStackTrace(); }
44.Java验证DTD
//importjava.io.*; //importjavax.xml.parsers.*; //importorg.xml.sax.*; //importorg.w3c.dom.*; try{ InputStreamin=newFileInputStream(filePath); SAXReadersaxReader=newSAXReader(); this.document=saxReader.read(in); DocumentBuilderFactoryfactory=null; factory=DocumentBuilderFactory.newInstance(); //进行dtd检查 factory.setValidating(true); }catch(Exceptione){ }
45.验证Schema
//importjava.io.*; //importjavax.xml.parsers.*; //importorg.xml.sax.*; //importorg.w3c.dom.*; StringxsdFileName=/"Q:////_dev_stu////xsdtest////src////note.xsd/"; try{ //创建默认的XML错误处理器 XMLErrorHandlererrorHandler=newXMLErrorHandler(); //获取基于SAX的解析器的实例 SAXParserFactoryfactory=SAXParserFactory.newInstance(); //解析器在解析时验证XML内容。 factory.setValidating(true); //指定由此代码生成的解析器将提供对XML名称空间的支持。 factory.setNamespaceAware(true); //使用当前配置的工厂参数创建SAXParser的一个新实例。 SAXParserparser=factory.newSAXParser(); //创建一个读取工具 SAXReaderxmlReader=newSAXReader(); //获取要校验xml文档实例 DocumentxmlDocument=(Document)xmlReader.read(newFile(xmlFileName)); //设置XMLReader的基础实现中的特定属性。核心功能和属性列表可以在http://sax.sourceforge.net/?selected=get-set中找到。 parser.setProperty( /"http://java.sun.com/xml/jaxp/properties/schemaLanguage", /"http://www.w3.org/2001/XMLSchema"); parser.setProperty( /"http://java.sun.com/xml/jaxp/properties/schemaSource", /"file:/"+xsdFileName); //创建一个SAXValidator校验工具,并设置校验工具的属性 SAXValidatorvalidator=newSAXValidator(parser.getXMLReader()); //设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 validator.setErrorHandler(errorHandler); //校验 validator.validate(xmlDocument); XMLWriterwriter=newXMLWriter(OutputFormat.createPrettyPrint()); //如果错误信息不为空,说明校验失败,打印错误信息 if(errorHandler.getErrors().hasContent()){ System.out.println(/"XML文件通过XSD文件校验失败!/"); writer.write(errorHandler.getErrors()); }else{ System.out.println(/"Good!XML文件通过XSD文件校验成功!/"); } }catch(Exceptionex){ System.out.println(/"XML文件:/"+xmlFileName+/"通过XSD文件:/"+xsdFileName+/"检验失败。/n原因:/"+ex.getMessage ()); ex.printStackTrace(); } }
46.Grep
//importjava.util.regex.*; //importjava.io.*; /** *Simpleimplementationoftheubiquitousgrepcommand. *Firstargumentistheregularexpressiontosearchfor(rememberto *quoteand/orescapeasappropriate).Allfollowingargumentsare *filenamestoreadandsearchfortheregularexpression. * *Created:April,2002 *@authorRonHitchens(ron@ronsoft.com) *@version$Id:SimpleGrep.java,v1.12002/05/0702:21:08ronExp$ */ publicstaticvoidmain(String[]argv) throwsException { if(argv.length<2){//如果参数行没有输入参数,结束程序 System.out.println("Usage:regexfile[...]"); return; } Patternpattern=Pattern.compile(argv[0]);//第一个参数为需要匹配的字符串 Matchermatcher=pattern.matcher(""); //一次读取各个文件 for(inti=1;i<argv.length;i++){ Stringfile=argv[i];//第2个参数开始,均为文件名。 BufferedReaderbr=null; Stringline; try{ br=newBufferedReader(newFileReader(file));//打开文件 }catch(IOExceptione){ //没有打开文件,则产生异常 System.err.println("Cannotread'"+file +"':"+e.getMessage()); continue; } while((line=br.readLine())!=null){//读入一行,直到文件结束 matcher.reset(line);//匹配字符串 if(matcher.find()){//如果有匹配的字符串,则输出 System.out.println(file+":"+line); } } br.close();//关闭文件 } }
47.直接创建多级目录
//importjava.io.*; Filef=newFile(%%1); f.mkdirs();
48.批量重命名
//importjava.io.*; Filetarget=newFile("%%1"); String[]files=target.list(); Filef=null; Stringfilename=null; for(Stringfile:files){ f=newFile(fl,file); filename=f.getName(); if(filename.substring(filename.lastIndexOf (".")).equalsIgnoreCase( "%%2")){ f.renameTo(newFile(target.getAbsolutePath(), filename.replace( "%%2","%%3"))); //这里可以反复使用replace替换,当然也可以使用正则表达式来 //替换了".txt"".bat" } }
49.文本查找替换
//importjava.nio.*; Strings1=%%1; Strings2=%%2; Strings3=%%3; intpos=%%4; /*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/ inti,j,k=0; i=pos; j=0; //将s1转化成StringBuffer型进行操作 repStr=newStringBuffer(s1); while(i<repStr.length()&&j<s2.length()) { if(repStr.charAt(i)==s2.charAt(j)) { ++i;++j; if(j==s2.length()) { /*j=s2.length()表示字符串匹配成功,匹配次数加1,此外对主串进行字符串替换*/ k=k+1; repStr.replace(i-j,i,s3); //将j进行重新赋值开始新的比较 j=0; } } else{i=i-j+1;j=0;} } returnk;
50.文件关联
//importjava.io.*; try{ Runtime.getRuntime().exec(%%1);//"assoc.txt=mynote""assoc[.ext[=[filetype]]]" }catch(IOExceptione){ e.printStackTrace(); }
52.设置JDK环境变量
@echooff IFEXIST%1/bin/java.exe( rem如输入正确的Java2SDK安装目录,开始设置环境变量 @setxJAVA_HOME%1 @setxpath%path%;%JAVA_HOME%/bin @setxclasspath%classpath%;. @setxclasspath%classpath%;%JAVA_HOME%/lib/tools.jar @setxclasspath%classpath%;%JAVA_HOME%/lib/dt.jar @setxclasspath%classpath%;%JAVA_HOME%/jre/lib/rt.jar @echoon @echoJava2SDK环境参数设置完毕,正常退出。 )ELSE( IF"%1"==""( rem如没有提供安装目录,提示之后退出 @echoon @echo没有提供Java2SDK的安装目录,不做任何设置,现在退出环境变量设置。 )ELSE( rem如果提供非空的安装目录但没有bin/java.exe,则指定的目录为错误的目录 @echoon @echo非法的Java2SDK的安装目录,不做任何设置,现在退出环境变量设置。 ) ) //http://sourceforge.net/projects/jregistrykey/ //importca.beq.util.win32.registry.*; //importjava.util.*;
1.打开键
RegistryKeyr=newRegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE//Microsoft//Windows//CurrentVersion//Explorer//ShellFolders");
2.添加键
RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,"Software//BEQ Technologies"); r.create();
3.写入字符串值
RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,"Software//BEQTechnologies"); RegistryValuev=newRegistryValue("myVal",ValueType.REG_SZ,"data"); r.setValue(v);
4.获取DWORD值
RegistryKeyr=newRegistryKey(RootKey.HKEY_CURRENT_USER,"Software//BEQTechnologies"); if(r.hasValue("myValue")){ RegistryValuev=r.getValue("myValue"); v.setType(ValueType.REG_DWORD); }//if
53.选择文件夹对话框
/* importjava.io.*; importjavax.swing.*; */ JFileChooserchooser=newJFileChooser(); chooser.setCurrentDirectory(newFile(".")); chooser.setFileFilter(newjavax.swing.filechooser.FileFilter(){ publicbooleanaccept(Filef){ returnf.getName().toLowerCase().endsWith(".gif") ||f.isDirectory(); } publicStringgetDescription(){ return"GIFImages"; } }); intr=chooser.showOpenDialog(null); if(r==JFileChooser.APPROVE_OPTION){ Stringname=chooser.getSelectedFile().getPath(); //label.setIcon(newImageIcon(name)); }
54.删除空文件夹
//importjava.io.*; Filef=newFile(%%1); if(isFolerNull(f)){ for(Filefile:f.listFiles()){ if(file.list().length==0){ System.out.println(file.getPath()); file.delete(); } } }
55.发送数据到剪贴板
//importjava.awt.*; //importjava.awt.datatransfer.*; Clipboardclipboard=Toolkit.getDefaultToolkit().getSystemClipboard(); TransferabletText=newStringSelection(%%1); clipboard.setContents(tText,null);
56.从剪贴板中取数据
//importjava.awt.*; //importjava.awt.datatransfer.*; //取得系统剪贴板里可传输的数据构造的Java对象 Transferablet=Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); try{ if(t!=null &&t.isDataFlavorSupported(DataFlavor.stringFlavor)){ //因为原系的剪贴板里有多种信息,如文字,图片,文件等 //先判断开始取得的可传输的数据是不是文字,如果是,取得这些文字 Strings=(String)t .getTransferData(DataFlavor.stringFlavor); //同样,因为Transferable中的DataFlavor是多种类型的, //所以传入DataFlavor这个参数,指定要取得哪种类型的Data. System.out.println(s); } }catch(UnsupportedFlavorExceptionex){ ex.printStackTrace(); }catch(IOExceptionex){ ex.printStackTrace(); }
57.获取文件路径的父路径
String%%2=%%1.substring(0,%%1.lastIndexOf("//"));
58.创建快捷方式
//importjava.io.*; try{ PrintWriterpw=newPrintWriter(newFileOutputStream("C:/a.bat")); pw.println(%%1);"C:/a.txt" pw.close(); } catch(IOExceptione){ e.printStackTrace(); }
59.弹出快捷菜单
//MouseEvente JPopupMenujpm=newJPopupMenu(); show(jpm,x,y);
60.文件夹复制到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径");//建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径");//建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent(); LinkedList<String>folderList=newLinkedList<String>(); folderList.add(%%1); LinkedList<String>folderList2=newLinkedList<String>(); folderList2.add(%%2+%%1.substring(%%1.lastIndexOf("//"))); while(folderList.size()>0){ (newFile(folderList2.peek())).mkdirs();//如果文件夹不存在则建立新文件夹 Filefolders=newFile(folderList.peek()); String[]file=folders.list(); Filetemp=null; try{ for(inti=0;i<file.length;i++){ if(folderList.peek().endsWith(File.separator)){ temp=newFile(folderList.peek()+File.separator +file[i]); }else{ temp=newFile(folderList.peek()+File.separator +file[i]); } if(temp.isFile()){ FileInputStreaminput=newFileInputStream(temp); FileOutputStreamoutput=newFileOutputStream( folderList2.peek()+File.separator +(temp.getName()).toString()); byte[]b=newbyte[5120]; intlen; while((len=input.read(b))!=-1){ output.write(b,0,len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 for(Filef:temp.listFiles()){ if(f.isDirectory()){ folderList.add(f.getPath()); folderList2.add(folderList2.peek() +File.separator+f.getName()); } } } } }catch(Exceptione){ //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); }
61.文件夹移动到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径");//建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径");//建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
62.目录下所有文件夹复制到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径"); //建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径");//建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
63.目录下所有文件夹移动到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径"); //建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径"); //建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
64.目录下所有文件复制到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径"); //建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径"); //建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
65.目录下所有文件移动到整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径"); //建立选择档案对话 //方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径"); //建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
66.对目标压缩文件解压缩到指定文件夹
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */
67.创建目录副本整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */ JFileChooserJfc=newJFileChooser("请选择源路径"); //建立选择档案对话 方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%1=Jfc.getSelectedFile().getParent(); Jfc=newJFileChooser("请选择目标路径"); //建立选择档案对话方块盒Jfc if(!Jfc.isFileSelectionEnabled()){ return; } String%%2=Jfc.getSelectedFile().getParent();
68.打开网页
//importjava.io.*; try{ Stringcommand="C://ProgramFiles//InternetExplorer//Iexplore.exe"+%%1; Runtime.getRuntime().exec(command); }catch(IOExceptionex){ ex.printStackTrace(); }
69.删除空文件夹整合操作
/* importjava.io.*; importjava.util.*; importjavax.swing.*; */
70.获取磁盘所有分区后再把光驱盘符去除(用"/0"代替),把结果放在数组allfenqu[]中,数组中每
个元素代表一个分区盘符,不包括://这样的路径,allfenqu[]数组开始时存放的是所有盘符。
当我用这样的代码测试结果是正确的,光驱盘符会被去掉:
Stringroot;//root代表盘符路径 for(i=0;i<20;i++)//0-20代表最大的盘符数 { root.Format("%c://",allfenqu[i]); if(GetDriveType(root)==5) allfenqu[i]='/0'; } 但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符: Stringroot; for(i=0;i<20;i++) { root=allfenqu[i]+"://"; if(GetDriveType(root)==5) allfenqu[i]='/0'; }
71.激活一个程序或程序关联的文件
//importjava.io.*; try{ Runtime.getRuntime().exec(%%1); }catch(IOExceptione){ e.printStackTrace(); }
72.HTTP下载
publicclassDownloadCSVFileActionextendsAction{ publicActionForwardexecute(ActionMappingmapping,ActionFormform, HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ try{ StringfileName=request.getParameter("fileName"); longmaID=Long.parseLong(request.getParameter("maID")); StringfilePath=request.getSession().getServletContext ().getRealPath("/")+"csv/"+maID+"/"+fileName; Filefdown=newFile(filePath); intfilelength=Integer.parseInt(String.valueOf (fdown.length())); //下载类型 response.setContentType("application/text;charset=GB2312"); response.setHeader("Content-Dispositon","attachment;filename= 销售详细记录.csv");//销售详细记录.csv是我想要的下载文件的文件名,但是下载对话框中显 示的是downLoadCSVFile.do response.setContentLength(filelength); byteb[]=newbyte[filelength]; FileInputStreamfi=newFileInputStream(fdown); OutputStreamo=response.getOutputStream(); intn=0; while((n=fi.read(b))!=-1){ o.write(b,0,n); } fi.close(); o.close(); returnnull; }catch(Exceptione){ request.setAttribute("ERROR",e); returnmapping.findForward("error"); } } }
对应的下载类型
privateStringgetContentType(StringfileName){ StringfileNameTmp=fileName.toLowerCase(); Stringret=""; if(fileNameTmp.endsWith("txt")){ ret="text/plain"; } if(fileNameTmp.endsWith("gif")){ ret="image/gif"; } if(fileNameTmp.endsWith("jpg")){ ret="image/jpeg"; } if(fileNameTmp.endsWith("jpeg")){ ret="image/jpeg"; } if(fileNameTmp.endsWith("jpe")){ ret="image/jpeg"; } if(fileNameTmp.endsWith("zip")){ ret="application/zip"; } if(fileNameTmp.endsWith("rar")){ ret="application/rar"; } if(fileNameTmp.endsWith("doc")){ ret="application/msword"; } if(fileNameTmp.endsWith("ppt")){ ret="application/vnd.ms-powerpoint"; } if(fileNameTmp.endsWith("xls")){ ret="application/vnd.ms-excel"; } if(fileNameTmp.endsWith("html")){ ret="text/html"; } if(fileNameTmp.endsWith("htm")){ ret="text/html"; } if(fileNameTmp.endsWith("tif")){ ret="image/tiff"; } if(fileNameTmp.endsWith("tiff")){ ret="image/tiff"; } if(fileNameTmp.endsWith("pdf")){ ret="application/pdf"; } returnret; }
73.FTP下载
/* importsun.net.ftp.FtpClient; importjava.io.*; importsun.net.*; */ //如果文件在某个目录下,则加入fc.cd("foodir"); //比如要下载ftp://ftp.xx.com/index.html则: try { FtpClientfc=newFtpClient("ftp.xx.com"); fc.login("username","888888"); intch; Filefi=newFile("c://index.html"); RandomAccessFilegetFile=newRandomAccessFile(fi,"rw"); getFile.seek(0); TelnetInputStreamfget=fc.get("index.html"); DataInputStreamputs=newDataInputStream(fget); while((ch=puts.read())>=0){ getFile.write(ch); } fget.close(); getFile.close(); fc.closeServer(); } catch(IOExceptionex) { ex.printStackTrace(); }
74.写图像到剪切板setClipboardImage
/* importjava.awt.*; importjava.awt.datatransfer.*; importjava.io.*; */ privatefinalImageimage; Transferabletrans=newTransferable(){ publicDataFlavor[]getTransferDataFlavors(){ returnnewDataFlavor[]{DataFlavor.imageFlavor}; } publicbooleanisDataFlavorSupported(DataFlavorflavor){ returnDataFlavor.imageFlavor.equals(flavor); } publicObjectgetTransferData(DataFlavorflavor) throwsUnsupportedFlavorException,IOException{ if(isDataFlavorSupported(flavor)) returnimage; thrownewUnsupportedFlavorException(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
75.从剪贴板复制图像到窗体
76.删除文件夹下的所有文件且不删除文件夹下的文件夹
//importjava.io.*; //importjava.util.*; LinkedList<String>folderList=newLinkedList<String>(); folderList.add(%%1); while(folderList.size()>0){ Filefile=newFile(folderList.peek()); folderList.removeLast(); File[]files=file.listFiles(); ArrayList<File>fileList=newArrayList<File>(); for(inti=0;i<files.length;i++){ if(files[i].isDirectory()){ folderList.add(files[i].getPath()); }else{ fileList.add(files[i]); } } for(Filef:fileList){ f.delete(); } }
希望本文所述对大家Java程序设计有所帮助。