Java常用的一些工具方法

导读:本篇文章讲解 Java常用的一些工具方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

       因为自己在开发中,遇到很多一些比较常用的工具类方法,有时候写了又不记得了,然后又要花很多时间去整理和查阅资料,很苦恼,所以就把自己开发中遇到的一些工具类方法记录下来,也方便更多的人一起学习。别忘记了,,我这可是随时更新的哦~~我相信,对你是非常有用的,所以想了解更新和更多的干活的,就必须要加我粉丝哈~~!!咳咳,好了,进入正文~~~~~

一:将中文转为拼音

/**
	 * 得到 全拼
	 * 
	 * @param src
	 * @return
	 */
	public static String getPingYin(String src) {
		char[] t1 = null;
		t1 = src.toCharArray();
		String[] t2 = new String[t1.length];
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String t4 = "";
		int t0 = t1.length;
		try {
			for (int i = 0; i < t0; i++) {
				// 判断是否为汉字字符
				if (java.lang.Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
					t4 += t2[0];
				} else {
					t4 += java.lang.Character.toString(t1[i]);
				}
			}
			return t4;
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		return t4;
	}

二:获取中文的第一个字母

/**
	 * 得到中文首字母
	 * 
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {

		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}

三:将字符串转为ASCII码

public static String getCnASCII(String cnStr) {
		StringBuffer strBuf = new StringBuffer();
		byte[] bGBK = cnStr.getBytes();
		for (int i = 0; i < bGBK.length; i++) {
			// System.out.println(Integer.toHexString(bGBK[i]&0xff));
			strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
		}
		return strBuf.toString();
	}

四:这里说一个非常重要的地方,就是关于文件流的知识(非常非常重要~~~~~~)

首先说一下,这下面就是完整的几个实例了,如果你有自己的需要,只要看懂我写的代码就自行更改就可以了,我相信都可以看懂的,因为真的真的写得很简单了~·(这些自己还是用心进行编写了的哈~!)

(1)读取TXT文件

package com.hnu.scw.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author scw
 * 2017-11-12
 * function: 读取txt文件的内容
 *
 */
public class ReadTxtContent {

	/**
	 * 读取txt文件
	 * @param fileName:需要读取txt文件的路径
	 * @return 返回读取到的内容,保存的是在一个list集合中
	 */
	public static List<String> readTxt(String fileName){		
		try {
			File file = new File(fileName);
			//判断读取的文件是否有,如果没有就创建一个空的,其实这里不处理也可以,因为抛了异常
			if(!file.exists()){
				file.createNewFile();
			}
			//打开读取txt文件流
			FileInputStream fr = new FileInputStream(file);
			InputStreamReader af=new InputStreamReader(fr);
			BufferedReader bf=new BufferedReader(af);
			//用于存储读取到的内容
			List<String> content = new ArrayList<String>();
			String line=bf.readLine();
			content.add(line);			
			while(line!=null) //判断是否读取到最后
			{
				line=bf.readLine();	
				//保存读取内容
				content.add(line);		
			}
			return content;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}

}

(2)读取Excl文件—–后缀为.xls

package com.hnu.scw.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * 读取Excl表格中的内容,主要后缀是.xls的
 * @author scw
 * 2017-11-12
 * 备注:要使用这个方法的时候,记得要导入lib中包含的包
 *
 */
public class ReadExclContent {

	/**
	 * 读取Excl表格内容
	 * @param exclFile:excl路径
	 * @return
	 */
	public static List<String> readExcl(String exclFile){
		Workbook rwb = null;
		InputStream is;
		try {
			is = new FileInputStream(exclFile);
			rwb = Workbook.getWorkbook(is);
		}catch (Exception e) {
			e.printStackTrace();
		} 
		int sheets = rwb.getNumberOfSheets();
		Sheet rs = rwb.getSheet(0);
		String sheetName = rs.getName();// 获取Sheet的名称
		int rsColumns = rs.getColumns();// 获取Sheet表中所包含的总列数	
		int rsRows = rs.getRows(); // 获取Sheet表中所包含的总行数	
		List<String> list = new ArrayList<String>();
		//获取到第一列标题的内容
		String[] head = new String[rsColumns];		
		//注意getCell方法是先列,后行的取法	
		Cell c = null;
		for(int i = 0 ; i < rsColumns ; i++){
			c = rs.getCell(i, 0);//获取到标题栏的每一列的内容;	
			head[i] = c.getContents();
		}
		
		Cell cell = null;
		int currentReadIndex = 1 ; //用于记录当前读取的内容条数 
		for (int j = 1; j < rsRows; j++) { //遍历总行数,从第一行开始读取	
			cell = rs.getCell(0, j);    //获取对应行第一列的对象
			if(Integer.parseInt(cell.getContents()) == 0){  //(1)这里0表示是选择题,过滤掉判断题
				cell = rs.getCell(1, j);    //获取到对应第二列的单元格对象
				//(2)判断题目的章节是是否是小于等于第四章的,因为这次只需要考到前面四章的内容
				if(Integer.parseInt(cell.getContents()) <= 4){	
					for (int i = 2; i < rsColumns; i++) {//遍历总列数		
						cell = rs.getCell(i, j);
							if(i == 2 ){ 				//(3)这里我要序号,所以要分情况,第一列我就换成序号了
								list.add( currentReadIndex + ":" + cell.getContents());
								currentReadIndex++ ;
							}
							else { //(4)因为前面两列的处理不需要这里进行,所以过滤掉了
								list.add(head[i] + cell.getContents());
							}
						}			
					}
				//读取完一个单元格内容就换行,这里就用@@表示需要换后,写操作的时候再处理(当然这个根据需要来的,不需要就不换行)
				list.add("@@");
			}			
		}
		return list;
	}

}

(3)写数据到TXT中

package com.hnu.scw.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 
 * @author scw
 *2017-11-12
 *function : 将数据写入到Txt文件中
 */
public class Write2Txt {

	/**
	 * 将数据写入到TXT文件
	 * @param list : 数据内容,这里用的是list集合作为参数内容
	 * @param fileName :要写入的文件名
	 */
	public static void writeContent2Txt(List<String> contentList , String fileName){
		File writeTxt = new File(fileName);
		//判断是否有这个文件了
		if(!writeTxt.exists()){ //如果不存在,则创建这个txt文件
			try {
				writeTxt.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//开启写操作
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(writeTxt));
			int writeLength = contentList.size(); // 获取到进行写的内容的大小长度
			String currentContent = "";
			for(int i = 0 ; i < writeLength ; i++){
				currentContent = contentList.get(i); //得到当前的内容
				if("@@".equals(currentContent)){ //如果读取的内容为@@,表示的是换行
					bw.write("\r\n"); // "\r\n"表示换行
				}else{
					bw.write(currentContent);
					bw.write("\r\n"); // "\r\n"表示换行
				}
			}
			bw.flush();
			bw.close(); //关闭流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}

(4)写数据到doc文档中

package com.hnu.scw.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;
/**
 * 
 * @author scw
 * 2017-11-12
 * function: 写数据到.doc后缀的文档中
 *
 */
public class Write2Word {
	
	/**
	 * 读取数据,并写入到doc的文件中
	 * @param contentList 需要写的源数据内容
	 * @param fileName 写到的文件路径,比如F:\\text.doc
	 */
	public static void writeContent2Word(List<String> contentList , String fileName){
		try {
			File file = new File(fileName);
			//判断目标路径是否存在
			if(!file.exists()){
				file.createNewFile();
			}
			//打开文件输出流
			FileOutputStream fo=new FileOutputStream(file);
			OutputStreamWriter osw=new OutputStreamWriter(fo);
			BufferedWriter bw=new BufferedWriter(osw);
			//获取读取的长度的大小
			int contentLength = contentList.size();
			String content = "";
			for(int i = 0 ; i < contentLength; i++){
				//获取需要写的内容
				content = contentList.get(i);				
				bw.write(content);
				//换行
				bw.newLine();
				//刷新缓存区
				bw.flush();
			}
		} 	
		catch (Exception e) {
		e.printStackTrace();
		}
	}

}

(5)写数据到PDF中

package com.hnu.scw.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 写数据到PDF
 * @author scw
 * 2017-11-12
 * function:将数据转为PDF形式
 *
 */
public class Write2PDF {
	/**
	 * 将数据写成pdf的形式
	 * @param filName:写入的目标文件路径
	 * @param contentList :写入的数据,我这里用的是list(具体问题具体的分析)
	 */
	public static void writeContent2PDF(String filName , List<String> contentList){
		try {  
			//加载路径
			File file = new File(filName);
			if(!file.exists()){ //如果没有存在这个文件,那么就创建
				file.createNewFile();
			}
			//打开写操作流
            OutputStream os = new FileOutputStream(file);  
            //创建一个文件对象
            Document document = new Document();  
            //初始化pdf写对象
            PdfWriter.getInstance(document, os); 
            //打开pdf对象
            document.open();  
            //设置写pdf的字体样式(这里设置主要是解决中文的问题,如果不用的话是输出不了中文的)
            BaseFont baseFont = BaseFont.createFont("/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);    
            Font font = new Font(baseFont);
            //创建一个pdf的段页对象,其实就是相当于一个list保存所有的内容,但是这里还可以设置pdf写的样式,非常有用哦
            Paragraph pg = new Paragraph("",font);
            //开始写操作
            int writeLength = contentList.size(); // 获取到进行写的内容的大小长度
            String currentContent = "";       
            for(int i = 0 ; i < writeLength ; i++){
            	currentContent = contentList.get(i); //得到当前的内容
            	//如果读取的内容为@@,表示的是换行(这里都是根据输入的内容来进行对应操作的,如果你的数据里面并不是这样的形式,那么根据自己的形式进行控制就是了)
            	if("@@".equals(currentContent)){ 
            		pg.add("\n");    //添加一个换行,表示读取一个段落完成了(因为我这数据里面是想把@@分割的内容分为一个段落,所以才这样处理的哦)     		
				}else{
					//将要写入的内容加入到pg对象中
					pg.add(currentContent);    
					//添加一个换行
					pg.add("\n"); 
				}
            }
          //将之前所有的内容进行真正写入到pdf文件中
    		document.add(pg);  
            //关闭文件流
            document.close();  
            //关闭输出流对象
            os.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}

}

备注:这里需要导入poi.jar包和itext包,,这个都可以在网上找到的,不过我也在把这几个贴出来吧。。另外,解决中文的问题,还需要一个字体包,,这里也出来了~~

Java常用的一些工具方法

上面几个方法的测试:(真实的案例,全部通过)

package com.hnu.scw.main;
import java.util.List;

/**
 * 
 * @author scw
 *2017-11-12
 *function : 多种文件流的操作
 */
import com.hnu.scw.util.ReadExclContent;
import com.hnu.scw.util.Write2PDF;
import com.hnu.scw.util.Write2Txt;
import com.hnu.scw.util.Write2Word;

public class Excl2Txt {
	public static void main(String[] args) {
		//Excl表的路径
		String exclFile = "F:\\csappquestion.xls";
		//获取到Excl表格的内容
		List<String> readResult = ReadExclContent.readExcl(exclFile);
		//将数据写入到Txt文件中
		//String fileName1 = "F:\\csapp1.txt";
		//Write2Txt.writeContent2Txt(readResult, fileName1);
		//将数据写入到pdf文件中
		//String fileName2 = "F:\\csapppdf.pdf";
		//Write2PDF.writeContent2PDF(fileName2, readResult);
		String fileName3 = "F:\\csappword.doc";
		Write2Word.writeContent2Word(readResult, fileName3);
	}

}

五:下面提供几个常用的代码段吧(我觉得还是比较实用的,不常用就一下忘记了)

(1)得到当前方法的名字

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

(2)转字符串到日期

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

或者

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
Date date = format.parse( myString );

(3)JDBC连接Oracle

public class OracleJdbcTest  {  
    String driverClass = "oracle.jdbc.driver.OracleDriver";  

    Connection con;  

    public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  
    {  
        Properties props = new Properties();  
        props.load(fs);  
        String url = props.getProperty("db.url");  
        String userName = props.getProperty("db.user");  
        String password = props.getProperty("db.password");  
        Class.forName(driverClass);  

        con=DriverManager.getConnection(url, userName, password);  
    }  

    public void fetch() throws SQLException, IOException  
    {  
        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
        ResultSet rs = ps.executeQuery();  

        while (rs.next())  
        {  
            // do the thing you do  
        }  
        rs.close();  
        ps.close();  
    }  

    public static void main(String[] args)  
    {  
        OracleJdbcTest test = new OracleJdbcTest();  
        test.init();  
        test.fetch();  
    }  
}

(4)把Java中的Date转为sql中的date

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

(5)
使用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();  
            }  
        }  
    }

(6)创建图片的缩略图

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();  
    }

(7)生成JSON格式数据(要导入json-rpc.jar包哦,当然还有其他的json包也可以)

JSONObject json = new JSONObject();  
json.put("city", "Mumbai");  
json.put("country", "India");  
String output = json.toString();

(8)抓屏程序(这个还是比较实用的呢。。。。也是偶尔看到的,觉得比较有意思)

import java.awt.Dimension;  
import java.awt.Rectangle;  
import java.awt.Robot;  
import java.awt.Toolkit;  
import java.awt.image.BufferedImage;  
import javax.imageio.ImageIO;  
import java.io.File;  
public void captureScreen(String fileName) throws Exception {  
   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));  
}  

(9)创建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();  
    }  
}

