使用NIO进行快速的文件拷贝

public static void fileCopy( File in, File out )             throws IOException     {         FileChannel inChannel = new FileInputStream( in ).getChannel();         FileChannel outChannel = new FileOutputStream( out ).getChannel();         try         { //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original — apparently has trouble copying large files on Windows               // magic number for Windows, 64Mb – 32Kb)               int maxCount = (64 * 1024 * 1024) – (32 * 1024);             long size = inChannel.size();             long position = 0;             while ( position < size )             {                position += inChannel.transferTo( position, maxCount, outChannel );             }         }         finally         {             if ( inChannel != null )             {                inChannel.close();             }             if ( outChannel != null )             {                 outChannel.close();             }         }     }

列出文件和目录

File dir = new File(“directoryName”);   String[] children = dir.list();   if (children == null) {       // Either dir does not exist or is not a directory     } else {       for (int i=0; i < children.length; i++) {           // Get filename of file or directory             String filename = children[i];       }   }   // It is also possible to filter the list of returned files.     // This example does not return any files that start with `.’.     FilenameFilter filter = new FilenameFilter() {       public boolean accept(File dir, String name) {           return !name.startsWith(“.”);       }   };   children = dir.list(filter);   // The list of files can also be retrieved as File objects     File[] files = dir.listFiles();   // This filter only returns directories     FileFilter fileFilter = new FileFilter() {       public boolean accept(File file) {           return file.isDirectory();       }   };   files = dir.listFiles(fileFilter);

创建ZIP和JAR文件 create zip jar

import java.util.zip.*; import java.io.*; public class ZipIt {     public static void main(String args[]) throws IOException {         if (args.length < 2) {             System.err.println(“usage: java ZipIt Zip.zip file1 file2 file3”);             System.exit(-1);         }         File zipFile = new File(args[0]);         if (zipFile.exists()) {             System.err.println(“Zip file already exists, please try another”);             System.exit(-2);         }         FileOutputStream fos = new FileOutputStream(zipFile);         ZipOutputStream zos = new ZipOutputStream(fos);         int bytesRead;         byte[] buffer = new byte[1024];         CRC32 crc = new CRC32();         for (int i=1, n=args.length; i < n; i++) {             String name = args[i];             File file = new File(name);             if (!file.exists()) {                 System.err.println(“Skipping: “ + name);                 continue;             }             BufferedInputStream bis = new BufferedInputStream(                 new FileInputStream(file));             crc.reset();             while ((bytesRead = bis.read(buffer)) != –1) {                 crc.update(buffer, 0, bytesRead);             }             bis.close();             // Reset to beginning of input stream               bis = new BufferedInputStream(                 new FileInputStream(file));             ZipEntry entry = new ZipEntry(name);             entry.setMethod(ZipEntry.STORED);             entry.setCompressedSize(file.length());             entry.setSize(file.length());             entry.setCrc(crc.getValue());             zos.putNextEntry(entry);             while ((bytesRead = bis.read(buffer)) != –1) {                 zos.write(buffer, 0, bytesRead);             }             bis.close();         }         zos.close();     } }

解析/读取XML 文件

<?xml version=“1.0”?> <students>     <student>         <name>John</name>         <grade>B</grade>         <age>12</age>     </student>     <student>         <name>Mary</name>         <grade>A</grade>         <age>11</age>     </student>     <student>         <name>Simon</name>         <grade>A</grade>         <age>18</age>     </student> </students> package net.viralpatel.java.xmlparser; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XMLParser {     public void getAllUserNames(String fileName) {         try {             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();             DocumentBuilder db = dbf.newDocumentBuilder();             File file = new File(fileName);             if (file.exists()) {                 Document doc = db.parse(file);                 Element docEle = doc.getDocumentElement();                 // Print root element of the document                   System.out.println(“Root element of the document: “                         + docEle.getNodeName());                 NodeList studentList = docEle.getElementsByTagName(“student”);                 // Print total student elements in document                   System.out                         .println(“Total students: “ + studentList.getLength());                 if (studentList != null && studentList.getLength() > 0) {                     for (int i = 0; i < studentList.getLength(); i++) {                         Node node = studentList.item(i);                         if (node.getNodeType() == Node.ELEMENT_NODE) {                             System.out                                     .println(“=====================”);                             Element e = (Element) node;                             NodeList nodeList = e.getElementsByTagName(“name”);                             System.out.println(“Name: “                                     + nodeList.item(0).getChildNodes().item(0)                                             .getNodeValue());                             nodeList = e.getElementsByTagName(“grade”);                             System.out.println(“Grade: “ […]

使用iText JAR生成PDF

import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Date; import com.lowagie.text.Document; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; public class GeneratePDF {     public static void main(String[] args) {         try {             OutputStream file = new FileOutputStream(new File(“C:\\Test.pdf”));             Document document = new Document();             PdfWriter.getInstance(document, file);             document.open();             document.add(new Paragraph(“Hello Kiran”));             document.add(new Paragraph(new Date().toString()));             document.close();             file.close();         } catch (Exception e) {             e.printStackTrace();         }     } }

创建图片的缩略图 createThumbnail

private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)         throws InterruptedException, FileNotFoundException, IOException     {         // load image from filename           Image image = Toolkit.getDefaultToolkit().getImage(filename);         MediaTracker mediaTracker = new MediaTracker(new Container());         mediaTracker.addImage(image, 0);         mediaTracker.waitForID(0);         // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());           // determine thumbnail size from WIDTH and HEIGHT           double thumbRatio = (double)thumbWidth / (double)thumbHeight;         int imageWidth = image.getWidth(null);         int imageHeight = image.getHeight(null);         double imageRatio = (double)imageWidth / (double)imageHeight;         if (thumbRatio < imageRatio) {             thumbHeight = (int)(thumbWidth / imageRatio);         } else {             thumbWidth = (int)(thumbHeight * imageRatio);         }         // draw original image to thumbnail image object and           // scale it to the new size on-the-fly           BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);         Graphics2D graphics2D = thumbImage.createGraphics();         graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);         graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);         // save thumbnail image to outFilename           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);         quality = Math.max(0, Math.min(quality, 100));         param.setQuality((float)quality / 100.0f, false);         encoder.setJPEGEncodeParam(param);         encoder.encode(thumbImage);         out.close();     }

Java Reflection, 1000x Faster

A few weeks ago I got to make some of my code 1000 times faster, without changing the underlying complexity! As the title implies, this involved making Java reflection calls faster. Let me explain my use case as well, because it’s relatively general, and a good example of why one would use reflection in the […]

分析java进程假死情况

1 引言   1.1 编写目的   为了方便大家以后发现进程假死的时候能够正常的分析并且第一时间保留现场快照。   1.2编写背景   最近服务器发现tomcat的应用会偶尔出现无法访问的情况。经过一段时间的观察最近又发现有台tomcat的应用出现了无法访问情况。简单描述下该台tomcat当时具体的表现:客户端请求没有响应,查看服务器端tomcat的进程是存活的,查看业务日志的时候发现日志停止没有任何最新的访问日志。连tomcat下面的catalina.log也没有任何访问记录,基本断定该台tomcat已不能提供服务。   2 分析步骤   根据前面我描述的假死现象,我最先想到的是网络是否出现了问题,是不是有什么丢包严重的情况,于是我开始从请求的数据流程开始分析,由于我们业务的架构采用的是nginx+tomcat的集群配置,一个请求上来的流向可以用下图来简单的描述一下:       2.1检查nginx的网络情况   更改nginx的配置,让该台nginx请求只转到本机器的出现问题的tomcat应用上面,在access.log里看是否有网络请求,结果可以查看到当前所有的网络请求,也就是说可以排除是网络的问题。   2.2检查tomcat 的网络情况   分析业务配置的tomcat访问日志xxxx.log上是否有日志访问记录,经过查询该台tomcat应用日志完全没有任何访问记录,由于我们的部署是本机的nginx转到本机的tomcat应用,所以可以排除不是网络问题。到此基本可以断定网络没有问题,tomcat 本身出现了假死的情况。在tomcat的日志里有报过OutOfMemoryError的异常,所以可以肯定tomcat假死的原因是OOM   3 分析JVM内存溢出   3.1为什么会发生内存泄漏   在我们学习Java的时候就知道它最为方便的地方就是我们不需要管理内存的分配和释放,一切由JVM自己来进行处理,当Java对象不再被应用时,等到堆内存不够用时JVM会进行GC处理,清除这些对象占用的堆内存空间,但是如果对象一直被应用,那么JVM是无法对其进行GC处理的,那么我们创建新的对象时,JVM就没有办法从堆中获取足够的内存分配给此对象,这时就会导致OOM。我们出现OOM原因,一般都是因为我们不断的往容器里存放对象,然而容器没有相应的大小限制或清除机制,这样就容易导致OOM。   3.2快速定位问题   当我们的应用服务器占用了过多内存的时候,我们怎么样才能快速的定位问题呢?要想快速定位问题,首先我们必需获取服务器JVM某时刻的内存快照。Jdk里面提供了很多相应的命令比如:jstack,jstat,jmap,jps等等. 在出现问题后我们应该快速保留现场。   3.2.1 jstack   可以观察到jvm中当前所有线程的运行情况和线程当前状态.   sudo jstack -F 进程ID 输出内容如下: 从上面的图我们可以看到tomcat进程里面没有死锁的情况,而且每个线程都处理等待的状态。这个时候我们可以telnet命令连上tomcat的端口查看tomcat进程是否有任务回应。这时发现tomcat没有任何回应可以证明tomcat应用已没有响应处理假死状态。   3.2.2 jstat […]

ant build java generics,ANT编译泛型

用ant编译java项目的,报泛型错误,但eclipse却没有报错;报错如下: ScopeUtil.java:185: type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds boolean,java.lang.Object 代码如下 :  public static final boolean isSuperAdmin() {    return getSession(key_SuperAdmin); } @SuppressWarnings(“unchecked”) public static final <T> T getSession(String name) { ActionContext actionContext = ActionContext.getContext(); Map<String, Object> session = actionContext.getSession(); return (T) session.get(name); } 经过分析,发现isSuperAdmin返回是boolean而getSession,返回是Boolean,既返回对象与返回类型的区别,所以在ant编译时出错; 把代码改一下就可以了: public static final boolean isSuperAdmin() { Boolean superAdmin = getSession(key_SuperAdmin); return superAdmin == true; }

To solve the problem between JAXB2.1 and JDK1.6/6.0

Scenario 1 1.8. Using JAX-WS 2.1 with JavaSE6 JavaSE6 ships with JAX-WS 2.0 API in rt.jar, which causes some trouble when you try to run applications that use JAX-WS 2.1 API. This document collects information about how to solve this issue. 1.8.1. Endorsed directory One way to fix this is to copy jaxws-api.jar and jaxb-api.jar […]