Java-工程中常用的程序片段

1.字符串-整型相互转换

String s = String.valueOf(2);
int a = Integer.parseInt(s);

2.向文件末尾添加内容

BufferedWriter bufferedWrite = null;
        try {
            bufferedWrite = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\2.txt",true));
            bufferedWrite.write("hello java file writer ");
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            if ( bufferedWrite != null ) {
                bufferedWrite.close();
            }
        }

3.得到当前方法的名字

String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

4.转字符串到日期

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        String d = "2008-07-10 20:23:30";
        try {
            Date date = simpleDateFormat.parse(d);
            System.out.println(date.toString());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

5.使用JDBC连接MySQL

package com.fpc.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class MySqlJdbcTest {
    private String driverClass = "com.mysql.jdbc.Driver";
    private Connection connection;
    
    //connection
    public void init(FileInputStream fs) throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        properties.load(fs);
        String url = properties.getProperty("url");
        String username = properties.getProperty("name");
        String password = properties.getProperty("password");
        Class.forName(driverClass);
        connection = DriverManager.getConnection(url,username,password);
    }
    
    //fetch
    public void fetch () throws SQLException {
        String sql = "select * from student";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while ( rs.next() ) {
            System.out.println(rs.getString("s_name"));
        }
        rs.close();
        ps.close();
    }
    public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
        MySqlJdbcTest test = new MySqlJdbcTest();
        File file = new File("C:\\Users\\Administrator\\Desktop\\db.properties");
        FileInputStream fs = new FileInputStream(file);
        test.init(fs);
        test.fetch();
    }
}

6.把Java.util.Date转成Java.sql.Date

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

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

public static void fileCopy(File in ,File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        //magic number for windows,64MB -32Kb
        int maxCount = (64*1024*1024) - (32*1024);
        long size = inChannel.size();
        int position = 0;
        while ( position < size ) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }
        if ( inChannel != null ) {
            inChannel.close();
        }
        if ( outChannel != null ) {
            outChannel.close();
        }
    }

8.创建JSON格式的数据

下载jar文件 json-rpc-1.0.jar

        JSONObject json = new JSONObject();
        json.put("name","fpc");
        json.put("age", 22);
        String str = json.toString();

 9.使用iText JAR生成PDF

Download itextpdf-5.4.1.jar

public static void main(String[] args) throws IOException, DocumentException{
        OutputStream file = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\test.pdf"));
        Document document = new Document();
        PdfWriter.getInstance(document, file);
        document.open();
        document.add(new Paragraph("Hello Fpc"));
        document.add(new Paragraph(new Date().toString()));
        document.close();
        file.close();
    }

10.抓屏程序

public void captureScreen(String fileName) throws IOException, AWTException {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(fileName));
    }

11.解析/读取XML文件

package com.fpc.Test;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLParser {
    public void getAllUserNames(String fileName) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File file = new File(fileName);
        
        if ( file.exists() ) {
            Document doc = db.parse(file);
            Element docElement = doc.getDocumentElement();
            
            //Print root element of the document
            System.out.println("Root element of the document: " + docElement.getNodeName());
            
            NodeList studentList = docElement.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 element = (Element) node;
                        NodeList nodeList = element.getElementsByTagName("name");
                        System.out.println("Name : " + nodeList.item(0).getChildNodes().item(0).getNodeValue());
                        
                        nodeList = element.getElementsByTagName("grade");
                        System.out.println("Grade : " + nodeList.item(0).getChildNodes().item(0).getNodeValue());
                        
                        nodeList = element.getElementsByTagName("age");
                        System.out.println("Age : " + nodeList.item(0).getChildNodes().item(0).getNodeValue());
                    } else {
                        System.exit(1);
                    }
                }
            }
        }
    }
    
    public static void main( String[] args ) throws ParserConfigurationException, SAXException, IOException {
        XMLParser xmlparser = new XMLParser();
        xmlparser.getAllUserNames("C:\\Users\\Administrator\\Desktop\\test.xml"); 
    }
}

12.把Array转成Map

commons-lang3-3.7.jar

public static void main( String[] args )  {
        String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },  
                { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };  
        Map<Object, Object> countriesCapitical = ArrayUtils.toMap(countries);
        //traverse
        for ( Map.Entry<Object, Object> entry : countriesCapitical.entrySet()) {
            System.out.println(entry.getKey() + "   " + entry.getValue());
        }
        
    }

 

posted @ 2017-11-28 15:33  起床oO  阅读(190)  评论(0编辑  收藏  举报