当前位置: 首页 > news >正文

用JAVA API解决几个实际问题

JAVA作为目前最流行和实用的语言,它众多强大的API可以帮助我们完成很多事情。

Google JAVA编程风格指南 http://hawstein.com/posts/google-java-style.html .


 

1.Jxl.jar

支持对Excel的读写操作。

可以相当于操作数据库了。

import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import java.io.*;

public class Read_excel {
    public static void main(String[] args) throws BiffException, IOException,
            RowsExceededException, WriteException {
        Workbook from = Workbook.getWorkbook(new File("test.xls"));
        Sheet f_sheet = from.getSheet(0);
        WritableWorkbook to = Workbook.createWorkbook(new File("test2.xls"));
        WritableSheet sheet = to.createSheet("签到", 0);

        Label label = new Label(0, 0, "签到表");
        sheet.addCell(label);
        for (int j = 8; j < f_sheet.getRows(); j++) {
            label = new Label(0, j - 7, f_sheet.getCell(1, j).getContents());
            sheet.addCell(label);
            label = new Label(1, j - 7, f_sheet.getCell(24, j).getContents());
            sheet.addCell(label);
            label = new Label(2, j - 7, f_sheet.getCell(25, j).getContents());
            sheet.addCell(label);
        }
        to.write();
        to.close();
    }
}

 

2.JSoup 北林网络管理小工具

http访问相关的支持,有get和post功能,可以实现模拟登录。

翻到了LZW的有关博客,真心极客耶,第一次接触这方面的登录问题,很长知识。

我这个Java小小程序完全可以替代学校那个臃肿的软件了,会帮你联网,并返回你的流量信息。


JSoup解析一个HTML文档为document

String:Document doc = Jsoup.parse(html);

URL:Document doc = Jsoup.connect("http://example.com/").get();

File:File input = new File("/tmp/input.html"); Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

将HTML解析成一个Document之后,就可以使用JS的DOM的方法进行操作

相关方法见JS。

 

UI部分代码

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class UI {
    public static void main(String[] args) {
        new MyWin("北林校园网登录器");
    }
}

class MyWin extends JFrame {
    private JTextField txtID = new JTextField(20);
    private JTextField txtKEY = new JTextField(20);

    private JLabel lblID = new JLabel("学号", JLabel.LEFT);
    private JLabel lblKEY = new JLabel("密码", JLabel.LEFT);

    private JButton btnTrans = new JButton("连接网络");

    MyWin(String title) {
        super(title);
        Container cp = getContentPane();

        JPanel lblPanel = new JPanel(new GridLayout(2, 1));
        lblPanel.add(lblID);
        lblPanel.add(lblKEY);

        JPanel txtPanel = new JPanel(new GridLayout(2, 1));
        txtPanel.add(txtID);
        txtPanel.add(txtKEY);

        txtID.requestFocus();

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(lblPanel, BorderLayout.WEST);
        panel.add(txtPanel, BorderLayout.CENTER);

        cp.add(panel, BorderLayout.CENTER);

        JPanel btnPane = new JPanel();
        btnPane.add(btnTrans);

        cp.add(btnPane, BorderLayout.SOUTH);

        btnTrans.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new WEB_LOGIN(txtID.getText().trim(), txtKEY.getText().trim());
            }
        });

        setSize(300, 300);
        setLocation(450, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }
}
View Code

 

