創(chuàng)建文件夾 //import java.io.*; File myFolderPath = new File(%%1); try { if (!myFolderPath.exists()) { myFolderPath.mkdir(); } } catch (Exception e) { System.out.println("新建目錄操作出錯(cuò)"); e.printStackTrace(); } 2.創(chuàng)建文件
//import java.io.*; File myFilePath = new File(%%1); try { if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); myFile.println(%%2); resultFile.close(); } catch (Exception e) { System.out.println("新建文件操作出錯(cuò)"); e.printStackTrace(); } 3.刪除文件
//import java.io.*; File myDelFile = new File(%%1); try { myDelFile.delete(); } catch (Exception e) { System.out.println("刪除文件操作出錯(cuò)"); e.printStackTrace(); } 4.刪除文件夾
//import java.io.*; File delFolderPath = new File(%%1); try { delFolderPath.delete(); //刪除空文件夾 } catch (Exception e) { System.out.println("刪除文件夾操作出錯(cuò)"); e.printStackTrace(); } 5.刪除一個(gè)文件下夾所有的文件夾
//import java.io.*; File delfile=new File(%%1); File[] files=delfile.listFiles(); for(int i=0;i<files.length;i++){ if(files[i].isDirectory()){ files[i].delete(); } } 6.清空文件夾 //import java.io.*; File delfilefolder=new File(%%1); try { if (!delfilefolder.exists()) { delfilefolder.delete(); } delfilefolder.mkdir(); } catch (Exception e) { System.out.println("清空目錄操作出錯(cuò)"); e.printStackTrace(); } 7.讀取文件
//import java.io.*; // 逐行讀取數(shù)據(jù) FileReader fr = new FileReader(%%1); BufferedReader br = new BufferedReader(fr); String %%2 = br.readLine(); while (%%2 != null) { %%3 %%2 = br.readLine(); } br.close(); fr.close(); 8.寫(xiě)入文件
//import java.io.*; // 將數(shù)據(jù)寫(xiě)入文件 try { FileWriter fw = new FileWriter(%%1); fw.write(%%2); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } 9.寫(xiě)入隨機(jī)文件
//import java.io.*; try { RandomAcessFile logFile=new RandomAcessFile(%%1,"rw"); long lg=logFile.length(); logFile.seek(%%2); logFile.writeByte(%%3); }catch(IOException ioe){ System.out.println("無(wú)法寫(xiě)入文件:"+ioe.getMessage()); } 10.讀取文件屬性
//import java.io.*; // 文件屬性的取得 File af = new File(%%1); if (af.exists()) { System.out.println(f.getName() + "的屬性如下: 文件長(zhǎng)度為:" + f.length()); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目錄" : "不是目錄"); System.out.println(f.canRead() ? "可讀取" : "不"); System.out.println(f.canWrite() ? "是隱藏文件" : ""); System.out.println("文件夾的最后修改日期為:" + new Date(f.lastModified())); } else { System.out.println(f.getName() + "的屬性如下:"); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目錄" : "不是目錄"); System.out.println(f.canRead() ? "可讀取" : "不"); System.out.println(f.canWrite() ? "是隱藏文件" : ""); System.out.println("文件的最后修改日期為:" + new Date(f.lastModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 } 11.寫(xiě)入屬性 //import java.io.*; File filereadonly=new File(%%1); try { boolean b=filereadonly.setReadOnly(); } catch (Exception e) { System.out.println("拒絕寫(xiě)訪問(wèn):"+e.printStackTrace()); } 12.枚舉一個(gè)文件夾中的所有文件
//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.peek()); folderList.removeLast(); File[] files = file.listFiles(); ArrayList<File> fileList = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { %%2=f.getAbsoluteFile(); %%3 } } 13.復(fù)制文件夾
//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); LinkedList<String> folderList2 = new LinkedList<String>(); folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// 如果是子文件夾 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); 2009-5-30 09:52 回復(fù) } } } } catch (Exception e) { //System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } 14.復(fù)制一個(gè)文件夾下所有的文件夾到另一個(gè)文件夾下
//import java.io.*; //import java.util.*; File copyfolders=new File(%%1); File[] copyfoldersList=copyfolders.listFiles(); for(int k=0;k<copyfoldersList.length;k++){ if(copyfoldersList[k].isDirectory()){ ArrayList<String>folderList=new ArrayList<String>(); folderList.add(copyfoldersList[k].getPath()); ArrayList<String>folderList2=new ArrayList<String>(); folderList2.add(%%2+"/"+copyfoldersList[k].getName()); for(int j=0;j<folderList.length;j++){ (new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾 File folders=new File(folderList.get(j)); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList.get(j).endsWith(File.separator)){ temp=new File(folderList.get(j)+"/"+file[i]); } else{ temp=new File(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夾 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch (Exception e) { System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } } } } 15.移動(dòng)文件夾
//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); LinkedList<String> folderList2 = new LinkedList<String>(); folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾 File folders = new File(folderList.peek());
String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); if (!temp.delete()) System.out.println("刪除單個(gè)文件操作出錯(cuò)!"); } if (temp.isDirectory()) {// 如果是子文件夾 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } } } catch (Exception e) { // System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); }
File f = new File(%%1); if (!f.delete()) { for (File file : f.listFiles()) { if (file.list().length == 0) { System.out.println(file.getPath()); file.delete(); } } } 16.移動(dòng)一個(gè)文件夾下所有的文件夾到另一個(gè)目錄下 //import java.io.*; //import java.util.*; File movefolders=new File(%%1); File[] movefoldersList=movefolders.listFiles(); for(int k=0;k<movefoldersList.length;k++){ if(movefoldersList[k].isDirectory()){ ArrayList<String>folderList=new ArrayList<String>(); folderList.add(movefoldersList[k].getPath()); ArrayList<String>folderList2=new ArrayList<String>(); folderList2.add(%%2+"/"+movefoldersList[k].getName()); for(int j=0;j<folderList.length;j++){ (new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾 File folders=new File(folderList.get(j)); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList.get(j).endsWith(File.separator)){ temp=new File(folderList.get(j)+"/"+file[i]); } else{ temp=new File(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); temp.delete(); } if(temp.isDirectory()){//如果是子文件夾 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch (Exception e) { System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } } movefoldersList[k].delete(); } } 17.以一個(gè)文件夾的框架在另一個(gè)目錄創(chuàng)建文件夾和空文件
//import java.io.*; //import java.util.*; boolean b=false;//不創(chuàng)建空文件 ArrayList<String>folderList=new ArrayList<String>(); folderList.add(%%1); ArrayList<String>folderList2=new ArrayList<String>(); folderList2.add(%%2); for(int j=0;j<folderList.length;j++){ (new File(folderList2.get(j))).mkdirs(); //如果文件夾不存在 則建立新文件夾 File folders=new File(folderList.get(j)); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList.get(j).endsWith(File.separator)){ temp=new File(folderList.get(j)+"/"+file[i]); } else{ temp=new File(folderList.get(j)+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ if (b) temp.createNewFile(); } if(temp.isDirectory()){//如果是子文件夾 folderList.add(folderList.get(j)+"/"+file[i]); folderList2.add(folderList2.get(j)+"/"+file[i]); } } } catch (Exception e) { System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } } 18.復(fù)制文件
//import java.io.*; int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在時(shí) FileInputStream inStream = new FileInputStream(oldfile); //讀入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字節(jié)數(shù) 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("復(fù)制單個(gè)文件操作出錯(cuò)"); e.printStackTrace(); } 19.復(fù)制一個(gè)文件夾下所有的文件到另一個(gè)目錄
//import java.io.*; File copyfiles=new File(%%1); File[] files=copyfiles.listFiles(); for(int i=0;i<files.length;i++){ if(!files[i].isDirectory()){ int bytesum = 0; int byteread = 0; try { InputStream inStream = new FileInputStream(files[i]); //讀入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字節(jié)數(shù) 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } catch (Exception e) { System.out.println("復(fù)制單個(gè)文件操作出錯(cuò)"); e.printStackTrace(); } } } 20.提取擴(kuò)展名
String %%2=%%1.substring(%%1.lastIndexOf(".")+1); 2009-5-30 09:53 回復(fù) 提取文件名 String %%2=%%1.substring(%%1.lastIndexOf("\\")+1); 22.提取文件路徑
String %%2=%%1.substring(0,%%1.lastIndexOf("\\")); 23.替換擴(kuò)展名
//import java.io.*; File replaceExt=new File(%%1); replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2); 25.移動(dòng)文件
//import java.io.*; int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在時(shí) InputStream inStream = new FileInputStream(oldfile); //讀入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字節(jié)數(shù) 文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("復(fù)制單個(gè)文件操作出錯(cuò)"); e.printStackTrace(); } 26.移動(dòng)一個(gè)文件夾下所有文件到另一個(gè)目錄 //import java.io.*; File movefile=new File(%%1); File[] movefiles=movefile.listFiles(); for(int i=0;i<movefiles.length;i++){ if(movefiles[i].isFile()){ int bytesum = 0; int byteread = 0; File oldfile = new File(movefiles[i]); try { if (oldfile.exists()) { //文件存在時(shí) InputStream inStream = new FileInputStream(oldfile); //讀入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字節(jié)數(shù) 文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("復(fù)制單個(gè)文件操作出錯(cuò)"); e.printStackTrace(); } } } 27.指定目錄下搜索文件
//import java.io.*; String filter="*.*"; String path=%%1; File file = new File(path); if(file.exists()) { if(file.isDirectory()) { File[] fileArray = file.listFiles(); for(File f:fileArray) { if(f.isDirectory()) { doSearch(filter,f.getPath()); } else { if(f.getName().indexOf(filter) >= 0) { countFiles++; result.append(f.getPath() + "\r\n"); } } statusShow1.setText(f.getPath()); } statusShow2.setText("The numbers of files had been found:" + countFiles); } else { System.out.println("Couldn't open the path!"); } } else { System.out.println("The path had been apointed was not Exist!"); } 28.打開(kāi)對(duì)話框
//import java.io.*; //import javax.swing.*; JFileChooser Jfc = new JFileChooser(); //建立選擇檔案對(duì)話方塊盒 Jfc if (Jfc.isFileSelectionEnabled()) { File %%1 = Jfc.getSelectedFile(); } 29.文件分割
//import java.io.* try { File f=new File(%%1); FileInputStream fileInputStream = new FileInputStream(f); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); String strFileName = f.getName(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1")); fileOutputStream.write(buffer,0,buffer.length/2); fileOutputStream.close(); fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2")); fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2); fileOutputStream.close(); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("using FileStreamDemo src des"); e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } 30.文件合并
//import java.io.* String strFileName = %%1.substring(%%1.LastIndexOf("\\") + 1); try { FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1")); FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2")); byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()]; FileInputStream.read(buffer, 0, fileInputStream1.available()); FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available()); fileInputStream.close(); fileInputStream2.close(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName)); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); catch(IOException e){ e.printStackTrace(); } 31.文件簡(jiǎn)單加密 //import java.io.* try { File f=new File((new File(%%1)).getPath()+"\\enc_"+(new File(%%1)).getName().split("http://")[1]); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2+"\\"+strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(int i=0;i<buffer.length;i++) { int ibt=buffer[i]; ibt+=100; ibt%=256; buffer[i]=(byte)ibt; } FileOutputStream fileOutputStream = new FileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } 32.文件簡(jiǎn)單解密
//import java.io.* try { File f=new File(%%1); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2+"\\enc_"+strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(int i=0;i<buffer.length;i++) { int ibt=buffer[i]; ibt-=100; ibt+=256; ibt%=256; buffer[i]=(byte)ibt; } FileOutputStream fileOutputStream = new FileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } 33.寫(xiě)入ini文件屬性
//import java.io.*; //import java.util.*; //import java.util.regex.*; if (configMap == null) { String WriteBuffer = ""; configMap = new HashMap<String, Serializable>(); String strLine = null; String currentNode = null; String previousNode = null; Vector<Properties> vec = new Vector<Properties>(); int row = 0; FileReader fileReader = null; try { fileReader = new FileReader("Config.ini"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(fileReader); try { while ((strLine = bufferedReader.readLine()) != null) { String oneLine = strLine.trim(); if (oneLine.length() >= 1) { Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]"); int nodelen = oneLine.split("[;]").length; String[] strArray1 = new String[4];
if (nodelen == 1) { oneLine = oneLine.split("[;]")[0].trim(); } else if (nodelen == 2) { strArray1[3] = oneLine.split("[;]")[1].trim(); oneLine = oneLine.split("[;]")[0].trim(); } Matcher m = p.matcher(oneLine); if (m.matches()) { strArray1[0] = "@Node"; strArray1[1] = oneLine; strArray1[2] = ""; } else { int keylen = oneLine.split("=").length; if (keylen == 1) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = ""; } else if (keylen == 2) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = oneLine.split("=")[1]; } else { strArray1[0] = "@ElementError"; strArray1[1] = ""; strArray1[2] = ""; strArray1[3] = ""; } } if (strArray1[0].equals("@Node")) { previousNode = currentNode; currentNode = strArray1[1]; if (row > 0) { configMap.put(previousNode, vec.elementAt(0)); vec.clear(); row = 0; } WriteBuffer += (oneLine + "\r\n"); } else if (strArray1[0].equals("@Key") && row == 0) { Properties ht = new Properties(); ht.setProperty(strArray1[1], strArray1[2]); if (strArray1[1].equals(%%1)) { WriteBuffer += (%%1+"=" + %%2 + "\r\n"); } else WriteBuffer += (oneLine + "\r\n"); vec.add(0, ht); row++; } else if (strArray1[0].equals("@Key") && row > 0) { Properties ht2 = new Properties(); ht2.put(strArray1[1], strArray1[2]); vec.clear(); vec.add(0, ht2); WriteBuffer += (oneLine + "\r\n"); row++; } } } configMap.put(currentNode, vec.elementAt(0)); } catch (FileNotFoundException e) { configMap = null; e.printStackTrace(); } catch (IOException e) { configMap = null; e.printStackTrace(); } finally { vec.clear(); try { bufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter fw = new FileWriter("Config.ini"); fw.write(WriteBuffer); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } 2009-5-30 09:54 回復(fù) 34.讀取ini文件屬性
//import java.io.*; //import java.util.*; //import java.util.regex.*; //private HashMap configMap=null; private Map<String, Serializable> configMap=null; String %%2=null; if (configMap == null) { configMap = new HashMap<String, Serializable>(); String strLine = null; String currentNode = null; String previousNode = null; Vector<Properties> vec = new Vector<Properties>(); int row = 0; FileReader fileReader = null; try { fileReader = new FileReader("Config.ini"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(fileReader); try { while ((strLine = bufferedReader.readLine()) != null) { String oneLine = strLine.trim(); if (oneLine.length() >= 1) { Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]"); int nodelen = oneLine.split("[;]").length; String[] strArray1 = new String[4]; if (nodelen == 1) { oneLine = oneLine.split("[;]")[0].trim(); } else if (nodelen == 2) { strArray1[3] = oneLine.split("[;]")[1].trim(); oneLine = oneLine.split("[;]")[0].trim(); } Matcher m = p.matcher(oneLine); if (m.matches()) { strArray1[0] = "@Node"; strArray1[1] = oneLine; strArray1[2] = ""; } else { int keylen = oneLine.split("=").length; if (keylen == 1) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = ""; } else if (keylen == 2) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = oneLine.split("=")[1]; } else { strArray1[0] = "@ElementError"; strArray1[1] = ""; strArray1[2] = ""; strArray1[3] = ""; } } if (strArray1[0].equals("@Node")) { previousNode = currentNode; currentNode = strArray1[1]; if (row > 0) { configMap.put(previousNode, vec.elementAt(0)); vec.clear(); row = 0; } } else if (strArray1[0].equals("@Key") && row == 0) { Properties ht = new Properties(); ht.setProperty(strArray1[1], strArray1[2]); if(strArray1[1].equals(%%1)) { %%2=strArray1[2]; return; } vec.add(0, ht); row++; } else if (strArray1[0].equals("@Key") && row > 0) { Properties ht2 = new Properties(); ht2.put(strArray1[1], strArray1[2]); vec.clear(); vec.add(0, ht2); row++; } } } configMap.put(currentNode, vec.elementAt(0)); } catch (FileNotFoundException e) { configMap = null; e.printStackTrace(); } catch (IOException e) { configMap = null; e.printStackTrace(); } finally { vec.clear(); try { bufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } 35.合并一個(gè)文件下所有的文件
File combinefiles=new File(%%1); File[] files=combinefiles.listFiles(); FileOutputStream fs; try { fs=new FileOutputStream(new File(%%2)); } catch(IOException e){ e.printStackTrace(); } for(int i=0;i<files.length;i++){ if(files[i].isFile()){ int bytesum=0; int byteread=0; try { FileInputStream inStream=new FileInputStream(files[i]); byte[] buffer = new byte[5120]; int length; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread; fs.write(buffer,0,byteread); } inStream.close(); } catch(Exception e){ //復(fù)制文件出錯(cuò) e.printStackTrace(); } } } try { fs.close(); } catch(IOException e){ { e.printStackTrace(); } 寫(xiě)入ini文件屬性 //import java.io.*; //import java.util.*; //import java.util.regex.*; //private HashMap configMap=null; private Map<String, Serializable> configMap=null; if(configMap==null) { String strLine=null; String currentNode=null; String previousNode=null; Vector<Properties> vec=new Vector<Properties>(); int row=0; FileReader fileReader = null; try { fileReader = new FileReader(%%1); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader bufferedReader=new BufferedReader(fileReader); try { while((strLine=bufferedReader.readLine())!=null) { String oneLine=strLine.trim(); if(oneLine.length()>=1) { Pattern p=Pattern.compile("\\[\\s*.*\\s*\\]"); int nodelen=oneLine.split("[;]").length; String[] strArray1=new String[4]; if(nodelen==1) { oneLine=oneLine.split("[;]")[0].trim(); } else if(nodelen==2) { strArray1[3]=oneLine.split("[;]")[1].trim(); oneLine=oneLine.split("[;]")[0].trim(); } Matcher m=p.matcher(oneLine); if(m.matches()) { strArray1[0]="@Node"; strArray1[1]=oneLine; strArray1[2]=""; } else { int keylen=oneLine.split("=").length; if(keylen==1) { strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=""; } else if(keylen==2) { strArray1[0]="@Key"; strArray1[1]=oneLine.split("=")[0]; strArray1[2]=oneLine.split("=")[1]; } else { strArray1[0]="@ElementError"; strArray1[1]=""; strArray1[2]=""; strArray1[3]=""; } } if(strArray1[0].equals("@Node")) { previousNode=currentNode; currentNode=strArray1[1]; if(row>0) { configMap.put(previousNode,vec.elementAt(0)); //"size:"+configMap.size() vec.clear(); row=0; } } else if(strArray1[0].equals("@Key") && row==0) { Properties ht=new Properties(); ht.setProperty(strArray1[1],strArray1[2]); vec.add(0,ht); row++; } else if(strArray1[0].equals("@Key") && row>0) { Properties ht2=new Properties(); ht2.put(strArray1[1],strArray1[2]); vec.clear(); vec.add(0,ht2); row++; } } } configMap.put(currentNode,vec.elementAt(0)); } catch (FileNotFoundException e) { configMap=null; e.printStackTrace(); } catch (IOException e) { configMap=null; e.printStackTrace(); } finally { vec.clear(); try {
bufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } String nodeKey="["+%%2+"]"; Properties ht=null; if(configMap.containsKey(nodeKey)) { ht=(Properties)configMap.get(nodeKey); } else { ht=(Properties)configMap.put(nodeKey,%%3); } try { ht.setProperty(%%3,%%4); } catch (NullPointException e) { e.printStackTrace(); } FileWriter fw= null; BufferedWriter bw= null; try { fw = new FileWriter(%%1); bw=new BufferedWriter(fw); } catch (IOException e) { e.printStackTrace(); } Set keys=configMap.keySet(); Iterator ite=keys.iterator(); while(ite.hasNext()) { String oneKey=(String)ite.next(); try { bw.write(oneKey+"\n"); } catch (IOException e) { e.printStackTrace(); } ht=(Properties)configMap.get(oneKey); ht.list(new PrintWriter(bw,true)); } 37.獲得當(dāng)前路徑
String %%1=this.getClass().getResource("/").getPath(); 38.讀取XML數(shù)據(jù)庫(kù)
//import java.io.*; //import javax.xml.parsers.*; //import org.xml.sax.*; //import org.w3c.dom.*; private Document document; File xml_file=new File(%%1); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); document=builder.parse(xml_file); } catch(Exception e) { e.printStackTrace(); } String subNodeTag=%%2; Element rootNode=document.getDocumentElement(); //%%2="serverList" //%%4="id" //%%6="port" //%%3="server" //%%5="ipaddr" NodeList nlist=rootNode.getElementsByTagName(subNodeTag); int len=nlist.getLength(); Node x=null; for(int i=0;i<len;i++) { x=nlist.item(i); String getNodeAttrValue=null; NamedNodeMap attrList=node.getAttributes(); for(int j=0;j<attrList.getLength();j++) { if(attrList.item(j).getNodeName().compareTo(%%7)==0) { getNodeAttrValue=attrList.item(j).getNodeValue(); break; } } if(getNodeAttrValue.compareTo(%%8)==0) break; } String %%9=null; if(x!=null) { NodeList nlist=node.getChildNodes(); int len=nlist.getLength(); Node currentNode; String nodeName; for(int i=0;i<len;i++) { currentNode=nlist.item(i); nodeName=currentNode.getNodeName(); if(nodeName.equals(%%5)==0) { %%9=document.getElementValue(currentNode); break; } } } 寫(xiě)入XML數(shù)據(jù)庫(kù) //import java.io.*; //import javax.xml.parsers.*; //import org.xml.sax.*; //import org.w3c.dom.*; //import javax.xml.transform.*; //import javax.xml.transform.dom.*; //import javax.xml.transform.stream.*; private Document document; private Element node; File xml_file=new File(%%1); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); document=builder.parse(xml_file); } catch(Exception e) { e.printStackTrace(); } String subNodeTag=%%2; Element rootNode=document.getDocumentElement(); //%%2="serverList" //%%4="id" //%%6="port" //%%3="server" //%%5="ipaddr" NodeList nlist=rootNode.getElementByTagName(subNodeTag); node=document.createElement(%%3); node.setAttribute(%%4,nlist.getLength()+1).toString()); node.appendChild(document.createTextNode("\n"); Element ipNode=document.createElement(%%5); ipNode.appendChild(document.createTextNode(%%8)); node.appendChild(ipNode); node.appendChild(document,createTextNode("\n"); Element port=document.createElement(%%6); port.appendChild(document.createTextNode(%%9)); node.appendChild(port); node.appendChild(document,createTextNode("\n"); nlist.appendChild(node); TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=null; try { transformer=tFactory.newTransformer(); DOMSource source=new DOMSource(document); StreamResult result=new StreamResult(xml_file); transformer.transform(source,result); } catch(Exception e) { e.printStackTrace(); } 40.ZIP壓縮文件
//import java.io.*; //import java.util.zip.*; //創(chuàng)建文件輸入流對(duì)象 FileInputStream fis=new FileInputStream(%%1); //創(chuàng)建文件輸出流對(duì)象 FileOutputStream fos=new FileOutputStream(%%2); //創(chuàng)建ZIP數(shù)據(jù)輸出流對(duì)象 ZipOutputStream zipOut=new ZipOutputStream(fos); //創(chuàng)建指向壓縮原始文件的入口 ZipEntry entry=new ZipEntry(args[0]); zipOut.putNextEntry(entry); //向壓縮文件中輸出數(shù)據(jù) int nNumber; byte[] buffer=new byte[1024]; while((nNumber=fis.read(buffer))!=-1) zipOut.write(buffer,0,nNumber); //關(guān)閉創(chuàng)建的流對(duì)象 zipOut.close(); fos.close(); fis.close(); } catch(IOException e) { System.out.println(e); } 41.獲得應(yīng)用程序完整路徑 String %%1=System.getProperty("user.dir"); 42.ZIP解壓縮
//import java.io.*; //import java.util.zip.*; try{ //創(chuàng)建文件輸入流對(duì)象實(shí)例 FileInputStream fis=new FileInputStream(%%1); //創(chuàng)建ZIP壓縮格式輸入流對(duì)象實(shí)例 ZipInputStream zipin=new ZipInputStream(fis); //創(chuàng)建文件輸出流對(duì)象實(shí)例 FileOutputStream fos=new FileOutputStream(%%2); //獲取Entry對(duì)象實(shí)例 ZipEntry entry=zipin.getNextEntry(); byte[] buffer=new byte[1024]; int nNumber; while((nNumber=zipin.read(buffer,0,buffer.length))!=-1) fos.write(buffer,0,nNumber); //關(guān)閉文件流對(duì)象 zipin.close(); fos.close(); fis.close(); } catch(IOException e) { System.out.println(e); } 43.遞歸刪除目錄中的文件
//import java.io.*; //import java.util.*; ArrayList<String> folderList = new ArrayList<String>(); folderList.add(%%1); for (int j = 0; j < folderList.size(); j++) { File file = new File(folderList.get(j)); File[] files = file.listFiles(); ArrayList<File> fileList = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { f.delete(); } } 43.ZIP壓縮文件夾
//import java.io.*; //import org.apache.tools.zip.ZipOutputStream; //這個(gè)包在ant.jar里,要到官方網(wǎng)下載 //import java.util.zip.*; try { String zipFileName = %%2; //打包后文件名字 File f=new File(%%1); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); String base= ""; if (f.isDirectory()) { File[] fl = f.listFiles(); out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } }else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; while ( (b = in.read()) != -1) { out.write(b); } in.close(); } out.close(); }catch (Exception ex) { ex.printStackTrace(); } 44.Java驗(yàn)證DTD //import java.io.*; //import javax.xml.parsers.*; //import org.xml.sax.*; //import org.w3c.dom.*; try { InputStream in=new FileInputStream(filePath); SAXReader saxReader = new SAXReader(); this.document = saxReader.read(in); DocumentBuilderFactory factory = null; factory = DocumentBuilderFactory.newInstance(); //進(jìn)行dtd檢查 factory.setValidating(true); } catch (Exception e) { } 45.驗(yàn)證Schema //import java.io.*; //import javax.xml.parsers.*; //import org.xml.sax.*; //import org.w3c.dom.*; String xsdFileName = \"Q:\\\\_dev_stu\\\\xsdtest\\\\src\\\\note.xsd\"; try { //創(chuàng)建默認(rèn)的XML錯(cuò)誤處理器 XMLErrorHandler errorHandler = new XMLErrorHandler(); //獲取基于 SAX 的解析器的實(shí)例 SAXParserFactory factory = SAXParserFactory.newInstance(); //解析器在解析時(shí)驗(yàn)證 XML 內(nèi)容。 factory.setValidating(true); //指定由此代碼生成的解析器將提供對(duì) XML 名稱空間的支持。 factory.setNamespaceAware(true); //使用當(dāng)前配置的工廠參數(shù)創(chuàng)建 SAXParser 的一個(gè)新實(shí)例。 SAXParser parser = factory.newSAXParser(); //創(chuàng)建一個(gè)讀取工具 SAXReader xmlReader = new SAXReader(); //獲取要校驗(yàn)xml文檔實(shí)例 Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName)); //設(shè)置 XMLReader 的基礎(chǔ)實(shí)現(xiàn)中的特定屬性。核心功能和屬性列表可以在 [url]http://sax./?selected=get-set[/url] 中找到。 parser.setProperty( \"http://java./xml/jaxp/properties/schemaLanguage", \"http://www./2001/XMLSchema"); parser.setProperty( \"http://java./xml/jaxp/properties/schemaSource", \"file:\" + xsdFileName); //創(chuàng)建一個(gè)SAXValidator校驗(yàn)工具,并設(shè)置校驗(yàn)工具的屬性 SAXValidator validator = new SAXValidator(parser.getXMLReader()); //設(shè)置校驗(yàn)工具的錯(cuò)誤處理器,當(dāng)發(fā)生錯(cuò)誤時(shí),可以從處理器對(duì)象中得到錯(cuò)誤信息。 validator.setErrorHandler(errorHandler); //校驗(yàn) validator.validate(xmlDocument); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); //如果錯(cuò)誤信息不為空,說(shuō)明校驗(yàn)失敗,打印錯(cuò)誤信息 if (errorHandler.getErrors().hasContent()) { System.out.println(\"XML文件通過(guò)XSD文件校驗(yàn)失??!\"); writer.write(errorHandler.getErrors()); } else { System.out.println(\"Good! XML文件通過(guò)XSD文件校驗(yàn)成功!\"); } } catch (Exception ex) { System.out.println(\"XML文件: \" + xmlFileName + \" 通過(guò)XSD文件:\" + xsdFileName + \"檢驗(yàn)失敗。\n原因: \" + ex.getMessage ());
ex.printStackTrace(); } } 46.Grep //import java.util.regex.*; //import java.io.*; /** * Simple implementation of the ubiquitous grep command. * First argument is the regular expression to search for (remember to * quote and/or escape as appropriate). All following arguments are * filenames to read and search for the regular expression. * * Created: April, 2002 * @author Ron Hitchens (ron@ronsoft.com) * @version $Id: SimpleGrep.java,v 1.1 2002/05/07 02:21:08 ron Exp $ */ public static void main (String [] argv) throws Exception { if (argv.length < 2) { // 如果參數(shù)行沒(méi)有輸入?yún)?shù),結(jié)束程序 System.out.println ("Usage: regex file [ ... ]"); return; } Pattern pattern = Pattern.compile (argv [0]); // 第一個(gè)參數(shù)為需要匹配的字符串 Matcher matcher = pattern.matcher (""); // 一次讀取各個(gè)文件 for (int i = 1; i < argv.length; i++) { String file = argv [i]; // 第2個(gè)參數(shù)開(kāi)始,均為文件名。 BufferedReader br = null; String line; try { br = new BufferedReader (new FileReader (file)); // 打開(kāi)文件 } catch (IOException e) { // 沒(méi)有打開(kāi)文件,則產(chǎn)生異常 System.err.println ("Cannot read '" + file + "': " + e.getMessage()); continue; } while ((line = br.readLine()) != null) { // 讀入一行,直到文件結(jié)束 matcher.reset (line); // 匹配字符串 if (matcher.find()) { // 如果有匹配的字符串,則輸出 System.out.println (file + ": " + line); } } br.close(); // 關(guān)閉文件 } } 2009-5-30 12:17 回復(fù) 47.直接創(chuàng)建多級(jí)目錄 //import java.io.*; File f=new File(%%1); f.mkdirs(); 48.批量重命名 //import java.io.*; File target = new File("%%1"); String[] files = target.list(); File f = null; String filename = null; for (String file : files) { f = new File(fl, file); filename = f.getName(); if (filename.substring(filename.lastIndexOf (".")).equalsIgnoreCase(
"%%2")) { f.renameTo(new File(target.getAbsolutePath(), filename.replace(
"%%2", "%%3"))); // 這里可以反復(fù)使用replace替換,當(dāng)然也可以使用正則表達(dá)式來(lái) 替換了 ".txt" ".bat"
} } 2009-5-31 10:56 回復(fù) 49.文本查找替換 //import java.nio.*; String s1=%%1; String s2=%%2; String s3=%%3; int pos=%%4; /*變量i和j分別表示主串和模式串中當(dāng)前字符串的位置,k表示匹配次數(shù)*/ int i,j,k=0; i = pos; j = 0; //將s1轉(zhuǎn)化成StringBuffer型進(jìn)行操作 repStr = new StringBuffer(s1); while(i<repStr.length()&&j<s2.length()) { if(repStr.charAt(i) == s2.charAt(j)) { ++i; ++j; if(j==s2.length()) { /*j=s2.length()表示字符串匹配成功,匹配次數(shù)加1,此外對(duì)主串進(jìn)行字符串替換*/ k = k+1; repStr.replace(i-j,i,s3); //將j進(jìn)行重新賦值開(kāi)始新的比較 j = 0; } } else {i = i-j+1; j = 0;} } return k; 50.文件關(guān)聯(lián) //import java.io.*; try { Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]" } catch (IOException e) { e.printStackTrace(); } 52.設(shè)置JDK環(huán)境變量 @echo off IF EXIST %1\bin\java.exe ( rem 如輸入正確的 Java2SDK 安裝目錄,開(kāi)始設(shè)置環(huán)境變量 @setx JAVA_HOME %1 @setx path %path%;%JAVA_HOME%\bin @setx classpath %classpath%;. @setx classpath %classpath%;%JAVA_HOME%\lib\tools.jar @setx classpath %classpath%;%JAVA_HOME%\lib\dt.jar @setx classpath %classpath%;%JAVA_HOME%\jre\lib\rt.jar @echo on @echo Java 2 SDK 環(huán)境參數(shù)設(shè)置完畢,正常退出。 ) ELSE ( IF "%1"=="" ( rem 如沒(méi)有提供安裝目錄,提示之后退出 @echo on @echo 沒(méi)有提供 Java2SDK 的安裝目錄,不做任何設(shè)置,現(xiàn)在退出環(huán)境變量設(shè)置。 ) ELSE ( rem 如果提供非空的安裝目錄但沒(méi)有bin\java.exe,則指定的目錄為錯(cuò)誤的目錄 @echo on @echo 非法的 Java2SDK 的安裝目錄,不做任何設(shè)置,現(xiàn)在退出環(huán)境變量設(shè)置。 ) ) //http:///projects/jregistrykey/ //import ca.beq.util.win32.registry.*; //import java.util.*; 1.打開(kāi)鍵 RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
2.添加鍵 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
r.create(); 9.寫(xiě)入字符串值 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data"); r.setValue(v); 6.獲取DWORD值 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); if(r.hasValue("myValue")) { RegistryValue v = r.getValue("myValue"); v.setType(ValueType.REG_DWORD); } // if 53.選擇文件夾對(duì)話框 /* import java.io.*; import javax.swing.*; */ JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); } public String getDescription() { return "GIF Images"; } }); int r = chooser.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); // label.setIcon(new ImageIcon(name)); } 54.刪除空文件夾
//import java.io.*; File f=new File(%%1); if (isFolerNull(f)) { for (File file :f.listFiles()) { if (file.list().length == 0) { System.out.println(file.getPath()); file.delete(); } } } 55.發(fā)送數(shù)據(jù)到剪貼板
//import java.awt.*; //import java.awt.datatransfer.*; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(%%1); clipboard.setContents(tText, null); 56.從剪貼板中取數(shù)據(jù) //import java.awt.*; //import java.awt.datatransfer.*; // 取得系統(tǒng)剪貼板里可傳輸?shù)臄?shù)據(jù)構(gòu)造的Java對(duì)象 Transferable t = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { // 因?yàn)樵档募糍N板里有多種信息, 如文字, 圖片, 文件等 // 先判斷開(kāi)始取得的可傳輸?shù)臄?shù)據(jù)是不是文字, 如果是, 取得這些文字 String s = (String) t .getTransferData(DataFlavor.stringFlavor); // 同樣, 因?yàn)門(mén)ransferable中的DataFlavor是多種類(lèi)型的, // 所以傳入DataFlavor這個(gè)參數(shù), 指定要取得哪種類(lèi)型的Data. System.out.println(s); } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } 57.獲取文件路徑的父路徑
String %%2=%%1.substring(0,%%1.lastIndexOf("\\")); 58.創(chuàng)建快捷方式
//import java.io.*; try { PrintWriter pw=new PrintWriter(new FileOutputStream("C:/a.bat")); pw.println(%%1);"C:/a.txt" pw.close(); } catch(IOException e){ e.printStackTrace(); } 59.彈出快捷菜單
//MouseEvent e JPopupMenu jpm=new JPopupMenu(); show(jpm,x,y); 60.文件夾復(fù)制到整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); LinkedList<String> folderList2 = new LinkedList<String>(); folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夾不存在 則建立新文件夾 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// 如果是子文件夾 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } } } catch (Exception e) { //System.out.println("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } 61.文件夾移動(dòng)到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 62.目錄下所有文件夾復(fù)制到整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 63.目錄下所有文件夾移動(dòng)到整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 64.目錄下所有文件復(fù)制到整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 65.目錄下所有文件移動(dòng)到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 66.對(duì)目標(biāo)壓縮文件解壓縮到指定文件夾
/* import java.io.*; import java.util.*; import javax.swing.*; */ 67.創(chuàng)建目錄副本整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("請(qǐng)選擇源路徑"); // 建立選擇檔案對(duì)話 方塊盒 Jfc
if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("請(qǐng)選擇目標(biāo)路徑"); // 建立選擇檔案對(duì)話方塊盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 68.打開(kāi)網(wǎng)頁(yè)
//import java.io.*; try{ String command = "C:\\Program Files\\Internet Explorer\\Iexplore.exe "+%%1; Runtime.getRuntime().exec(command); } catch (IOException ex) { ex.printStackTrace(); } 69.刪除空文件夾整合操作
/* import java.io.*; import java.util.*; import javax.swing.*; */ 70.獲取磁盤(pán)所有分區(qū)后再把光驅(qū)盤(pán)符去除(用"\0"代替),把結(jié)果放在數(shù)組allfenqu[] 中,數(shù)組中每 個(gè)元素代表一個(gè)分區(qū)盤(pán)符,不包括 :\\ 這樣的路徑,allfenqu[]數(shù)組開(kāi)始時(shí)存放的是所有盤(pán)符。
當(dāng)我用這樣的代碼測(cè)試結(jié)果是正確的,光驅(qū)盤(pán)符會(huì)被去掉: String root; //root代表盤(pán)符路徑 for(i=0;i<20;i++) //0-20代表最大的盤(pán)符數(shù) { root.Format("%c:\\",allfenqu[i]); if(GetDriveType(root)==5) allfenqu[i]='\0'; } 但我用這樣的代碼時(shí)結(jié)果卻無(wú)法去掉光驅(qū)盤(pán)符,allfenqu[]中還是會(huì)包含光驅(qū)盤(pán)符:
String root; for(i=0;i<20;i++) { root=allfenqu[i]+":\\"; if(GetDriveType(root)==5) allfenqu[i]='\0'; } 71.激活一個(gè)程序或程序關(guān)聯(lián)的文件
//import java.io.*; try { Runtime.getRuntime().exec(%%1); } catch (IOException e) { e.printStackTrace(); } 72.HTTP下載
public class DownloadCSVFileAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
try { String fileName = request.getParameter( "fileName "); long maID = Long.parseLong(request.getParameter( "maID ")); String filePath = request.getSession().getServletContext ().getRealPath( "/ ")+ "csv/ "+maID+ "/ "+fileName;
File fdown = new File(filePath); int filelength = Integer.parseInt(String.valueOf (fdown.length()));
//下載類(lèi)型 response.setContentType( "application/text;charset=GB2312 "); response.setHeader( "Content-Dispositon ", "attachment;filename= 銷(xiāo)售詳細(xì)記錄.csv "); //銷(xiāo)售詳細(xì)記錄.csv是我想要的下載文件的文件名,但是下載對(duì)話框中顯
示的是 downLoadCSVFile.do
response.setContentLength(filelength); byte b[]=new byte[filelength]; FileInputStream fi=new FileInputStream(fdown); OutputStream o=response.getOutputStream(); int n = 0; while((n=fi.read(b))!=-1) { o.write(b,0,n); } fi.close(); o.close(); return null; }catch (Exception e) { request.setAttribute( "ERROR ", e); return mapping.findForward( "error "); } } } 對(duì)應(yīng)的下載類(lèi)型
private String getContentType(String fileName) { String fileNameTmp = fileName.toLowerCase(); String ret = "";
if (fileNameTmp.endsWith("txt")) { ret = "text/plain"; } if (fileNameTmp.endsWith("gif")) { ret = "image/gif"; } if (fileNameTmp.endsWith("jpg")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("jpeg")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("jpe")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("zip")) { ret = "application/zip"; } if (fileNameTmp.endsWith("rar")) { ret = "application/rar"; } if (fileNameTmp.endsWith("doc")) { ret = "application/msword"; } if (fileNameTmp.endsWith("ppt")) { ret = "application/vnd.ms-powerpoint"; } if (fileNameTmp.endsWith("xls")) { ret = "application/vnd.ms-excel"; } if (fileNameTmp.endsWith("html")) { ret = "text/html"; } if (fileNameTmp.endsWith("htm")) { ret = "text/html"; } if (fileNameTmp.endsWith("tif")) { ret = "image/tiff"; } if (fileNameTmp.endsWith("tiff")) { ret = "image/tiff"; } if (fileNameTmp.endsWith("pdf")) { ret = "application/pdf"; } return ret; } 2009-5-31 11:09 回復(fù) 73.FTP下載 /* import sun.net.ftp.FtpClient; import java.io.*; import sun.net.*; */ //如果文件在某個(gè)目錄下,則加入fc.cd("foodir"); //比如要下載ftp://ftp.xx.com/index.html則: try { FtpClient fc=new FtpClient("ftp.xx.com"); fc.login("username","888888"); int ch; File fi = new File("c:\\index.html"); RandomAccessFile getFile = new RandomAccessFile(fi,"rw"); getFile.seek(0); TelnetInputStream fget=fc.get("index.html"); DataInputStream puts = new DataInputStream(fget); while ((ch = puts.read()) >= 0) { getFile.write(ch); } fget.close(); getFile.close(); fc.closeServer(); } catch (IOException ex) { ex.printStackTrace();
} 74.寫(xiě)圖像到剪切板 setClipboardImage
/* import java.awt.*; import java.awt.datatransfer.*; import java.io.*; */ private final Image image; Transferable trans = new Transferable() { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor); } public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) return image; throw new UnsupportedFlavorException(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null); 75.從剪貼板復(fù)制圖像到窗體
76.刪除文件夾下的所有文件且不刪除文件夾下的文件夾
//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.peek()); folderList.removeLast(); File[] files = file.listFiles(); ArrayList<File> fileList = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { f.delete(); } } File() 構(gòu)造函數(shù),一般是依據(jù)文件所在的指定位置來(lái)創(chuàng)建文件對(duì)象 canWrite() 返回文件是否可以讀寫(xiě) canRead() 返回文件是否可讀 compareTo(File pathname)檢查文件路徑間的順序 createNewFile() 當(dāng)文件不存在時(shí)生成文件 delete() 從文件系統(tǒng)內(nèi)刪除該文件 deleteOnExit() 程序順利結(jié)束時(shí)刪除文件 equals(Object obj) 檢查特定對(duì)象的路徑名是否相等 exists() 判斷文件是否存在 getAbsoluteFile() 返回文件完整路徑的File實(shí)例 getAbsolutePath() 返回文件完整路徑 getName() 返回文件名稱 getParent() 返回文件父目錄路徑 getPath() 返回文件路徑字符串 getParentFile() 返回文件所在文件夾的路徑 hashCode() 返回文件哈希碼 isDirectory() 判斷該路徑指示的是否是目錄 isFile() 判斷該路徑指示的是否是文件 lastModified() 返回該文件最后更改時(shí)間標(biāo)志 length() 返回文件長(zhǎng)度 list() 返回文件和目錄清單 mkdir() 生成指定的目錄 renameTo(File dest) 更改文件名字 setReadOnly() 將文件設(shè)置為可讀 toString() 返回文件狀態(tài)的字符串 toURL() 將文件的路徑字符串轉(zhuǎn)換成URL |
|
來(lái)自: 懷舊妞妞 > 《File類(lèi)》