(10)解析/读取XML文件,(我想这个很多Java开发者都对这个有印象的吧。。因为很重要和常用呀)

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>

Java代码:

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: " 
                                    + nodeList.item(0).getChildNodes().item(0)  
                                            .getNodeValue());  

                            nodeList = e.getElementsByTagName("age");  
                            System.out.println("Age: " 
                                    + nodeList.item(0).getChildNodes().item(0)  
                                            .getNodeValue());  
                        }  
                    }  
                } else {  
                    System.exit(1);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
    public static void main(String[] args) {  

        XMLParser parser = new XMLParser();  
        parser.getAllUserNames("c:\\test.xml");  
    }  
}

(11)发送邮件(这个在Web开发中,用得还是比较多的,大家可以看看)

import javax.mail.*;  
import javax.mail.internet.*;  
import java.util.*;  

public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException  
{  
    boolean debug = false;  

     //Set the host smtp address  
     Properties props = new Properties();  
     props.put("mail.smtp.host", "smtp.example.com");  

    // create some properties and get the default Session  
    Session session = Session.getDefaultInstance(props, null);  
    session.setDebug(debug);  

    // create a message  
    Message msg = new MimeMessage(session);  

    // set the from and to address  
    InternetAddress addressFrom = new InternetAddress(from);  
    msg.setFrom(addressFrom);  

    InternetAddress[] addressTo = new InternetAddress[recipients.length];  
    for (int i = 0; i < recipients.length; i++)  
    {  
        addressTo[i] = new InternetAddress(recipients[i]);  
    }  
    msg.setRecipients(Message.RecipientType.TO, addressTo);  

    // Optional : You can also set your custom headers in the Email if you Want  
    msg.addHeader("MyHeaderName", "myHeaderValue");  

    // Setting the Subject and Content Type  
    msg.setSubject(subject);  
    msg.setContent(message, "text/plain");  
    Transport.send(msg);  
}

