常用方法

本文介绍了一个包含多种Java实用工具方法的类,包括文件操作、日期转换、图像处理等功能。涉及文件追加写入、字符串转日期、创建图片缩略图、屏幕截图、文件目录操作、发送邮件及文件压缩等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Test {

	/**
	 * @param args
	 * @throws IOException 
	 */
	private static final Log logger =LogFactory.getLog(Test.class.getName());
	
	/**
	 * 向文件末尾添加内容
	 * @throws IOException
	 */
	public void addStr() throws IOException{
		String filename="D:\\lll.txt";
		BufferedWriter out = null;  
		try {  
		    out = new BufferedWriter(new FileWriter(filename, true));  
		    out.write("woshihoulaide");  
		} catch (IOException e) {  
		    // error processing code  
		} finally {  
		    if (out != null) {  
		        out.close();  
		    }  
		} 
	}
	
	/**
	 * 转字符串到日期
	 * @throws ParseException 
	 */
	public void strToDate() throws ParseException{
		SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
		java.util.Date date = format.parse( "2012-01-03 22:00" ); 
	}
	
	
	/**
	 * 创建图片的缩略图
	 * @param filename
	 * @param thumbWidth
	 * @param thumbHeight
	 * @param quality
	 * @param outFilename
	 * @throws InterruptedException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)  
	        throws InterruptedException, FileNotFoundException, IOException  
	    {  
	        Image image = Toolkit.getDefaultToolkit().getImage(filename);  
	        MediaTracker mediaTracker = new MediaTracker(new Container());  
	        mediaTracker.addImage(image, 0);  
	        mediaTracker.waitForID(0);  
	        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);  
	        }  
	        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);  
	        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();  
	    } 

	/**
	 * 抓屏 1000
	 * @param fileName
	 * @throws Exception
	 */
	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));  
		}  
	
	/**
	 * 列出文件目录
	 */
	public void listPath(){
		
		File dir = new File("D:\\");  
		String[] children = dir.list();  
		if (children == null) {  
		} else {  
			for (int i=0; i < children.length; i++) {  
				String filename = children[i];  
			}  
		}  
		FilenameFilter filter = new FilenameFilter() {  
			public boolean accept(File dir, String name) {  
				return !name.startsWith(".");  
			}  
		};  
		children = dir.list(filter);  
		File[] files = dir.listFiles();  
		FileFilter fileFilter = new FileFilter() {  
			public boolean accept(File file) {  
				return file.isDirectory();  
			}  
		};  
		files = dir.listFiles(fileFilter); 
		logger.info(files[6]);
	}
	
	
	/**
	 * send mail
	 * @param recipients
	 * @param subject
	 * @param message
	 * @param from
	 * @throws MessagingException
	 */
	public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException  
	{  
	    boolean debug = false;  
	     Properties props = new Properties();  
	     props.put("mail.smtp.host", "smtp.example.com");  
	    Session session = Session.getDefaultInstance(props, null);  
	    session.setDebug(debug);  
	    Message msg = new MimeMessage(session);  
	    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);  
	    msg.addHeader("MyHeaderName", "myHeaderValue");  
	    msg.setSubject(subject);  
	    msg.setContent(message, "text/plain");  
	    Transport.send(msg);  
	} 
	
	/**
	 * 创建压缩文件
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception  {
		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();  
            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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值