Java 文件操作大全


1.创建文件夹 //import java.io.*; File myFolderPath = new File(%%1); try { if (!myFolderPath.exists()) { myFolderPath.mkdir(); } } catch (Exception e) { System.out.println("新建目录操作出错"); e.printStackTrace(); } 2.创建文件 //import java.io.*; File myFilePath = new File(%%1); try { if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); myFile.println(%%2); myFile.flush(); resultFile.close(); } catch (Exception e) { System.out.println("新建文件操作出错"); e.printStackTrace(); } 3.删除文件 //import java.io.*; File myDelFile = new File(%%1); try { myDelFile.delete(); } catch (Exception e) { System.out.println("删除文件操作出错"); e.printStackTrace(); } 4.删除文件夹 /* import java.io.*; import java.util.*; */ LinkedList folderList = new LinkedList(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); ArrayList fileList = new ArrayList(); 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(); } } folderList = new LinkedList(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.getLast()); if (file.delete()) { folderList.removeLast(); } else { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { folderList.add(files[i].getPath()); } } } 5.删除一个文件下夹所有的文件夹 /* import java.io.*; private static LinkedList folderList=null; */ File delfile=new File(%%1); File[] files=delfile.listFiles(); for(int i=0;i(); folderList.add(files[i]); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); ArrayList fileList = new ArrayList(); 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(); } } folderList = new LinkedList(); folderList.add(files[i]); while (folderList.size() > 0) { File file = new File(folderList.getLast()); if (file.delete()) { folderList.removeLast(); } else { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { folderList.add(files[i].getPath()); } } } } } } 6.清空文件夹 //import java.io.*; File delfilefolder=new File(%%1); try { if (!delfilefolder.exists() && !delfilefolder.delete()){ LinkedList folderList = new LinkedList(); folderList.add(delfilefolder); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); ArrayList fileList = new ArrayList(); 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(); } } folderList = new LinkedList(); folderList.add(delfilefolder); while (folderList.size() > 0) { File file = new File(folderList.getLast()); if (file.delete()) { folderList.removeLast(); } else { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { folderList.add(files[i].getPath()); } } } } delfilefolder.mkdir(); } catch (Exception e) { System.out.println("清空目录操作出错"); e.printStackTrace(); } 7.读取文件 //import java.io.*; // 逐行读取数据 FileReader fr = new FileReader(%%1); BufferedReader br = new BufferedReader(fr); String %%2 = br.readLine(); while (%%2 != null) { %%3 %%2 = br.readLine(); } br.close(); fr.close(); 8.写入文件 //import java.io.*; // 将数据写入文件 try { FileWriter fw = new FileWriter(%%1); fw.write(%%2); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } 9.写入随机文件 //import java.io.*; try { RandomAcessFile logFile=new RandomAcessFile(%%1,"rw"); long lg=logFile.length(); logFile.seek(%%2); logFile.writeByte(%%3); }catch(IOException ioe){ System.out.println("无法写入文件:"+ioe.getMessage()); } 10.读取文件属性 //import java.io.*; // 文件属性的取得 File af = new File(%%1); if (af.exists()) { System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length()); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified())); } else { System.out.println(f.getName() + "的属性如下:"); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件的最后修改日期为:" + new Date(f.lastModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 } 11.写入属性 //import java.io.*; File filereadonly=new File(%%1); try { boolean b=filereadonly.setReadOnly(); } catch (Exception e) { System.out.println("拒绝写访问:"+e.printStackTrace()); } 12.枚举一个文件夹中的所有文件 /* import java.io.*; import java.util.*; */ LinkedList folderList = new LinkedList(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); List fileList = new ArrayList(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { %%2=f.getAbsoluteFile(); %%3 } } 13.复制文件夹 /* import java.io.*; import java.util.*; */ LinkedList folderList = new LinkedList(); folderList.add(%%1); LinkedList folderList2 = new LinkedList(); folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// 如果是子文件夹 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } } } catch (Exception e) { //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } 14.复制一个目录下所有的文件夹到另一个文件夹下 /* import java.io.*; import java.util.*; */ File copyfolders=new File(%%1); File[] copyfoldersList=copyfolders.listFiles(); for(int k=0;kfolderList=new ArrayList(); folderList.add(copyfoldersList[k].getPath()); ListfolderList2=new ArrayList(); folderList2.add(%%2+"/"+copyfoldersList[k].getName()); for(int j=0;j folderList = new LinkedList(); folderList.add(%%1); LinkedList folderList2 = new LinkedList(); 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()) //删除单个文件操作出错 } 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) { //复制整个文件夹内容操作出错 e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } File f = new File(%%1); if (!f.delete()) { for (File file : f.listFiles()) { if (file.list().length == 0) { System.out.println(file.getPath()); file.delete(); } } } 16.移动一个目录下所有的文件夹到另一个目录下 /* import java.io.*; import java.util.*; */ File movefolders=new File(%%1); File[] movefoldersList=movefolders.listFiles(); for(int k=0;kfolderList=new ArrayList(); folderList.add(movefoldersList[k].getPath()); ListfolderList2=new ArrayList(); folderList2.add(%%2+"/"+movefoldersList[k].getName()); for(int j=0;jfolderList=new ArrayList(); folderList.add(%%1); ListfolderList2=new ArrayList(); folderList2.add(%%2); for(int j=0;j= 0) { //f.getPath() } } //f.getPath() } //"The numbers of files had been found:" + countFiles } else { //"Couldn't open the path!" } } else { System.out.println("The path had been apointed was not Exist!"); } } doSearch(%%1); 28.打开对话框 /* import java.io.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (Jfc.isFileSelectionEnabled()) { File %%2 = Jfc.getSelectedFile(); } 29.文件分割 //import java.io.*; try { File f=new File(%%1); FileInputStream fileInputStream = new FileInputStream(f); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); String strFileName = f.getName(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1")); fileOutputStream.write(buffer,0,buffer.length/2); fileOutputStream.close(); fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2")); fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2); fileOutputStream.close(); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("using FileStreamDemo src des"); e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } 30.文件合并 //import java.io.*; String strFileName = %%1.substring(%%1.LastIndexOf("\\") + 1); try { FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1")); FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2")); byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()]; FileInputStream.read(buffer, 0, fileInputStream1.available()); FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available()); fileInputStream.close(); fileInputStream2.close(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName)); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(IOException e){ e.printStackTrace(); } 31.文件简单加密 //import java.io.*; try { File f=new File((new File(%%1)).getPath()+"\\enc_"+(new File(%%1)).getName().split("//")[1]); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2+"\\"+strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(int i=0;i(); String strLine = null; String currentNode = null; String previousNode = null; ArrayList vec = new ArrayList(); int row = 0; 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, (ArrayList)vec.clone()); vec.clear(); row = 0; } } else if (strArray1[0].equals("@Key") && row == 0) { Properties ht = new Properties(); ht.setProperty(strArray1[1], strArray1[2]); vec.add(ht); row++; } else if (strArray1[0].equals("@Key") && row > 0) { Properties ht2 = new Properties(); ht2.put(strArray1[1], strArray1[2]); vec.add(ht2); row++; } } } configMap.put(currentNode, (ArrayList)vec.clone()); } catch (FileNotFoundException e) { configMap = null; e.printStackTrace(); return false; } catch (IOException e) { configMap = null; e.printStackTrace(); return false; } } return true; } try { fileReader = new FileReader(%%1); //"Setup.ini" } catch (FileNotFoundException e1) { e1.printStackTrace(); } if (readIni()) { ArrayList li = null; li = (ArrayList) configMap.get(%%2); //"[DataSource]" for (Properties pro : li) { if(pro.containsKey(%%3)) %%4=pro.getProperty(%%3); } } try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } 34.合并一个目录下所有的文件 //import java.io.*; 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 li = null; try { FileWriter fw = new FileWriter("Setup.ini"); li = (ArrayList) configMap.get("[DataSource]"); fw.write("[DataSource]\r\n"); for (Properties pro : li) { if (pro.containsKey("ip")) fw.write("ip=" + jt1.getText() + "\r\n"); else if (pro.containsKey("username")) fw.write("username=" + username1 + "\r\n"); else if (pro.containsKey("password")) fw.write("password=" + password1 + "\r\n"); else if (pro.containsKey("database")) fw.write("database=" + database1 + "\r\n"); else if (pro.containsKey("table")) fw.write("table=" + table1 + "\r\n"); } li = (ArrayList) configMap.get("[DataTarget]"); fw.write("\r\n[DataTarget]\r\n"); for (Properties pro : li) { if (pro.containsKey("ip")) fw.write("ip=" + jt2.getText() + "\r\n"); else if (pro.containsKey("username")) fw.write("username=" + username2 + "\r\n"); else if (pro.containsKey("password")) fw.write("password=" + password2 + "\r\n"); else if (pro.containsKey("database")) fw.write("database=" + database2 + "\r\n"); else if (pro.containsKey("table")) fw.write("table=" + table2 + "\r\n"); } fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } 36.获得当前路径 String %%1=this.getClass().getResource("/").getPath(); //String %%1=System.getProperty("user.dir") 37.读取 XML 数据库 /* import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; private static Document document; private static 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="Product" //%%4="id" //%%6="port" //%%3="Name" //%%5="001" NodeList nlist = rootNode.getElementsByTagName(subNodeTag); int len = nlist.getLength(); for (int i = 0; i < len; i++) { node = nlist.item(i); String getNodeAttrValue = null; NamedNodeMap attrList = node.getAttributes(); for (int j = 0; j < attrList.getLength(); j++) { if (attrList.item(j).getNodeName().equals(%%4)) { getNodeAttrValue = attrList.item(j).getNodeValue(); break; } } if (getNodeAttrValue.equals(%%5)) { nlist = node.getChildNodes(); String %%9=((Element) node).getElementsByTagName(%%3).item(0) .getFirstChild().getNodeValue(); break; } } 38.写入 XML 数据库 /* import java.io.*; import javax.xml.parsers.*; 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="Product" //%%4="pid" //%%6="author" // %%3="Name" //%%5="price" NodeList nlist = rootNode.getElementsByTagName(subNodeTag); String ss = null; int len = nlist.getLength(); for (int i = 0; i < len; i++) { node = (Element) nlist.item(i); //node.setAttribute(%%4, "0"+String.valueOf(i)); //ID 格式化 String getNodeAttrValue = null; NamedNodeMap attrList = node.getAttributes(); for (int j = 0; j < attrList.getLength(); j++) { if (attrList.item(j).getNodeName().equals(%%4)) { getNodeAttrValue = attrList.item(j).getNodeValue(); break; } } if (getNodeAttrValue.equals("001")) { nlist = node.getChildNodes(); ss = ((Element) node).getElementsByTagName(%%3).item(0) .getFirstChild().getNodeValue(); ss = ((Element) node).getElementsByTagName(%%6).item(0) .getFirstChild().getNodeValue(); ss = ((Element) node).getElementsByTagName(%%5).item(0) .getFirstChild().getNodeValue(); ((Element) node).getElementsByTagName(%%3).item(0) .getFirstChild().setTextContent(%%7); ((Element) node).getElementsByTagName(%%6).item(0) .getFirstChild().setTextContent(%%8); ((Element) node).getElementsByTagName(%%5).item(0) .getFirstChild().setTextContent(%%9); break; } } if (ss == null) { node = document.createElement(%%2); node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1)); node.appendChild(document.createTextNode("\n")); Element server = document.createElement(%%3); server.appendChild(document.createTextNode(%%7)); node.appendChild(server); Element ipNode = document.createElement(%%6); ipNode.appendChild(document.createTextNode(%%8)); node.appendChild(ipNode); node.appendChild(document.createTextNode("\n")); Element port = document.createElement(%%5); port.appendChild(document.createTextNode(%%9)); node.appendChild(port); node.appendChild(document.createTextNode("\n")); rootNode.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(); } 39.ZIP 压缩文件 /* import java.io.*; import java.util.zip.*; */ //创建文件输入流对象 FileInputStream fis=new FileInputStream(%%1); //创建文件输出流对象 FileOutputStream fos=new FileOutputStream(%%2); //创建 ZIP 数据输出流对象 ZipOutputStream zipOut=new ZipOutputStream(fos); //创建指向压缩原始文件的入口 ZipEntry entry=new ZipEntry(args[0]); zipOut.putNextEntry(entry); //向压缩文件中输出数据 int nNumber; byte[] buffer=new byte[1024]; while((nNumber=fis.read(buffer))!=-1) zipOut.write(buffer,0,nNumber); //关闭创建的流对象 zipOut.close(); fos.close(); fis.close(); } catch(IOException e) { System.out.println(e); } 40.ZIP 解压缩 /* import java.io.*; import java.util.zip.*; */ try{ //创建文件输入流对象实例 FileInputStream fis=new FileInputStream(%%1); //创建 ZIP 压缩格式输入流对象实例 ZipInputStream zipin=new ZipInputStream(fis); //创建文件输出流对象实例 FileOutputStream fos=new FileOutputStream(%%2); //获取 Entry 对象实例 ZipEntry entry=zipin.getNextEntry(); byte[] buffer=new byte[1024]; int nNumber; while((nNumber=zipin.read(buffer,0,buffer.length))!=-1) fos.write(buffer,0,nNumber); //关闭文件流对象 zipin.close(); fos.close(); fis.close(); } catch(IOException e) { System.out.println(e); } 41.获得应用程序完整路径 String %%1=System.getProperty("user.dir"); 42.递归删除目录中的文件 /* import java.io.*; import java.util.*; */ ArrayList folderList = new ArrayList(); folderList.add(%%1); for (int j = 0; j < folderList.size(); j++) { File file = new File(folderList.get(j)); File[] files = file.listFiles(); ArrayList fileList = new ArrayList(); 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 java.util.*; import java.util.zip.*; */ public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) { ArrayList fileNames = new ArrayList(); ArrayList files = new ArrayList(); FileOutputStream fileOut = null; ZipOutputStream outputStream = null; FileInputStream fileIn = null; StringBuffer sb = new StringBuffer(outputZipNameAndPath); // FileInputStream fileIn =null; try { if (outputZipNameAndPath.indexOf(".zip") != -1) { outputZipNameAndPath = outputZipNameAndPath; } else { sb.append(".zip"); outputZipNameAndPath = sb.toString(); } fileOut = new FileOutputStream(outputZipNameAndPath); outputStream = new ZipOutputStream(fileOut); int outputZipFileNameListSize = 0; if (outputZipFileNameList != null) { outputZipFileNameListSize = outputZipFileNameList.size(); } for (int i = 0; i < outputZipFileNameListSize; i++) { File rootFile = new File(outputZipFileNameList.get(i).toString()); listFile(rootFile, fileNames, files, ""); } for (int loop = 0; loop < files.size(); loop++) { fileIn = new FileInputStream((File) files.get(loop)); outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop))); byte[] buffer = new byte[1024]; while (fileIn.read(buffer) != -1) { outputStream.write(buffer); } outputStream.closeEntry(); fileIn.close(); } return outputZipNameAndPath; } catch (IOException ioe) { return null; } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } if (fileIn != null) { try { fileIn.close(); } catch (IOException e) { } } } } private static void listFile(File parentFile, List nameList, List fileList, String directoryName) { if (parentFile.isDirectory()) { File[] files = parentFile.listFiles(); for (int loop = 0; loop < files.length; loop++) { listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/"); } } else { fileList.add(parentFile); nameList.add(directoryName + parentFile.getName()); } } ArrayList outputZipFileName=new ArrayList(); String savePath=""; int argSize = 0; savePath = %%1; outputZipFileName.add(%%2); ZipFileOther instance=new ZipFileOther(); instance.zipFileProcess(outputZipFileName,savePath); 44.验证 DTD /* import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; */ File xml_dtd = new File(%%1); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(xml_dtd); //进行 dtd 检查 factory.setValidating(true); } catch (Exception e) { e.printStackTrace(); } 45.验证 Schema /* import javax.xml.*; import javax.xml.transform.stream.*; import javax.xml.validation.*; import org.xml.sax.*; */ SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource ss = new StreamSource(%%1); //"mySchema.xsd" try { Schema schema = factory.newSchema(ss); } catch (SAXException e) { e.printStackTrace(); } 46.Grep /* import java.util.regex.*; import java.io.*; */ throws Exception Pattern pattern = Pattern.compile(%%1); // 第一个参数为需要匹配的字符串 Matcher matcher = pattern.matcher(""); String file = %%2; BufferedReader br = null; String line; try { br = new BufferedReader (new FileReader (file)); // 打开文件 } catch (IOException e) { // 没有打开文件,则产生异常 System.err.println ("Cannot read '" + file + "': " + e.getMessage()); } while ((line = br.readLine()) != null) { // 读入一行,直到文件结束 matcher.reset (line); // 匹配字符串 if (matcher.find()) { // 如果有匹配的字符串,则输出 System.out.println (file + ": " + line); } } br.close(); // 关闭文件 47.直接创建多级目录 //import java.io.*; File f=new File(%%1); f.mkdirs(); 48.批量重命名 //import java.io.*; File target = new File("%%1"); String[] files = target.list(); File f = null; String filename = null; for (String file : files) { f = new File(target, file); filename = f.getName(); if (filename.substring(filename.lastIndexOf(".")).equalsIgnoreCase( "%%2")) { f.renameTo(new File(target.getAbsolutePath(), filename.replace( "%%2", "%%3"))); // 这里可以反复使用 replace 替换,当然也可以使用正则表达式来替换 了 ".txt" ".bat" } } 49.文本查找替换 //import java.nio.*; String s1=%%1; String s2=%%2; String s3=%%3; int pos=%%4; /*变量 i 和 j 分别表示主串和模式串中当前字符串的位置,k 表示匹配次数*/ int i,j,k=0; i = pos; j = 0; //将 s1 转化成 StringBuffer 型进行操作 repStr = new StringBuffer(s1); while(i 0) { for (int i = 0; i < list.size() - 1; i++) { ProductQuery query = (ProductQuery) list.get(i); HSSFRow datarow = sheet.createRow(i + 1); HSSFCell data[] = new HSSFCell[8]; for (short j = 0; j < 8; j++) { data[j] = datarow.createCell(j); //将单元格定义成 UTF_16 编码,这样才能使输出数据不会乱码 data[j].setEncoding(HSSFCell.ENCODING_UTF_16); } data[0].setCellValue(query.getCertId()); data[1].setCellValue(query.getCertNum()); data[2].setCellValue(query.getCityCode()); data[3].setCellValue(query.getSoftWareCname()); data[4].setCellValue(query.getSoftWareEname()); data[5].setCellValue(query.getSoftwareFor()); data[6].setCellValue(query.getSoftwareFuncDesc()); data[7].setCellValue(query.getSoftwareType()); } } //将工作薄输出到输出流 ServletOutputStream sos=response.getOutputStream(); wb.write(sos); sos.close(); //也可输出成 xls 文件 File file = new File("workbook.xls"); try { FileOutputStream fileOut = new FileOutputStream(file); wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } 52.设置 JDK 环境变量 @echo off IF EXIST %1\bin\java.exe ( rem 如输入正确的 Java2SDK 安装目录,开始 设置环境变量 @setx JAVA_HOME %1 @setx path %path%;%JAVA_HOME%\bin @setx classpath %classpath%;. @setx classpath %classpath%;%JAVA_HOME%\lib\tools.jar @setx classpath %classpath%;%JAVA_HOME%\lib\dt.jar @setx classpath %classpath%;%JAVA_HOME%\jre\lib\rt.jar @echo on @echo Java 2 SDK 环境参数设置完毕,正常退 出。 ) ELSE ( IF "%1"=="" ( rem 如没有提供安装目录,提示之后退出 @echo on @echo 没有提供 Java2SDK 的安装目录,不做任 何设置,现在退出环境变量设置。 ) ELSE ( rem 如果提供非空的安装目录但没有 bin\java.exe,则指定的目录为错误的目录 @echo on @echo 非法的 Java2SDK 的安装目录,不做任何 设置,现在退出环境变量设置。 ) ) //http://sourceforge.net/projects/jregistrykey/ //import ca.beq.util.win32.registry.*; //import java.util.*; 1.打开键 RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"); 2.添加键 RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); r.create(); 9.写入字符串值 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.选择文件夹对话框 /* import java.io.*; import javax.swing.*; */ JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); } public String getDescription() { return "GIF Images"; } }); int r = chooser.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); // label.setIcon(new ImageIcon(name)); } 54.删除空文件夹 //import java.io.*; File f=new File(%%1); if (isFolerNull(f)) { for (File file :f.listFiles()) { if (file.list().length == 0) { System.out.println(file.getPath()); file.delete(); } } } 55.发送数据到剪贴板 /* import java.awt.*; import java.awt.datatransfer.*; */ Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(%%1); clipboard.setContents(tText, null); 56.从剪贴板中取数据 /* import java.awt.*; import java.awt.datatransfer.*; import java.io.*; */ // 取得系统剪贴板里可传输的数据构造的 Java 对象 Transferable t = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { // 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等 // 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字 String %%1 = (String) t .getTransferData(DataFlavor.stringFlavor); // 同样, 因为 Transferable 中的 DataFlavor 是多种类型的, // 所以传入 DataFlavor 这个参数, 指定要取得哪种类型的 Data. } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } 57.获取文件路径的父路径 String %%2=%%1.substring(0,%%1.lastIndexOf("\\")); 58.创建快捷方式 //import java.io.*; try { PrintWriter pw=new PrintWriter(new FileOutputStream("C:/a.bat")); pw.println(%%1);"C:/a.txt" pw.close(); } catch(IOException e){ e.printStackTrace(); } 59.弹出快捷菜单 //MouseEvent e JPopupMenu jpm=new JPopupMenu(); show(jpm,x,y); 60.文件夹复制到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc.showDialog(null, %%1); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); LinkedList folderList = new LinkedList(); folderList.add(%%1); LinkedList folderList2 = new LinkedList(); folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// 如果是子文件夹 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } } } catch (Exception e) { //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); } 61.文件夹移动到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 62.目录下所有文件夹复制到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc.showDialog(null, %%1); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 63.目录下所有文件夹移动到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 64.目录下所有文件复制到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 65.目录下所有文件移动到整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 66.对目标压缩文件解压缩到指定文件夹 /* import java.io.*; import java.util.zip.*; */ String zipFileName=%%1; String extPlace=%%2; File myFolderPath = new File(extPlace); try { if (!myFolderPath.exists()) { myFolderPath.mkdir(); } } catch (Exception e) { //新建目录操作出错 e.printStackTrace(); return; } try { ZipInputStream in = new ZipInputStream(new FileInputStream( zipFileName)); ZipEntry entry = null; while ((entry = in.getNextEntry()) != null) { String entryName = entry.getName(); File file = new File(extPlace , entryName); if (entry.isDirectory()) { file.mkdirs(); } else { FileOutputStream os = new FileOutputStream(file); // Transfer bytes from the ZIP file to the output // file byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); in.closeEntry(); } } } catch (IOException e) { e.printStackTrace(); } 67.创建目录副本整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%1 = Jfc.getSelectedFile().getParent(); Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc Jfc.showDialog(null, %%1); if (!Jfc.isFileSelectionEnabled()) { return; } String %%2 = Jfc.getSelectedFile().getParent(); 68.打开网页 //import java.io.*; try{ String command = "C:\\Program Files\\Internet Explorer\\Iexplore.exe "+%%1; Runtime.getRuntime().exec(command); } catch (IOException ex) { ex.printStackTrace(); } 69.删除空文件夹整合操作 /* import java.io.*; import java.util.*; import javax.swing.*; */ 70.获取磁盘所有分区后再把光驱盘符去除(用"\0"代替),把结果放在数组 allfenqu[] 中,数组 中每个元素代表一个分区盘符,不包括 :\\ 这样的路径,allfenqu[]数组开始时存放的是所有 盘符。 当我用这样的代码测试结果是正确的,光驱盘符会被去掉: String root; //root 代表盘符路径 for(i=0;i<20;i++) //0-20 代表最大的盘符数 { root.Format("%c:\\",allfenqu[i]); if(GetDriveType(root)==5) allfenqu[i]='\0'; } 但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符: String root; for(i=0;i<20;i++) { root=allfenqu[i]+":\\"; if(GetDriveType(root)==5) allfenqu[i]='\0'; } 71.激活一个程序或程序关联的文件 //import java.io.*; try { Runtime.getRuntime().exec(%%1); } catch (IOException e) { e.printStackTrace(); } 72.HTTP 下载 /* import java.io.*; */ public class DownloadCSVFileAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { String fileName = request.getParameter( "fileName "); long maID = Long.parseLong(request.getParameter( "maID ")); String filePath = request.getSession().getServletContext ().getRealPath( "/ ")+ "csv/ "+maID+ "/ "+fileName; File fdown = new File(filePath); int filelength = Integer.parseInt(String.valueOf(fdown.length())); //下载类型 response.setContentType( "application/text;charset=GB2312 "); response.setHeader( "Content-Dispositon ", "attachment;filename=销售 详细记录.csv "); //销售详细记录.csv 是我想要的下载文件的文件名,但是下载对话框中显示 的是 downLoadCSVFile.do response.setContentLength(filelength); byte b[]=new byte[filelength]; FileInputStream fi=new FileInputStream(fdown); OutputStream o=response.getOutputStream(); int n = 0; while((n=fi.read(b))!=-1) { o.write(b,0,n); } fi.close(); o.close(); return null; }catch (Exception e) { request.setAttribute( "ERROR ", e); return mapping.findForward( "error "); } } } 对应的下载类型 private String getContentType(String fileName) { String fileNameTmp = fileName.toLowerCase(); String ret = ""; if (fileNameTmp.endsWith("txt")) { ret = "text/plain"; } if (fileNameTmp.endsWith("gif")) { ret = "image/gif"; } if (fileNameTmp.endsWith("jpg")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("jpeg")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("jpe")) { ret = "image/jpeg"; } if (fileNameTmp.endsWith("zip")) { ret = "application/zip"; } if (fileNameTmp.endsWith("rar")) { ret = "application/rar"; } if (fileNameTmp.endsWith("doc")) { ret = "application/msword"; } if (fileNameTmp.endsWith("ppt")) { ret = "application/vnd.ms-powerpoint"; } if (fileNameTmp.endsWith("xls")) { ret = "application/vnd.ms-excel"; } if (fileNameTmp.endsWith("html")) { ret = "text/html"; } if (fileNameTmp.endsWith("htm")) { ret = "text/html"; } if (fileNameTmp.endsWith("tif")) { ret = "image/tiff"; } if (fileNameTmp.endsWith("tiff")) { ret = "image/tiff"; } if (fileNameTmp.endsWith("pdf")) { ret = "application/pdf"; } return ret; } 73.FTP 下载 /* import sun.net.ftp.FtpClient; import java.io.*; import sun.net.*; */ //如果文件在某个目录下,则加入 fc.cd("foodir"); //比如要下载 ftp://ftp.xx.com/index.html 则: try { FtpClient fc=new FtpClient("ftp.xx.com"); fc.login("username","888888"); int ch; File fi = new File("c:\\index.html"); RandomAccessFile getFile = new RandomAccessFile(fi,"rw"); getFile.seek(0); TelnetInputStream fget=fc.get("index.html"); DataInputStream puts = new DataInputStream(fget); while ((ch = puts.read()) >= 0) { getFile.write(ch); } fget.close(); getFile.close(); fc.closeServer(); } catch (IOException ex) { ex.printStackTrace(); } 74.写图像到剪切板 setClipboardImage /* import java.awt.*; import java.awt.datatransfer.*; import java.io.*; private final Image image; */ Transferable trans = new Transferable() { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) return image; throw new UnsupportedFlavorException(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null); 75.从剪贴板复制图像到窗体 76.删除文件夹下的所有文件且不删除文件夹下的文件夹 //import java.io.*; //import java.util.*; LinkedList folderList = new LinkedList(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); ArrayList fileList = new ArrayList(); 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(); } } 78.拷贝文件名复制文件 package p1; import java.io.*; import java.awt.*; import java.awt.datatransfer.*; public class VCFileCopy { public static void main(String[] args) { // TODO Auto-generated method stub // // 取得系统剪贴板里可传输的数据构造的 Java 对象 Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard() .getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { // 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等 // 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这 些文字 String s = (String) t.getTransferData(DataFlavor.stringFlavor); // 同样, 因为 Transferable 中的 DataFlavor 是多种类型的, // 所以传入 DataFlavor 这个参数, 指定要取得哪种类型的 Data. System.out.println(s); int bytesum = 0; int byteread = 0; File oldfile = new File(s); try { if (oldfile.exists()) { // 文件存在时 FileInputStream inStream = new FileInputStream(oldfile); // 读入原文件 FileOutputStream fs = new FileOutputStream(new File( "C:\\" , oldfile.getName())); byte[] buffer = new byte[5120]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; // 字节数 文件大 小 fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } 79.开源程序库 Xercesc-C++代码工程中内联 import java.io.*; import java.util.*; import java.util.regex.*; public class InlineXercesc { private final String filter = ".cpp"; private ArrayList all = new ArrayList(); private LinkedList fal2 = new LinkedList(); private static String CurDir = System.getProperty("user.dir"); private void doSearch(String path) { File filepath = new File(path); if (filepath.exists()) { if (filepath.isDirectory()) { File[] fileArray = filepath.listFiles(); for (File f : fileArray) { if (f.isDirectory()) { doSearch(f.getPath()); } else { if (f.getName().indexOf(filter) >= 0) { for (String file : all) { if (file.substring(file.lastIndexOf("\\") + 1) .equals(f.getName())) { fal2.add(f.getAbsolutePath()); } } } } } } else { System.out.println("Couldn't open the path!"); } } else { System.out.println("The path had been apointed was not Exist!"); } } public InlineXercesc(String lib) throws IOException { String SourceLib = "D:\\Desktop\\大项目\\xerces-c-3.0.1\\src"; Pattern pattern = Pattern.compile("include.*?" + lib + ".*?>"); // 第一个参数为需 要匹配的字符串 Matcher matcher = pattern.matcher(""); LinkedList fal = new LinkedList(); File delfile = new File(CurDir); File[] files2 = delfile.listFiles(); for (int l = 0; l < files2.length; l++) { if (files2[l].isDirectory()) { String enumDir = CurDir + "\\" + files2[l].getName() + "\\"; LinkedList folderList = new LinkedList(); folderList.add(files2[l].getAbsolutePath()); while (folderList.size() > 0) { File file = new File(folderList.poll()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { String fileStr = files[i].getAbsolutePath(); // 第 2 个参数开始,均为文件名。 BufferedReader br = null; String line; try { br = new BufferedReader(new FileReader(fileStr)); // 打开文件 } catch (IOException e) { // 没有打开文件,则产生异常 System.err.println("Cannot read '" + fileStr + "': " + e.getMessage()); continue; } StringBuilder sb = new StringBuilder(2048); while ((line = br.readLine()) != null) { // 读 入一行,直到文件结束 matcher.reset(line); // 匹配字符 串 if (matcher.find()) { // 如果有匹配 的字符串,则输出 sb.append(line.replace( line.substring(line.indexOf("<"), line.lastIndexOf("/") + 1), "\"").replace('>', '\"')); line = line.substring( line.indexOf("<") + 1, line.lastIndexOf(">")).replace('/', '\\'); fal.add(SourceLib + "\\" + line); } else { sb.append(line); } sb.append("\r\n"); } br.close(); // 关闭文件 FileWriter fw2 = new FileWriter(fileStr); fw2.write(sb.toString()); fw2.flush(); fw2.close(); } } } while (fal.size() > 0) { String file = fal.poll(); // 第 2 个参数开始,均为文件名。 String targetPath = enumDir + file.substring(file.lastIndexOf("\\") + 1); if (!new File(targetPath).exists()) { BufferedReader br = null; String line; try { br = new BufferedReader(new FileReader(file)); // 打开文件 } catch (IOException e) { // 没有打开文件,则产生异常 System.err.println("Cannot read '" + file + "': " + e.getMessage()); continue; } FileWriter fw = new FileWriter(targetPath); while ((line = br.readLine()) != null) { // 读入一行, 直到文件结束 matcher.reset(line); // 匹配字符串 if (matcher.find()) { // 如果有匹配的字符 串,则输出 fal.add(SourceLib + "\\" + line.substring(line.indexOf("<") + 1, line.lastIndexOf(">")).replace( '/', '\\')); line = line.replace(line.substring(line .indexOf("<"), line.lastIndexOf("/") + 1), "\""); line = line.replace(">", "\""); } fw.write(line + "\r\n"); } fw.flush(); fw.close(); br.close(); // 关闭文件 } } LinkedList folderListArr = new LinkedList(); folderListArr.add(CurDir); while (folderListArr.size() > 0) { File file = new File(folderListArr.poll()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderListArr.add(files[i].getPath()); } else { if (files[i].getName().substring( files[i].getName().lastIndexOf(".")) .equals(".hpp")) all.add(files[i].getAbsoluteFile().toString() .replace(".hpp", ".cpp")); } } } int count = 1; while (count > 0) { doSearch(SourceLib); all.clear(); while (fal2.size() > 0) { String file1 = fal2.poll(); // 第 2 个参数开始,均 为文件名。 String targetPath = enumDir + file1.substring(file1.lastIndexOf("\\") + 1); if (!new File(targetPath).exists()) { BufferedReader br = null; String line; try { br = new BufferedReader(new FileReader(file1)); // 打开文件 } catch (IOException e) { // 没有打开文件,则产生异常 System.err.println("Cannot read '" + file1 + "': " + e.getMessage()); continue; } FileWriter fw; try { fw = new FileWriter(targetPath); while ((line = br.readLine()) != null) { // 读入一行,直到文件结束 matcher.reset(line); // 匹 配字符串 if (matcher.find()) { // 如 果有匹配的字符串,则输出 fal2.add(SourceLib + "\\" + line.substring( line.indexOf('<') + 1, line.lastIndexOf('>')) .replace('/', '\\')); all.add(fal2.getLast().replace(".hpp", ".cpp")); line = line.replace(line.substring(line .indexOf('<'), line .lastIndexOf('/') + 1), "\""); line = line.replace('>', '\"'); } fw.write(line + "\r\n"); } fw.flush(); fw.close(); br.close(); // 关闭文件 } catch (IOException e) { e.printStackTrace(); } } } count = all.size(); } } } } public static void main(String[] args) { try { new InlineXercesc("xercesc"); // 将数据写入文件 try { FileWriter fw = new FileWriter(CurDir + "\\DetailCpp.cmd"); fw.write("copy StdAfx.cpp+*.c+*.cpp " + CurDir + "\\StdAfx.cpp && del *.c && del *.cpp"); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { } } } 80.提取包含头文件列表 import java.io.*; import java.util.regex.*; import java.util.*; public class InlineExt { private String CurDir = System.getProperty("user.dir"); public InlineExt() { Pattern pattern = Pattern.compile("include.*?\".*?.hpp\""); // 第一个参数为需要 匹配的字符串 Matcher matcher = pattern.matcher(""); File delfile = new File(CurDir); File[] files2 = delfile.listFiles(); for (int l = 0; l < files2.length; l++) { if (files2[l].isDirectory()) { Set ts = new LinkedHashSet(); File file = new File(files2[l].getPath(), "StdAfx.cpp"); BufferedReader br = null; FileWriter fw = null; String line; try { br = new BufferedReader(new FileReader(file)); // 打开文 件 while ((line = br.readLine()) != null) { matcher.reset(line); // 匹配字符串 if (matcher.find()) { // 如果有匹配的字符串,则 输出 ts.add(line.substring(line.indexOf('\"') + 1, line .lastIndexOf('\"'))); } } Iterator it = ts.iterator(); File file2 = new File(files2[l], "ReadMe.txt"); if (file2.exists()) { fw = new FileWriter(file2); while (it.hasNext()) { fw.write("#include \"" + it.next() + "\"\r\n"); } } } catch (IOException e) { // 没有打开文件,则产生异常 System.err.println("Cannot read '" + file + "': " + e.getMessage()); continue; } finally { try { if (br != null) br.close(); if (fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { new InlineExt(); } } 81.剪贴扳转换成打印字符 import java.awt.*; import java.awt.datatransfer.*; import java.io.*; public class ClipBoard { public static void main(String[] args) { // 取得系统剪贴板里可传输的数据构造的 Java 对象 Transferable t = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { // 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件 等 // 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字 String s = (String) t .getTransferData(DataFlavor.stringFlavor); String[]arr=s.split("\n"); StringBuilder sb=new StringBuilder(1024); for(String ss:arr) { if(!ss.trim().equals("")){ sb.append("w.WriteLine(\"ECHO " + ss.replace("^", "^^").replace("&", "^&").replace(":", "^:").replace(">", "^>").replace("<", "^<").replace("|", "^|").replace("\"", "^\"").replace("\\", "\\\\").replace("\"", "\\\"") + "\");"); sb.append("\r\n"); } } Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(sb.toString()); clipboard.setContents(tText, null); } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } 82.把 JButton 或 JTree 组件写到一个流中 /* 由于 JButton 和 JTree 都已经实现了 Serializable 接口,因此你所说的问题是可以做到的。 使用 ObjectInputStream 读取文件中的对象,使用 ObjectOutputStream 把对象写入文件。如: */ /* import java.io.*; import javax.swing.*; */ public class Save { public static void main(String[] args) { // Write JButton button = new JButton("TEST Button"); JTree tree = new JTree(); try { ObjectOutputStream outForButton = new ObjectOutputStream( new FileOutputStream("button")); outForButton.writeObject(button); outForButton.close(); ObjectOutputStream outForTree = new ObjectOutputStream( new FileOutputStream("tree")); outForTree.writeObject(tree); outForTree.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Read try { ObjectInputStream inForButton = new ObjectInputStream( new FileInputStream("button")); JButton buttonReaded = (JButton) inForButton.readObject(); ObjectInputStream inForTree = new ObjectInputStream( new FileInputStream("tree")); JTree treeReaded = (JTree) inForTree.readObject(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } 83.注册全局热键 //http://hi.baidu.com/ekou/blog/item/81cd52087a305bd463d986e4.html //http://www.blogjava.net/Files/walsece/jintellitype.rar //http://commons.apache.org/logging/ commons-loggins.jar 所谓系统级热键就是指一组快捷键,不论当前系统焦点在哪个程序中,只要按下该键,程序 就能够捕捉该事件并进行相关处理。该功能在应用程序中是非常有用的,比如系统自带的 “win+L”自动锁屏,QQ 中默认的“ctrl+alt+Z”自动打开当前的消息窗口等等。 Java 中的事件 监听机制虽然功能强大,但是当系统焦点脱离该程序时也无能为力。要实现该功能必须调用 系统的钩子函数,因此在 java 中也必须通过 jni 调用来实现,但是对于不熟悉系统函数或者 其他编成语言的朋友来说却是个难题。 以前实现类似的功能都是自己通过 c 调用系统的钩子 函数然后再通过 jni 调用,自己写的东西只要能满足简单的需求即可,因此功能和程序结构 也比较简单。后来在国外的一个网站上发现了一个组件“jintellitype”帮我们封装了绝大部分 的功能,而且结构上也采用 java 中的事件监听机制,我们只要在程序中通过注册即可实现, 下面是一个简单的例子: import com.melloware.jintellitype.HotkeyListener; import com.melloware.jintellitype.JIntellitype; public class HotKey implements HotkeyListener { static final int KEY_1 = 88; static final int KEY_2 = 89; static final int KEY_3 = 90; /** * 该方法负责监听注册的系统热键事件 * * @param key:触发的热键标识 */ public void onHotKey(int key) { switch (key) { case KEY_1: System.out.println("ctrl+alt+I 按下........."); break; case KEY_2: System.out.println("ctrl+alt+O 按下........."); break; case KEY_3: System.out.println("系统退出.........."); destroy(); } } /** * 解除注册并退出 */ void destroy() { JIntellitype.getInstance().unregisterHotKey(KEY_1); JIntellitype.getInstance().unregisterHotKey(KEY_2); JIntellitype.getInstance().unregisterHotKey(KEY_3); System.exit(0); } /** * 初始化热键并注册监听事件 */ void initHotkey() { // 参数 KEY_1 表示改组热键组合的标识,第二个参数表示组合键,如果没有 则为 0,该热键对应 ctrl+alt+I JIntellitype.getInstance().registerHotKey(KEY_1, JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'I'); JIntellitype.getInstance().registerHotKey(KEY_2, JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'O'); JIntellitype.getInstance().registerHotKey(KEY_3, JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'X'); JIntellitype.getInstance().addHotKeyListener(this); } public static void main(String[] args) { HotKey key = new HotKey(); key.initHotkey(); // 下面模拟长时间执行的任务 while (true) { try { Thread.sleep(10000); } catch (Exception ex) { break; } } } } 偶尔,我们可以给用户添加一些快捷键,不管现在焦点在哪里。 有个做法就是,任何组建上注册你的监听器,但显然,这不是一个好做法 java 的 toolkit 可以直接添加一个监听器, 一下就是示例 Toolkit toolkit = Toolkit.getDefaultToolkit(); toolkit.addAWTEventListener(capListener, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK| AWTEvent.WINDOW_EVENT_MASK); 实现一个监听器: class CapListener implements AWTEventListener { public void eventDispatched(AWTEvent event) { } } 这就可以了 84.菜单勾选/取消完成后关闭计算机 //import java.io.*; public class Parent implements ICallBack { public static void main(String[] args) { Parent parent=new Parent(); Thread son=new Son(parent); son.start(); } public void output() { try { Runtime.getRuntime().exec("shutdown -f -s -t 0"); } catch (IOException e) { e.printStackTrace(); } } } /* 内部线程类 */ class Son extends Thread { private ICallBack event; public Son(ICallBack callback) { event=callback; } public void run() { try { java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy- MM-dd HH:mm:ss"); while(true) { Thread.currentThread().sleep(3000); event.output(fmt.format(new java.util.Date())); Thread.currentThread().sleep(3000); } } catch (Exception e) { } } } /* 回调接口 */ interface ICallBack { public void output(); } 85.菜单勾选/取消完成后重新启动计算机 //import java.io.*; public class Parent implements ICallBack { public static void main(String[] args) { Parent parent=new Parent(); Thread son=new Son(parent); son.start(); } public void output() { try { Runtime.getRuntime().exec("shutdown -f -r -t 0"); } catch (IOException e) { e.printStackTrace(); } } } /* 内部线程类 */ class Son extends Thread { private ICallBack event; public Son(ICallBack callback) { event=callback; } public void run() { try { java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy- MM-dd HH:mm:ss"); while(true) { Thread.currentThread().sleep(3000); event.output(fmt.format(new java.util.Date())); Thread.currentThread().sleep(3000); } } catch (Exception e) { } } } /* 回调接口 */ interface ICallBack { public void output(); } 86.菜单勾选/取消完成后注销计算机 //import java.io.*; public class Parent implements ICallBack { public static void main(String[] args) { Parent parent=new Parent(); Thread son=new Son(parent); son.start(); } public void output() { try { Runtime.getRuntime().exec("shutdown -l"); } catch (IOException e) { e.printStackTrace(); } } } /* 内部线程类 */ class Son extends Thread { private ICallBack event; public Son(ICallBack callback) { event=callback; } public void run() { try { java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy- MM-dd HH:mm:ss"); while(true) { Thread.currentThread().sleep(3000); event.output(fmt.format(new java.util.Date())); Thread.currentThread().sleep(3000); } } catch (Exception e) { } } } /* 回调接口 */ interface ICallBack { public void output(); } 87.菜单勾选/取消开机自启动程序 //http://sourceforge.net/projects/jregistrykey/ //import ca.beq.util.win32.registry.*; //import java.util.*; RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies"); RegistryValue v = new RegistryValue("run", ValueType.REG_SZ, "data"); r.setValue(v); ///////////////////////////////////////////////////////////// 拖一个 CheckBox 1、软件启动时给 CheckBox 重置状态: //http://sourceforge.net/projects/jregistrykey/ //import ca.beq.util.win32.registry.*; //import java.util.*; RegistryKey R_local = Registry.LocalMachine; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); if (R_run.GetValue("BirthdayTipF") == null) { checkBox1.Checked = false; } else { checkBox1.Checked = true; } R_run.Close(); R_local.Close(); 2、CheckChanged 事件: private void checkBox1_CheckedChanged(object sender, EventArgs e) { string R_startPath = Application.ExecutablePath; if (checkBox1.Checked == true) { RegistryKey R_local = Registry.LocalMachine; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.SetValue("BirthdayTipF", R_startPath); R_run.Close(); R_local.Close(); } else { try { RegistryKey R_local = Registry.LocalMachine; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.Deletue("BirthdayTipF", false); R_run.Close(); R_local.Close(); } catch (Exception ex) { MessageBox.Show("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } } 88.菜单勾选/取消自动登录系统 89.模拟键盘输入字符串 /* import java.awt.*; import java.awt.event.*; throws Exception{ */ static Robot robot; static{ try { robot = new Robot(); } catch (AWTException e) {} } static void sendKey(String ks){ KeyStore k = KeyStore.findKeyStore(ks); if(k!=null){ if(k.upCase) upCase(k.v); else sendKey(k.v); } else{ for(int i=0; i='0'&&c<='9'){ sendKey(c); } else if(c>='a'&&c<='z'){ sendKey(c-32); } else if(c>='A'&&c<='Z'){ upCase(c); } } } } private static void upCase(int kc){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress(kc); robot.keyRelease(kc); robot.keyRelease(KeyEvent.VK_SHIFT); } private static void sendKey(int kc){ robot.keyPress(kc); robot.keyRelease(kc); } static class KeyStore{ //special keys final static KeyStore[] sp = { new KeyStore("{Tab}",KeyEvent.VK_TAB),//tab new KeyStore("{Enter}",KeyEvent.VK_ENTER),//enter new KeyStore("{PUp}",KeyEvent.VK_PAGE_UP),//page up new KeyStore("{<}",KeyEvent.VK_LESS),//< new KeyStore("{Up}",KeyEvent.VK_UP),//up key new KeyStore("{At}",KeyEvent.VK_AT,true),//@ new KeyStore("{Dollar}",KeyEvent.VK_DOLLAR,true),//$ }; String k; int v; boolean upCase; KeyStore(String k,int v){ this(k,v,false); } KeyStore(String s,int i,boolean up){ k=s; v=i; upCase=up; } static KeyStore findKeyStore(String k){ for(int i=0; i getDirMD5(File file,boolean listChild) { if(!file.isDirectory()){ return null; } // Map map=new HashMap(); String md5; File files[]=file.listFiles(); for(int i=0;i
还剩90页未读

继续阅读

下载pdf到电脑,查找使用更方便

pdf的实际排版效果,会与网站的显示效果略有不同!!

需要 15 金币 [ 分享pdf获得金币 ] 20 人已下载

下载pdf

pdf贡献者

sinasohuqq

贡献于2012-01-02

下载需要 15 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!
下载pdf