六:Java读取Properties文件的方法(主要是说明Properties类的使用)

1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2。使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3。使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4。使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

七:JavaBean中的内省机制,来获取到JavaBean中对应属性的set或者get方法,或者获取到JavaBean中所有的set和get方法

说一下内省机制,这个其实用得地方挺多的,就比如在J2EE开发的时候,servlet后台接受到JSP传送过来的参数;如果参数个数不多,那么直接用request.getparemater()方法就可以了,但是如果多了的话,就很麻烦了对不对呢?再说一下SpringMvc中进行参数接受的时候采取的Model类,这个大家应该都知道吧。其实之所以能够把前端传送的参数都接受,就是有用到了内省机制的。所以,简单点说,内省机制就是能够获取和封装到JavaBean中的属性和方法。。。(SpringMvc的底层源码真的写得很好,可以看看)

进入真正的方法:

JavaBean———-User     (就用这个吧。大家用的多,熟悉些)

public class User {  
    private String name;  
    private int age;  
    public User(String name, int age) {  
        this.name = name;  
        this.age = age;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
}  

获取方法:

public class Test {  
    public static void main(String[] args) throws IntrospectionException, InvocationTargetException,  
            IllegalAccessException {  
        User user =new User("zhangsan", 21);  
        String propertyName = "name";  //设置要获取JavaBean中的属性名
        PropertyDescriptor pd=new PropertyDescriptor(propertyName, user.getClass());// 指定获取属性  
        Method readMethod = pd.getReadMethod();//获取到读方法,这个其实就是相当于get方法(反射机制)  
        Object invoke = readMethod.invoke(user, null);// 反射机制调用  
        System.out.println("名字:" + invoke);  
        pd.getWriteMethod().invoke(user, "lisi");  //这个就是相当于set方法
        invoke = readMethod.invoke(user, null);  
        System.out.println("名字:" + invoke);   //通过运行结果来看看
  
        // 获取整个Bean的信息   
        BeanInfo beanInfo= Introspector.getBeanInfo(user.getClass(), Object.class);// 在Object类时候停止检索,可以选择在任意一个父类停止  
  
        System.out.println("所有属性描述:");  
        PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();// 获取所有的属性描述  
        for (PropertyDescriptor propertyDescriptor: pds) {  
            System.out.println(propertyDescriptor.getName());  
        }  
        System.out.println("所有方法描述:");  
        for (MethodDescriptor methodDescriptor: beanInfo.getMethodDescriptors()) {  
            System.out.println(methodDescriptor.getName());  //获取到方法的名字
//            Method method = methodDescriptor.getMethod();   //获取到方法,如果需要使用再里面反射方法invake
        }  
    }  
}  

八:

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/12434.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!