网络相关部分

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class WEB_LOGIN {

    WEB_LOGIN(String ID, String KEY) {
        // System.out.println(ID + " " + KEY);
        parseUrl(ID, KEY);
    }

    static String translate(HttpResponse response) {
        StringBuilder sb = new StringBuilder("");
        try {
            HttpEntity translate = response.getEntity();
            if (translate != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        translate.getContent()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    static String doGet(HttpClient httpClient, String url, String... pairs) {
        String entityContent = null;
        try {
            url = makeGetSrl(url, pairs);
            HttpGet get = new HttpGet(url);
            get.addHeader("Accept", "text/html, application/xhtml+xml, */*");
            get.addHeader("Accept-Language", "zh-CN,en-US;q=0.5");
            get.addHeader("User-Agent",
                    "Mozilla/27.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            get.addHeader("Accept-Encoding", "gzip, deflate, sdch");
            get.addHeader("Connection", "Keep-alive");
            HttpResponse response = httpClient.execute(get);
            entityContent = translate(response);
            // print("%d", response.getStatusLine().getStatusCode());
            EntityUtils.consume(response.getEntity());
            // getCookies(httpClient);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return entityContent;
    }

    static String makeGetSrl(String url, String... pairs) {
        if (!url.endsWith("?")) {
            url += "?";
        }
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        int len = pairs.length;
        for (int i = 0; i < len / 2; i++) {
            params.add(new BasicNameValuePair(pairs[2 * i], pairs[2 * i + 1]));
        }
        String paramsStr = URLEncodedUtils.format(params, "utf-8");
        url += paramsStr;
        return url;
    }

    static String doPost(HttpClient httpClient, String url, String... pairs) {
        String entityContent = null;
        try {
            HttpPost post = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < pairs.length / 2; i++) {
                params.add(new BasicNameValuePair(pairs[2 * i],
                        pairs[2 * i + 1]));
            }
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            // System.out.println(response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 302)
                System.out.println("OK");
            else if (response.getStatusLine().getStatusCode() == 200)
                System.out.println("NO");
            else if (response.getStatusLine().getStatusCode() == 404)
                System.out.println("UnConnected");
            post.abort();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return entityContent;
    }

    public static void parseUrl(String ID, String KEY) {
        try {
            Document doc = Jsoup.connect("http://login.bjfu.edu.cn/index.jsp")
                    .get();
            Elements hrefs = doc.select("span.login_txt");
            Element href = hrefs.first();
            System.out.println("IP" + "   " + href.text().toString());
            // Scanner in = new Scanner(System.in);
            // String ID = in.nextLine();
            // String KEY = in.nextLine();
            HttpClient httpClient = new DefaultHttpClient();
            doPost(httpClient, "http://login.bjfu.edu.cn/checkLogin.jsp",
                    "username", ID, "password", KEY, "ip", href.text()
                            .toString(), "action", "连接网络");

            String content = doGet(httpClient,
                    "http://login.bjfu.edu.cn/user/index.jsp", "ip", href
                            .text().toString(), "action", "connect");
            // System.out.println(content);
            doc = Jsoup.parse(content);
            Element elem = doc.select("frame[src]").select("[name=main]")
                    .first();
            Pattern pattern = Pattern.compile("userid=(\\d+)");
            Matcher matcher = pattern.matcher(elem.toString());
            String userId = null;
            if (matcher.find()) { // while
                userId = matcher.group(1);
            }
            System.out.println("userId : " + userId);
            content = doGet(httpClient,
                    "http://login.bjfu.edu.cn/user/network/connect_action.jsp",
                    "userid", userId, "ip", href.text().toString(), "type", "2");
            // System.out.println(content);

            String content2 = doGet(httpClient,
                    "http://login.bjfu.edu.cn/user/admin_top.jsp");
            doc = Jsoup.parse(content2);
            elem = doc.body().select("td[width]").select("[align=right]")
                    .first();
            pattern = Pattern.compile(">...<");
            Matcher matcher1 = pattern.matcher(elem.toString());
            String Name = null;
            if (matcher1.find()) {
                Name = matcher1.group(0);
            }
            parseFile(content, Name.substring(1, Name.length() - 1));
            // System.out.println(Name.substring(1, Name.length() - 1) +
            // " 同学你好");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void getCookies(HttpClient client) {
        StringBuilder sb = new StringBuilder();
        List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore()
                .getCookies();
        for (Cookie cookie : cookies)
            sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
        System.out.println(sb.toString());
    }

    public static void parseFile(String html, String name) {
        // String map[] = { "", "本月套餐", "下月套餐", "账户余额", "产生费用", "流量上限", "已用流量",
        // "剩余流量", "超出流量" };
        Document doc = Jsoup.parse(html);
        String codes = doc.select("td[class]").select("td[align]").text();
        String ans = codes.replaceAll("[^0-9.]+", "\n");
        // System.out.println(ans);
        new MyWin2(name, ans);
    }
}

class MyWin2 extends JFrame {
    private JLabel Name = new JLabel("", JLabel.LEFT);

    private JLabel lblID = new JLabel("本月套餐", JLabel.LEFT);
    private JLabel lblID2 = new JLabel("下月套餐", JLabel.LEFT);
    private JLabel lblID3 = new JLabel("账户余额", JLabel.LEFT);
    private JLabel lblID4 = new JLabel("产生费用", JLabel.LEFT);
    private JLabel lblID5 = new JLabel("流量上限", JLabel.LEFT);
    private JLabel lblID6 = new JLabel("已用流量", JLabel.LEFT);
    private JLabel lblID7 = new JLabel("剩余流量", JLabel.LEFT);
    private JLabel lblID8 = new JLabel("超出流量", JLabel.LEFT);

    private JLabel txtID = new JLabel("", JLabel.LEFT);
    private JLabel txtID2 = new JLabel("", JLabel.LEFT);
    private JLabel txtID3 = new JLabel("", JLabel.LEFT);
    private JLabel txtID4 = new JLabel("", JLabel.LEFT);
    private JLabel txtID5 = new JLabel("", JLabel.LEFT);
    private JLabel txtID6 = new JLabel("", JLabel.LEFT);
    private JLabel txtID7 = new JLabel("", JLabel.LEFT);
    private JLabel txtID8 = new JLabel("", JLabel.LEFT);

    MyWin2(String name, String content) {
        super(name);
        Container cp = getContentPane();
        Name.setText(name + "同学您好!");
        JPanel lblPanel = new JPanel(new GridLayout(9, 1));
        lblPanel.add(Name);
        lblPanel.add(lblID);
        lblPanel.add(lblID2);
        lblPanel.add(lblID3);
        lblPanel.add(lblID4);
        lblPanel.add(lblID5);
        lblPanel.add(lblID6);
        lblPanel.add(lblID7);
        lblPanel.add(lblID8);

        JPanel txtPanel = new JPanel(new GridLayout(8, 1));
        String[] strArray = content.split("\n");
        txtID.setText(strArray[0]);
        txtPanel.add(txtID2);
        txtID2.setText(strArray[1]);
        txtPanel.add(txtID2);
        txtID3.setText(strArray[2]);
        txtPanel.add(txtID3);
        txtID4.setText(strArray[3]);
        txtPanel.add(txtID4);
        txtID5.setText(strArray[4]);
        txtPanel.add(txtID5);
        txtID6.setText(strArray[5]);
        txtPanel.add(txtID6);
        txtID7.setText(strArray[6]);
        txtPanel.add(txtID7);
        txtID8.setText(strArray[7]);
        txtPanel.add(txtID8);
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(Name, BorderLayout.NORTH);
        panel.add(lblPanel, BorderLayout.WEST);
        panel.add(txtPanel, BorderLayout.CENTER);

        cp.add(panel, BorderLayout.CENTER);

        setSize(200, 300);
        setLocation(450, 200);
        setVisible(true);
    }
}
View Code

 

3.北林图书馆借阅信息查询系统

在Post http://222.28.112.228:8080/reader/redr_verify.php 提交个人登录信息,

包含学号,密码,和验证码信息。

验证码信息是通过 http://222.28.112.228:8080/reader/captcha.php 传递一个code,可以任意指定,默认是的传递学号,而我们传递88就会返回一个.gif

这个图片中红色数字就是验证信息。

保存图片需要用到File和OutputStream,将HttpGet的HttpResponse全部信息写入文件,就得到了这个gif图片。

用一个ImageIcon的JLabel显示这个验证码。

然后我们就可以通过 http://222.28.112.228:8080/reader/redr_info.php 得到想要的个人信息。

通过 http://222.28.112.228:8080/reader/book_lst.php 得到借阅书单信息。

匹配汉字的正则表达式是 [\u4e00-\u9fa5]+: 

 

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Test {

    public static void main(String[] args) throws IOException {
        parseUrl();
    }

    static String makeGetSrl(String url, String... pairs) {
        if (!url.endsWith("?")) {
            url += "?";
        }
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        int len = pairs.length;
        for (int i = 0; i < len / 2; i++) {
            params.add(new BasicNameValuePair(pairs[2 * i], pairs[2 * i + 1]));
        }
        String paramsStr = URLEncodedUtils.format(params, "utf-8");
        url += paramsStr;
        return url;
    }

    public static void parseUrl() throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(makeGetSrl(
                "http://222.28.112.228:8080/reader/captcha.php", "code", "88"));
        HttpResponse response = httpClient.execute(get);
        File storeFile = new File("/tmp.gif");
        OutputStream output = new FileOutputStream(storeFile);
        response.getEntity().writeTo(output);
        output.close();
        new ShowBmp(httpClient, "/tmp.gif").setVisible(true);
    }
}

class ShowBmp extends JFrame {
    private JTextField txtID = new JTextField(20);
    private JTextField txtKEY = new JTextField(20);
    private JTextField txtCERT = new JTextField(20);

    private JLabel lblMES = new JLabel("请输入登录信息", JLabel.CENTER);
    private JLabel lblID = new JLabel("学号", JLabel.LEFT);
    private JLabel lblKEY = new JLabel("密码", JLabel.LEFT);
    private JLabel lblCERT = new JLabel("验证码", JLabel.LEFT);

    private JButton btnTrans = new JButton("登录");

    static int doPost(HttpClient httpClient, String url, String... pairs) {
        int result = -1;
        try {
            HttpPost post = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < pairs.length / 2; i++) {
                params.add(new BasicNameValuePair(pairs[2 * i],
                        pairs[2 * i + 1]));
            }
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == 302)
                result = 1;
            else if (response.getStatusLine().getStatusCode() == 200)
                result = 0;
            else if (response.getStatusLine().getStatusCode() == 404)
                result = -1;
            post.abort();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    static String translate(HttpResponse response) {
        StringBuilder sb = new StringBuilder("");
        try {
            HttpEntity translate = response.getEntity();
            if (translate != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        translate.getContent()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    static String doGet(HttpClient httpClient, String url, String... pairs) {
        String result = null;
        try {
            url = makeGetSrl(url, pairs);
            HttpGet get = new HttpGet(url);
            get.addHeader("Accept", "text/html, application/xhtml+xml, */*");
            get.addHeader("Accept-Language", "zh-CN,en-US;q=0.5");
            get.addHeader("User-Agent",
                    "Mozilla/27.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            get.addHeader("Accept-Encoding", "gzip, deflate, sdch");
            get.addHeader("Connection", "Keep-alive");
            HttpResponse response = httpClient.execute(get);

            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    static String makeGetSrl(String url, String... pairs) {
        if (!url.endsWith("?")) {
            url += "?";
        }
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        int len = pairs.length;
        for (int i = 0; i < len / 2; i++) {
            params.add(new BasicNameValuePair(pairs[2 * i], pairs[2 * i + 1]));
        }
        String paramsStr = URLEncodedUtils.format(params, "utf-8");
        url += paramsStr;
        return url;
    }

    ShowBmp(final HttpClient httpClient, String bmpFile) {
        super("北林图书馆登录系统");
        setLocation(200, 200);
        Image image = null;
        try {
            image = ImageIO.read(new File(bmpFile));
        } catch (IOException ex) {
        }

        JLabel label = new JLabel(new ImageIcon(image));

        Container cp = getContentPane();

        JPanel lblPanel = new JPanel(new GridLayout(3, 1));
        lblPanel.add(lblID);
        lblPanel.add(lblKEY);
        lblPanel.add(lblCERT);

        JPanel txtPanel = new JPanel(new GridLayout(4, 1));
        txtPanel.add(txtID);
        txtPanel.add(txtKEY);
        txtPanel.add(txtCERT);
        txtPanel.add(label);

        txtID.requestFocus();

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(lblMES, BorderLayout.NORTH);
        panel.add(lblPanel, BorderLayout.WEST);
        panel.add(txtPanel, BorderLayout.CENTER);

        cp.add(panel, BorderLayout.CENTER);

        JPanel btnPane = new JPanel();
        btnPane.add(btnTrans);

        cp.add(btnPane, BorderLayout.SOUTH);

        btnTrans.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int state = doPost(httpClient,
                        "http://222.28.112.228:8080/reader/redr_verify.php",
                        "number", txtID.getText(), "passwd", txtKEY.getText(),
                        "captcha", txtCERT.getText(), "select", "cert_no",
                        "returnUrl", "");
                if (state == 1) {
                    String content = doGet(httpClient,
                            "http://222.28.112.228:8080/reader/redr_info.php");
                    Document doc = Jsoup.parse(content);
                    String elem = doc.select("div[id=mylib_content]")
                            .select("table[width=100%]").first().text();
                    elem = elem.replaceAll("[\u4e00-\u9fa5]+:", " ");
                    System.out.println(elem);

                    content = doGet(httpClient,
                            "http://222.28.112.228:8080/reader/book_lst.php");
                    doc = Jsoup.parse(content);
                    elem = doc.select("div[class=mylib_con_con pan_top]")
                            .select("strong[class=iconerr]").first().text();
                    System.out.println(elem);
                } else {
                    txtID.setText(null);
                    txtKEY.setText(null);
                    txtCERT.setText(null);
                    lblMES.setText("登录信息有误,请核实");
                }
            }
        });
        setSize(300, 300);
        setLocation(450, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
View Code

 

4.处理图像,为图像添加水印效果

JAVA的Image为我们提供了图像笔刷的功能,借用这个功能实现图像水印的效果。

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {
    public final static void pressImage(String pressImg, String targetImg,
            int x, int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src_biao, (wideth - wideth_biao),
                    (height - height_biao), wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void pressText(String pressText, String targetImg,
            String fontName, int fontStyle, Color color, int fontSize, int x,
            int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                    / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 缩放 filePath图片路径 bb比例不对时是否需要补白
     */
    public static void resize(String filePath, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; // 缩放比例
            File f = new File(filePath);
            BufferedImage bi = ImageIO.read(f);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            // 计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue()
                            / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(
                        AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {
                BufferedImage image = new BufferedImage(width, height,
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                g.dispose();
                itemp = image;
            }
            ImageIO.write((BufferedImage) itemp, "jpg", f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        pressText("我是文字水印", "IMG.jpg", "黑体", 36, Color.white, 80, 0, 0, 0.7f);
    }

    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }
}
View Code

 

5.简单检测U盘工具,关机提示未拔U盘

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    private static Map<String, Boolean> map = new LinkedHashMap<String, Boolean>();
    private static String[] arr = new String[] { "C", "D", "E", "F", "G", "H",
            "I", "J" };
    public static int check() {
        File file;
        while (true) {
            for (String str : arr) {
                file = new File(str + ":\\");
                if (file.exists() && !map.get(str)) {
                    map.put(str, file.exists());
                    return 1;
                }
                if (map.get(str) && !file.exists()) {
                    map.remove(str);
                    return 2;
                }
                if (file.exists() != map.get(str)) {
                    map.put(str, file.exists());
                }
            }
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void init() {
        File file;
        map.clear();
        for (String str : arr) {
            file = new File(str + ":\\");
            map.put(str, file.exists());
        }
        System.out.println(map);
    }
    public static void main(String[] args) {
        init();
        int r;
        r = check();
        if (r == 1)
            System.out.println("检测到U盘");
        else if (r == 2)
            System.out.println("拔出U盘");
    }
}
View Code

 

6.mail.jar 发邮件客户端

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

class MailThread implements Runnable {
    Message message;
    String toAddress;

    public MailThread(Message msg, String to) {
        message = msg;
        toAddress = to;
    }

    public void run() {
        try {
            // 创建一封邮件,并设置信息
            message.setRecipient(RecipientType.TO, new InternetAddress(
                    toAddress));
            // 直接发送,message通过已经授权的Session生成
            Transport.send(message);
            System.out.println("--> Sended !");
        } catch (Exception e) {
            System.out.println("--> Error !");
        }
    }
}

public class Mail {
    public static void main(String[] args) throws Exception {
        final String user = "ad@kuangshi.info";
        final String password = "********";

        String fromAddress = "ad@kuangshi.info";
        String toAddress;
        String subject = "邮件测试主题";
        String content = "测试邮件<script>alert('ok')</script>";

        // 配置参数
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.exmail.qq.com");
        // 生成Session时以获取授权连接
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        session.setDebug(true);

        // 创建一封邮件,并设置信息
        String nick = javax.mail.internet.MimeUtility.encodeText("推广");
        Message message = new MimeMessage(session);
        message.setSubject(subject);
        message.setFrom(new InternetAddress(nick + "<" + fromAddress + ">"));
        message.setSentDate(new Date());
        message.setContent(content, "text/html;charset=utf-8");

        File fp = new File("list.txt");
        BufferedReader br = new BufferedReader(new FileReader(fp));
        String temp = null;
        Pattern regex = Pattern
                .compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
        while ((temp = br.readLine()) != null) {
            if (regex.matcher(temp).matches())
                toAddress = temp;
            else
                continue;
            MailThread mt = new MailThread(message, toAddress);
            new Thread(mt).start();
        }
    }
}

 

转载于:https://www.cnblogs.com/updateofsimon/p/3523244.html

相关文章:

  • 运行WampServer时,提示Exception Exception in module wampmanager.exe at 000F15A0.解决办法
  • Android增量升级的方法和原理
  • oracle引起一些问题
  • Ubuntu 13.10 下安装python 3.3 IDLE
  • 搭建samba文件共享服务器
  • 实时用户操作审计系统
  • 文件系统与RAID总结
  • HBase工具之监控Region的可用和读写延时状况
  • AppStore占坑注意事项
  • 删除.gitignore中的在version control中的文件
  • ios之coredata(一)
  • Understanding CSS Filter Effects
  • 图像处理-缩放-平移旋转等等
  • 2012蓝桥杯【初赛试题】干支纪年
  • C语言初学者代码中的常见错误与瑕疵(14)
  • ES6核心特性
  • ES学习笔记(10)--ES6中的函数和数组补漏
  • Hibernate最全面试题
  • iOS动画编程-View动画[ 1 ] 基础View动画
  • jdbc就是这么简单
  • text-decoration与color属性
  • Twitter赢在开放,三年创造奇迹
  • yii2中session跨域名的问题
  • 阿里研究院入选中国企业智库系统影响力榜
  • 从零开始在ubuntu上搭建node开发环境
  • 基于 Babel 的 npm 包最小化设置
  • 聊聊directory traversal attack
  • 爬虫进阶 -- 神级程序员:让你的爬虫就像人类的用户行为!
  • 小程序、APP Store 需要的 SSL 证书是个什么东西?
  • 格斗健身潮牌24KiCK获近千万Pre-A轮融资,用户留存高达9个月 ...
  • #includecmath
  • #预处理和函数的对比以及条件编译
  • (1)(1.13) SiK无线电高级配置(五)
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • **python多态
  • ... 是什么 ?... 有什么用处?
  • .net core webapi 部署iis_一键部署VS插件:让.NET开发者更幸福
  • .NET/C# 判断某个类是否是泛型类型或泛型接口的子类型
  • .NET6 命令行启动及发布单个Exe文件
  • .NET处理HTTP请求
  • .NET企业级应用架构设计系列之技术选型
  • .sys文件乱码_python vscode输出乱码
  • ??eclipse的安装配置问题!??
  • @Service注解让spring找到你的Service bean
  • [android] 看博客学习hashCode()和equals()
  • [Android] 修改设备访问权限
  • [AUTOSAR][诊断管理][ECU][$37] 请求退出传输。终止数据传输的(上传/下载)
  • [AutoSar]BSW_Com02 PDU详解
  • [AutoSAR系列] 1.3 AutoSar 架构
  • [Avalon] Avalon中的Conditional Formatting.
  • [c#基础]值类型和引用类型的Equals,==的区别
  • [C++][数据结构][算法]单链式结构的深拷贝