免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1050 | 回复: 0
打印 上一主题 下一主题

Programming [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-18 01:25 |只看该作者 |倒序浏览

Java

  • Overview


  • Examples

  • Strings. Parsing
    comma-separated data.

  • Regexp. Pattern matching.


  • Date and time


  • IO


  • Files


  • Image processing


  • e-mail


  • Make an SQL query to database


  • XML

  • Execute an external
    application via Java

  • Obtain class info

    Overview
    Java is an object-oriented programming language. Switching to objectoriented
    programming (OOP) from other programming paradigms can be difficult. Java
    focuses on creating objects (data structures or behaviors) that can be assessed
    and manipulated by the program.
    Like other programming languages, Java provides support for reading and
    writing data to and from different input and output devices. Java uses processes
    that increase the efficiency of input and output, facilitate
    internationalization, and provide better support for non-UNIX platforms. Java
    looks over your program as it runs and automatically deallocates memory that is
    no longer required. This means you do not have to keep track of memory pointers
    or manually deallocate memory. This feature means a program is less likely to
    crash and that memory can not be intentionally misused.
    Java is related to C++, which is a direct descendent of C. Much of the
    character of Java is inherited from these two languages. From C, Java derives
    its syntax. Many of Java's object-oriented features were influenced by C++. In
    fact, several of Java's defining characteristics come from or are responses to
    its predecessors. Moreover, the creation of Java was deeply rooted in the
    process of refinement and adaptation that has been occurring in computer
    programming languages for the past three decades. For these reasons, this
    section reviews the sequence of events and forces that led up to Java. As you
    will see, each innovation in language design was driven by the need to solve a
    fundamental problem that the preceding languages could not solve. Java is no
    exception.
    Examples
    Strings. Parsing comma-separated data.
    CSV (comma-separated values) is quite frequently used in different
    applications. Many MS-Windows-based spreadsheets and some databases use CSV to
    export data.
    CSV is deceptive. It looks simple at first glance, but the values may be
    quoted or unquoted. Even more, the values may contain escaped quotes. These
    obstacles are beyond the StringTokenizer capabilities.
    ostermiller.com
    provides
    a set of classes that may easily help us to overcome the problem. The class
    below will parse a csv file and pop up an alert box with every single value from
    the file.
                              
    import com.Ostermiller.util.CSVParser;
    import java.io.InputStreamReader;
    import java.io.FileInputStream;
    import javax.swing.JOptionPane;
    public class CSVExample {
      public static void main(String[] args) throws Exception {
        CSVParser shredder = new CSVParser(
          new InputStreamReader(
            new FileInputStream("source.csv"))
          );
        String t;
        while ((t = shredder.nextValue()) != null) {
          JOptionPane.showMessageDialog(
          null,
          t,
          "Value from line " + shredder.getLastLineNumber(),
            JOptionPane.INFORMATION_MESSAGE
          );
        }
        System.exit(0);
      }
    }
    Regexp. Pattern matching.
    Regular expressions, or REs for short, provide a concise and precise
    specification of patterns to be matched in text. Java 2 did not include any
    facilities for describing regular expressions in text. This is mildly surprising
    given how powerful regular expressions are, how ubiquitous they are on the Unix
    operating system where Java was first brewed, and how powerful they are in
    modern scripting languages like sed, awk, Python, and Perl.
    Apache Jakarta
    RegExp
    project has achieved sufficient momentum to become
    nearly a standard. Apache has, in fact, two regular expressions packages. The
    second, Oro, provides full Perl5-style regular expressions, AWK-like regular
    expressions, glob expressions, and utility classes for performing substitutions,
    splits, filtering filenames, etc.
    import org.apache.regexp.*;
    public class RegExpTest {
      public static void main(String[] argv) throws RESyntaxException {
        //a patter string that we use to match a line.
        String pattern = "^Q[^u]\\d+\\.";
        //a source string for test.
        String input = "QA777. is the next flight. It is on time.";
        // Construct an RE object
        RE r = new RE(pattern);
        // Use RE to match an input.
        boolean found = r.match(input);
        System.out.println(pattern + (found ? " matches " : " doesn't match ") + input);
      }
    }
    Date and time
    To find out todays date:
    System.out.println(new java.util.Date());
    Use formatted date:
    Date dNow = new Date();
    System.out.println("It is now " + dNow.toString());
    // Use a SimpleDateFormat to print the date our way.
    SimpleDateFormat formatter = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
    System.out.println("It is " + formatter.format(dNow));
    Computing difference between two dates.
    import java.util.*;
           
    public class DateDiff {
      public static void main(String[] av) {
        Date d1 = new GregorianCalendar(1999,11,31,23,59).getTime( );
        Date d2 = new Date();
        long diff = d2.getTime() - d1.getTime();
        System.out.println("Difference between " + d2 +
                           "\n" + "\tand Y2K is " +
                           (diff / (1000*60*60*24)) +" days.");
        }
    }
    Comparing dates:
    import java.util.*;
    import java.text.*;
    public class CompareDates {
      public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
        Date d1 = df.parse(args[0]);
        Date d2 = df.parse(args[1]);
        String relation;
        if (d1.equals(d2))
          relation = "the same date as";
        else if (d1.before(d2))
          relation = "before";
        else
          relation = "after";
        System.out.println(d1 + " is " + relation + ' ' + d2);
      }
    }
    IO
    First of all, here's a small example of how to set up input and output
    streams.
    import java.io.*;
    class Streams {
    public static void main(String[] args) throws IOException {
      BufferedInputStream in = new BufferedInputStream(
                                 new FileInputStream(
                                   "test.in"));
      PrintStream out = new PrintStream(
                          new BufferedOutputStream(
                            new FileOutputStream("test.out")));
      System.setIn(in);
      System.setOut(out);
      System.setErr(out);
      BufferedReader br = new BufferedReader(
                            new InputStreamReader(System.in));
      String s;
      while((s = br.readLine()) != null)
        System.out.println(s);
        out.close(); // Remember this!
      }
    }
    And also the object serialization example could be useful. Object
    serialization allows to take any object that implements the Serializable
    interface and turn it into a sequence of bytes that can later be fully restored
    to regenerate the original object.
    To serialize an object, the OutputStream object is created and then wrap it
    inside an ObjectOutputStream object. After that use writeObject() and the object
    is serialized and sent to the OutputStream. To restore the object wrap an
    InputStream inside an ObjectInputStream and call readObject(). What comes back
    is, as usual, a reference to an upcast Object we have to downcast to set things
    straight.
    //MyClass.java
    import java.io.Serializable;
    public class MyClass implements Serializable {
      public Integer i = new Integer(10);
    }
    //ClassSaver.java
    import java.io.*;
    public class ClassSaver {
      public static void main(String[] args) throws IOException {
        ObjectOutput out = new ObjectOutputStream(
                             new FileOutputStream("file.out"));
        MyClass mc = new MyClass();
        out.writeObject(mc);
      }
    }
    //ClassRestorer.java
    import java.io.*;
    public class ThawAlien {
      public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(
                                 new FileInputStream("file.out"));
        Object o = in.readObject();
        System.out.println(o.getClass());
      }
    }
    Files
    The File class has a number of "informational" methods. To use any of these,
    you must construct a File object containing the name of the file it is to
    operate upon.
    import java.io.*;
    import java.util.*;
    public class Status {
      public static void main(String[] argv) throws IOException {
        if (argv.length == 0) {
          System.err.println("Usage: Status filename");
          System.exit(1);
        }
        for (int i = 0; i
    Image processing
    Identify animated GIF
    Once I needed to identify if a GIF encoded picture was animated. The
    procedure shown below worked quite well for me
      /**
       * Get encoding name, like "GIF" or "JPEG"
       * @param byte[] bytes - source bytes of a picture
       * @return String - returns "GIF" if the set of source bytes represent a gif encoded image,
       *                - returns "JPEG" if the set of source bytes represent a jpeg encoded image
       *                - throws exception if neither of above
       */
      public static String getSourseFormatName(final byte[] bytes) throws Exception{
        InputStream in = new ByteArrayInputStream(bytes);
        int a = in.read() & 0xff;
        int b = in.read() & 0xff;
          
        if (a==71 && b==73){ //71 = "G" and //74 = "I"
          // this is GIF
          // now we'll find out if it is an animated GIF
          in.skip(8);
          // read Logical Screen Descriptor's packed field
          int k = in.read() & 0xff;
          // no need for the rest two bytes in the Logical Screen Descriptor
          in.skip(2);
          int colorTable = 0;
          //if the first byte is '1' then there's the Global Color Table present
          if (k > 127){
            //calculate number of bytes to be skiped in Global Color Table
            colorTable = k & 0x07;
            int toSkip = 3 * (int)Math.pow(2.0,(double)(colorTable+1));
            in.skip(toSkip);
            // just after the Global Color Table there's the animation descriptor:
            // byte   1       : 33 (hex 0x21) GIF Extension code
            // byte   2       : 255 (hex 0xFF) Application Extension Label
            // byte   3       : 11 (hex (0x0B) Length of Application Block (eleven bytes of data to follow)
            int A = in.read() & 0xff; // mask the most significant byte
            int B = in.read() & 0xff;
            int C = in.read() & 0xff;
            if(A==33 && B==255 && C==11){
              throw new Exception("Animated GIF! I will not process it.");
            }
          }
          return "GIF";
        }else if (a==255 && b==216){// 255="J" and 216="P"
          //this is JPEG
          return "JPEG";
        }else{
          throw new Exception("Unknown format! I will not process it.");   
        }
      }
    Writing JPEG image with predefined quality.
    The method below shows how to write a JPEG encoded image with predefined
    quality.
    /*need following imports*/                                  
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    ...
      /**
       * Writes JPEG with a given quality a target file.
       * @param BufferedImage im - rendered picture
       * @param float quality - quality of jpeg compression. 0.0
    Converting array of bytes to a BafferedImage object.
    Consider that you have read in an image file and you have now an array of
    bytes representing this file. To obtain a BufferedImage object for further image
    processing use javax.imageio.ImageIO class (introdiced in JDK 1.4).
      /**
      * byte[] to BufferedImage
       * @param bytes
       * @return BufferedImage
       * @exception IOException
       */
      public static BufferedImage getBufferedImageFromBytes(final byte[] bytes)
      throws IOException {
        ByteArrayInputStream ba = new ByteArrayInputStream(bytes);
        BufferedImage buf = ImageIO.read(ba);
        ba.close();
        return buf;
      }
    Image dithering
    Dithering is a technique for digital haftoning. Dithering can be accomplished
    by tresholding the image against a dither matrix. The elements
    of dither matrix are thresholds. The matrix is laid like a tile
    over the entire image and each pixel is compared to the corresponding threshold.
    The pixel becomes white if its value exceeds the threshold or black
    otherwise.
        public static BufferedImage ditherByMatrix(int[][] matrix, BufferedImage sourceImage) {
            // Create binary image to hold result
            int w = sourceImage.getWidth();
            int h = sourceImage.getHeight();
            BufferedImage ditheredImage =
             new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
            Raster input = sourceImage.getRaster();
            WritableRaster output = ditheredImage.getRaster();
            int n = matrix.length;
            for (int y = 0; y  threshold)
                  output.setSample(x, y, 0, 1);
                    }
            return ditheredImage;
        }
    e-mail
    import java.io.IOException;
    import java.io.PrintStream;
    import sun.net.smtp.*;
    public class HelloMail {
    public static void main(String[] args){
        String smtpServer; // assign your smtp
        String fromAddr;   // from
        String toAddr;     // to
        try {
          SmtpClient sc = new SmtpClient(smtpServer);
          sc.from(fromAddr);
          sc.to(toAddr);
          PrintStream ps = sc.startMessage();
          ps.println("Subject: this is a test");
          ps.println();
                           
          ps.println("Hello there!");
          sc.closeServer();
        }catch (IOException e){
          System.err.println(e);
          System.out.println("Sorry, your mail can't be sent.");
        }
      }
    }
    Make an SQL query to database
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    /** Load a driver and connect to a database and return connection.*/
    public class Connect {
      public static Connection getConnection() {
        String dbURL = "jdbc:odbc:Companies"; //any database URL
        try {
          // Load the jdbc-odbc bridge driver
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          // Enable logging
          DriverManager.setLogStream(System.err);
          System.out.println("Getting Connection");
          Connection conn = DriverManager.getConnection(dbURL, "user", "password"); // set user and password
          SQLWarning warn = conn.getWarnings();
          while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message: " + warn.getMessage());
            System.out.println("Vendor: " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
          }
          PreparedStatement stmt = conn.prepareStatement("SELECT user_name, full_name from userdb where id=?");
          stmt.setInt(1, 12345);
          ResultSet rs = stmt.executeQuery();
          
          // Now retrieve (all) the rows that matched the query
          while (rs.next()) {
            String name = rs.getString(1);
            String fullName = rs.getString(2);
            System.out.println("User " + name + " is named " + fullName);
          }
          
        } catch (ClassNotFoundException e) {
          System.out.println("Can't load driver " + e);
        } catch (SQLException e) {
          System.out.println("Database access failed " + e);
        } finally {
          try {
            rs.close(); // All done with that resultset
          } finally {
            try {
              stmt.close(); // All done with that statement
            } finally {
              conn.close(); // All done with that DB connection
            }
          }
        }
      }
    }
    XML
    Here's an example of simple XML tree construction using DOM.
    /*need some special imports*/                                  
    import org.apache.crimson.tree.AttributeNode;
    import org.apache.crimson.tree.XmlDocument;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    ...
    public static void itemList(HashSet items, File out)
    throws IOException{
      FileOutputStream fs = new FileOutputStream(out);
      XmlDocument xmlDoc = new XmlDocument();
      Node root = xmlDoc.createElement("root");
      xmlDoc.appendChild(root);
      for(Iterator i = items.iterator(); i.hasNext();){
        String item = (String)i.next();
        Node item = xmlDoc.createElement("item");
                
        Attr itemId = xmlDoc.createAttribute("id");
        itemId.setValue(item);
        item.getAttributes().setNamedItem(itemId);
                
        xmlDoc.write(fs);
        fs.close();
      }
    }
    Execute an external application via Java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class Executor {
            public static void main(String[] args) throws java.io.IOException {
                Process p = Runtime.getRuntime().exec(args[0]);
              
                // uncomment the following code in case you'd like to read
                // the output from executed application
                /*
                String line;
                BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = is.readLine( )) != null) {
                  System.out.println(line);
                }
                */  
            }
    }
    Obtain class info
    import java.lang.reflect.*;
    public class ListMethods {
      public static void main(String[] argv) throws ClassNotFoundException {
        if (argv.length == 0) {
          System.err.println("Usage: ListMethods className");
          return;
        }
        Class c = Class.forName(argv[0]);
        Constructor[] cons = c.getConstructors();
        printList("Constructors", cons);
        Method[] meths = c.getMethods( );
        printList("Methods", meths);
      }
      static void printList(String s, Object[] o) {
        System.out.println("*** " + s + " ***");
        for (int i=0; i
    by ant
                   
                   
                   

    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/52454/showart_692425.html
  • 您需要登录后才可以回帖 登录 | 注册

    本版积分规则 发表回复

      

    北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
    未成年举报专区
    中国互联网协会会员  联系我们:huangweiwei@itpub.net
    感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

    清除 Cookies - ChinaUnix - Archiver - WAP - TOP