您的位置:首页 > 编程语言 > Java开发

JAVA文件操作大全(5)

2016-07-15 11:30 232 查看
拖一个CheckBox

1、软件启动时给CheckBox重置状态:

//http://sourceforge.net/projects/jregistrykey/

//import ca.beq.util.win32.registry.*;

//import java.util.*;

RegistryKey R_local = Registry.LocalMachine;

RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

if (R_run.GetValue("BirthdayTipF") == null)

{

checkBox1.Checked = false;

}

else

{

checkBox1.Checked = true;

}

R_run.Close();

R_local.Close();

2、CheckChanged事件:

private void checkBox1_CheckedChanged(object sender, EventArgs e)

{

string R_startPath = Application.ExecutablePath;

if (checkBox1.Checked == true)

{

RegistryKey R_local = Registry.LocalMachine;

RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

R_run.SetValue("BirthdayTipF", R_startPath);

R_run.Close();

R_local.Close();

}

else

{

try

{

RegistryKey R_local = Registry.LocalMachine;

RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

R_run.Deletue("BirthdayTipF", false);

R_run.Close();

R_local.Close();

}

catch (Exception ex)

{

MessageBox.Show("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

throw;

}

}

}

88.菜单勾选/取消自动登录系统

89.模拟键盘输入字符串

/*

import java.awt.*;

import java.awt.event.*;

throws Exception{

*/

static Robot robot;

static{

try {

robot = new Robot();

} catch (AWTException e) {}

}

static void sendKey(String ks){

KeyStore k = KeyStore.findKeyStore(ks);

if(k!=null){

if(k.upCase)

upCase(k.v);

else

sendKey(k.v);

}

else{

for(int i=0; i<ks.length(); i++){

char c = ks.charAt(i);

if(c>='0'&&c<='9'){

sendKey(c);

}

else if(c>='a'&&c<='z'){

sendKey(c-32);

}

else if(c>='A'&&c<='Z'){

upCase(c);

}

}

}

}

private static void upCase(int kc){

robot.keyPress(KeyEvent.VK_SHIFT);

robot.keyPress(kc);

robot.keyRelease(kc);

robot.keyRelease(KeyEvent.VK_SHIFT);

}

private static void sendKey(int kc){

robot.keyPress(kc);

robot.keyRelease(kc);

}

static class KeyStore{

//special keys

final static KeyStore[] sp = {

new KeyStore("{Tab}",KeyEvent.VK_TAB),//tab

new KeyStore("{Enter}",KeyEvent.VK_ENTER),//enter

new KeyStore("{PUp}",KeyEvent.VK_PAGE_UP),//page up

new KeyStore("{<}",KeyEvent.VK_LESS),//<

new KeyStore("{Up}",KeyEvent.VK_UP),//up key

new KeyStore("{At}",KeyEvent.VK_AT,true),//@

new KeyStore("{Dollar}",KeyEvent.VK_DOLLAR,true),//$

};

String k;

int v;

boolean upCase;

KeyStore(String k,int v){

this(k,v,false);

}

KeyStore(String s,int i,boolean up){

k=s;

v=i;

upCase=up;

}

static KeyStore findKeyStore(String k){

for(int i=0; i<sp.length; i++){

if(sp[i].k.equals(k))

return sp[i];

}

return null;

}

}

Thread.sleep(1000);

sendKey("{Tab}");//tab

sendKey("{<}");//<

sendKey("abcd123AHahahAA");//abcd123AHahahAA

sendKey("{At}");//@

sendKey("{Dollar}");//$

sendKey("{Up}");//up arrow

90.提取PDF文件中的文本

//http://incubator.apache.org/pdfbox/

/*

import java.io.*;

import org.pdfbox.pdfparser.*;

import org.pdfbox.pdmodel.*;

import org.pdfbox.util.*;

*/

public class SimplePDFReader {

/**

* simply reader all the text from a pdf file.

* You have to deal with the format of the output text by yourself.

* 2008-2-25

* @param pdfFilePath file path

* @return all text in the pdf file

*/

public static String getTextFromPDF(String pdfFilePath) {

String result = null;

FileInputStream is = null;

PDDocument document = null;

try {

is = new FileInputStream(pdfFilePath);

PDFParser parser = new PDFParser(is);

parser.parse();

document = parser.getPDDocument();

PDFTextStripper stripper = new PDFTextStripper();

result = stripper.getText(document);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (document != null) {

try {

document.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

return result;

}

}

得到PDF的文本内容之后,自己根据文件的格式,取得想要的文本(这里我找的就是文章的标题,在文本中恰巧都是文件的第一行的内容),然后通过java的File相关api,对文件进行更名操作。

import java.io.File;

import java.io.FilenameFilter;

public class PaperNameMender {

public static void changePaperName(String filePath) {

//使用SimplePDFReader得到pdf文本

String ts = SimplePDFReader.getTextFromPDF(filePath);

//取得一行内容

String result = ts.substring(0, ts.indexOf('\n'));

//得到源文件名中的最后一个逗点.的位置

int index = filePath.indexOf('.');

int nextIndex = filePath.indexOf('.', index + 1);

while(nextIndex != -1) {

index = nextIndex;

nextIndex = filePath.indexOf('.', index + 1);

}

//合成新文件名

String newFilename = filePath.substring(0, index) + " " +

result.trim() + ".pdf";

File originalFile = new File(filePath);

//修改文件名

originalFile.renameTo(new File(newFilename));

}

}

91.操作内存映射文件

/*

import java.io.*;

import java.nio.*;

import java.nio.channels.*;

*/

private static int length = 0x8FFFFFF; // 128 Mb

MappedByteBuffer out =

new RandomAccessFile("test.dat", "rw").getChannel()

.map(FileChannel.MapMode.READ_WRITE, 0, length);

for(int i = 0; i < length; i++)

out.put((byte)'x');

System.out.println("Finished writing");

for(int i = length/2; i < length/2 + 6; i++)

System.out.print((char)out.get(i));

92.重定向windows控制台程序的输出信息

92.1 取得Runtime.getRuntime().exec("cmd /c dir")的输入输出

//import java.io.*;

try {

String command = "cmd /c dir";

Process proc = Runtime.getRuntime().exec(command);

InputStreamReader ir = new InputStreamReader(proc.getInputStream());

LineNumberReader lnr = new LineNumberReader(ir);

String line;

while( (line = lnr.readLine()) != null)

{

System.out.println(line);

}

} catch (IOException e) {

e.printStackTrace();

}

92.2 利用ProcessBuilder来创建Process对象,执行外部可执行程序

// //Eg1:

// String address = null;

//

// String os = System.getProperty("os.name");

// System.out.println(os);

//

// if (os != null) {

// if (os.startsWith("Windows")) {

// try {

// ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");

// Process p = pb.start();

//

// BufferedReader br = new BufferedReader(

// new InputStreamReader(p.getInputStream()));

//

// String line;

// while ((line = br.readLine()) != null) {

// if (line.indexOf("Physical Address") != -1) {

// int index = line.indexOf(":");

// address = line.substring(index + 1);

// break;

// }

// }

// br.close();

// address = address.trim();

// } catch (IOException e) {

// // TODO Auto-generated catch block

// e.printStackTrace();

// }

// } else if (os.startsWith("Linux")) {

// try {

// ProcessBuilder pb = new ProcessBuilder(

//

// "ifconfig", "/all");

//

// Process p = pb.start();

// BufferedReader br = new BufferedReader(

// new InputStreamReader(p.getInputStream()));

// String line;

// while ((line = br.readLine()) != null) {

// int index = line.indexOf("硬件地址");

// if (index != -1) {

// address = line.substring(index + 4);

// break;

// }

// }

// br.close();

// address = address.trim();

// } catch (IOException e) {

// e.printStackTrace();

// }

// }

// }

// //Eg2:

// try {

// Process proc;

// proc = Runtime.getRuntime().exec("cmd.exe");

// BufferedReader read = new BufferedReader(new InputStreamReader(proc

// .getInputStream()));

// new Thread(new Echo(read)).start();

//

// PrintWriter out = new PrintWriter(new OutputStreamWriter(proc

// .getOutputStream()));

// BufferedReader in = new BufferedReader(new InputStreamReader(

// System.in));

// String instr = in.readLine();

// while (!"exit".equals(instr)) {

// instr = in.readLine();

// out.println(instr);

// out.flush();

// }

//

// in.readLine();

// read.close();

// out.close();

// } catch (IOException e) {

// // TODO Auto-generated catch block

// e.printStackTrace();

// }

}

}

class Echo implements Runnable {

private BufferedReader read;

public Echo(BufferedReader read) {

this.read = read;

}

public void run() {

try {

String line = read.readLine();

while (line != null) {

System.out.println(line);

line = read.readLine();

}

System.out.println("---执行完毕:");

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

93.接受邮件

//import javax.mail.*;

public class UserAuthentication extends Authenticator {

private String userName;

private String password;

public void setPassword(String password){

this.password = password;

}

public void setUserName(String userName){

this.userName = userName;

}

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

}

//ReceiveMailTest.java

import javax.mail.*;

import java.io.*;

import java.util.*;

import javax.mail.*;

public class ReceiveMailTest {

private Folder inbox;

private Store store;

//连接邮件服务器,获得所有邮件的列表

public Message[] getMail(String host, String name, String password) throws

Exception {

Properties prop = new Properties();

prop.put("mail.pop3.host", host);

Session session = Session.getDefaultInstance(prop);

store = session.getStore("pop3");

store.connect(host, name, password);

inbox = store.getDefaultFolder().getFolder("INBOX");

inbox.open(Folder.READ_ONLY);

Message[] msg = inbox.getMessages();

FetchProfile profile = new FetchProfile();

profile.add(FetchProfile.Item.ENVELOPE);

profile.add(FetchProfile.Item.FLAGS);

profile.add("X-Mailer");

inbox.fetch(msg, profile);

return msg;

}

//处理任何一种邮件都需要的方法

private void handle(Message msg) throws Exception {

System.out.println("邮件主题:" + msg.getSubject());

System.out.println("邮件作者:" + msg.getFrom()[0].toString());

System.out.println("发送日期:" + msg.getSentDate());

}

//处理文本邮件

public void handleText(Message msg) throws Exception {

this.handle(msg);

System.out.println("邮件内容:" + msg.getContent());

}

//处理Multipart邮件,包括了保存附件的功能

public void handleMultipart(Message msg) throws Exception {

String disposition;

BodyPart part;

// 1、从Message中取到Multipart

// 2、遍历Multipart里面得所有bodypart

// 3、判断BodyPart是否是附件,

// 如果是,就保存附件

// 否则就取里面得文本内容

Multipart mp = (Multipart) msg.getContent();

int mpCount = mp.getCount(); //Miltipart的数量,用于除了多个part,比如多个附件

for (int m = 0; m < mpCount; m++) {

this.handle(msg);

part = mp.getBodyPart(m);

disposition = part.getDisposition();

if (disposition != null && disposition.equals(Part.ATTACHMENT)) { //判断是否有附件

this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释

} else {

System.out.println(part.getContent());

}

}

}

private void saveAttach(BodyPart part) throws Exception {

String temp = part.getFileName(); //得到未经处理的附件名字

System.out.println("*********temp=" + temp);

System.out.println("**********" + base64Decoder(temp));

String s = temp;//temp.substring(11, temp.indexOf("?=") - 1); //去到header和footer

//文件名一般都经过了base64编码,下面是解码

String fileName = s;//this.base64Decoder(s);

System.out.println("有附件:" + fileName);

InputStream in = part.getInputStream();

FileOutputStream writer = new FileOutputStream(new File("d:/temp/"+fileName));

byte[] content = new byte[255];

int read = 0;

while ((read = in.read(content)) != -1) {

writer.write(content);

}

writer.close();

in.close();

}

//base64解码

private String base64Decoder(String s) throws Exception {

sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

byte[] b = decoder.decodeBuffer(s);

//sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

//String str = encoder.encode(bytes);

return (new String(b));

}

//关闭连接

public void close() throws Exception {

if (inbox != null) {

inbox.close(false);

}

if (store != null) {

store.close();

}

}

public static void main(String args[]) {

String host = "192.168.1.245";

String name = "user2";

String password = "yyaccp";

ReceiveMailTest receiver = new ReceiveMailTest();

try {

Message[] msg = receiver.getMail(host, name, password);

for (int i = 0; i < msg.length; i++) {

if (msg[i].isMimeType("text/*")) { //判断邮件类型

receiver.handleText(msg[i]);

} else {

receiver.handleMultipart(msg[i]);

}

System.out.println("****************************");

}

receiver.close();

} catch (Exception e) {

e.printStackTrace();

System.out.println(e);

}

}

}

94.发送邮件

//import javax.mail.*;

public class UserAuthentication extends Authenticator {

private String userName;

private String password;

public void setPassword(String password){

this.password = password;

}

public void setUserName(String userName){

this.userName = userName;

}

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

}

//SendMailTest.java

import java.io.*;

import javax.mail.internet.*;

import javax.mail.*;

import java.io.*;

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

import java.util.*;

import javax.activation.*;

import javax.mail.*;

public class SendMailTest {

public SendMailTest() {

}

public static void main(String[] args) throws Exception {

String smtpServer = "192.168.1.245";

String userName = "user2";

String password = "yyaccp";

String fromAddress = "user1@mailserver";

String toAddress = "user2@mailserver";

String subject = "邮件标题";

String content = "邮件内容";

String attachFile1 = "d:/temp/test.txt";

String attachFile2 = "d:/temp/test2.txt";

SendMailTest sendMail = new SendMailTest();

Session session = sendMail.getSession(smtpServer, userName, password);

if(session != null){

String[] files = {attachFile1, attachFile2};

//Message msg = sendMail.getMessage(session, subject, content, files);

Message msg = sendMail.getMessage(session, subject, content);

if(msg != null){

//发送源地址

msg.setFrom(new InternetAddress(fromAddress));

//发送目的地址

InternetAddress[] tos = InternetAddress.parse(toAddress);

msg.setRecipients(Message.RecipientType.TO, tos);

//抄送目的地址

// InternetAddress[] toscc = InternetAddress.parse(ccAddr);

// msg.setRecipients(Message.RecipientType.CC, toscc);

//

//密送目的地址

// InternetAddress[] tosbcc = InternetAddress.parse(bccAddr);

// msg.setRecipients(Message.RecipientType.BCC, tosbcc);

//发送邮件

boolean bool = sendMail.sendMail(msg);

if(bool){

System.out.println("发送成功");

}else{

System.out.println("发送失败");

}

}

}

}

public Session getSession(String smtpServer, String userName, String password){

// 192.168.1.245

// user2

// yyaccp

Session session = null;

try{

Properties props = new Properties();

props.put("mail.smtp.host", smtpServer); //例如:202.108.44.206 smtp.163.com

props.put("mail.smtp.auth", "true"); //认证是否设置

UserAuthentication authen = new UserAuthentication();

authen.setPassword(password);

authen.setUserName(userName);

session = Session.getDefaultInstance(props, authen);

}catch(Exception e){

e.printStackTrace();

}

return session;

}

public Message getMessage(Session session, String subject, String text){

Message msg = null;

try{

msg = new MimeMessage(session);

msg.setText(text);

msg.setSubject(subject);

}catch(Exception e){

e.printStackTrace();

}

return msg;

}

public boolean sendMail(Message msg){

boolean bool = false;

try {

Transport.send(msg);

bool = true;

} catch (MessagingException ex) {

ex.printStackTrace();

}

return bool;

}

public Message getMessage(Session session, String subject, String text, String[] archives){

// d:/temp/saa.txt

Message msg = null;

try{

Multipart contentPart = new MimeMultipart();

// 生成Message对象

msg = new MimeMessage(session);

// 设置邮件内容

msg.setContent(contentPart);

// 设置邮件标题

msg.setSubject(subject);

// 组织邮件内容,包括邮件的文本内容和附件

// 1 邮件文本内容

MimeBodyPart textPart = new MimeBodyPart();

textPart.setText(text);

// 将文本部分,添加到邮件内容

contentPart.addBodyPart(textPart);

// 2 附件

if(archives != null){

for(int i=0; i<archives.length; i++){

MimeBodyPart archivePart = new MimeBodyPart();

//选择出每一个附件文件名

String filename = archives[i];

//得到数据源

FileDataSource fds = new FileDataSource(filename);

//得到附件本身并至入BodyPart

archivePart.setDataHandler(new DataHandler(fds));

//得到文件名同样至入BodyPart

archivePart.setFileName(fds.getName());

// 将附件添加到附件集

contentPart.addBodyPart(archivePart);

}

}

}catch(Exception e){

e.printStackTrace();

}

return msg;

}

/**

* 获取文本文件内容

* @param path String

* @throws IOException

* @return String

*/

public String getFile(String path) throws IOException {

//读取文件内容

char[] chrBuffer = new char[10];//缓冲十个字符

int intLength;

String s = "";//文件内容字符串

FileReader fis = new FileReader(path);

while ( (intLength = fis.read(chrBuffer)) != -1) {

String temp = String.valueOf(chrBuffer);//转换字符串

s = s + temp;//累加字符串

}

return s;

}

}

95.报表相关

//http://www.jfree.org/jfreechart/

/*

import java.io.*;

import java.awt.*;

import org.jfree.chart.*;

import org.jfree.chart.title.TextTitle;

import org.jfree.data.general.*;

*/

String title = "梦泽科技员工学历情况统计";

DefaultPieDataset piedata = new DefaultPieDataset();

piedata.setValue("大专", 8.1);

piedata.setValue("大学", 27.6);

piedata.setValue("硕士", 53.2);

piedata.setValue("博士及以上", 19.2);

piedata.setValue("大专以下", 1.9);

JFreeChart chart = ChartFactory.createPieChart(title, piedata, true, true, true);

chart.setTitle(new TextTitle(title, new Font("宋体", Font.BOLD, 25)));

chart.addSubtitle(new TextTitle("最后更新日期:2005年5月19日", new Font("楷书", Font.ITALIC, 18)));

chart.setBackgroundPaint(Color.white);

try {

ChartUtilities.saveChartAsJPEG(new File("PieChart.jpg"), chart, 360, 300);

} catch (IOException exz) {

System.out.print("....Cant′t Create image File");

}

96.全屏幕截取

/*

import java.awt.*;

import java.awt.image.*;

import java.io.*;

import javax.imageio.*;

*/

try{

Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

BufferedImage screenshot = (new Robot())

.createScreenCapture(new Rectangle(0, 0,

(int) d.getWidth(), (int) d.getHeight()));

// 根据文件前缀变量和文件格式变量,自动生成文件名

String name = %%1 + "."

+ %%2; //"png"

File f = new File(name);

ImageIO.write(screenshot, %%2, f);

} catch (Exception ex) {

System.out.println(ex);

}

97.区域截幕

/*

import java.awt.*;

import java.awt.image.*;

import java.io.*;

import java.util.*;

import javax.imageio.*;

*/

interface ImageType {

public final static String JPG = "JPG";

public final static String PNG = "PNG";

public final static String GIF = "GIF";

}

public class ScreenDumpHelper {

/** ScreenDumpHelper 静态对象 */

private static ScreenDumpHelper defaultScreenDumpHelper;

public static ScreenDumpHelper getDefaultScreenDumpHelper() {

if (defaultScreenDumpHelper == null)

return new ScreenDumpHelper();

return defaultScreenDumpHelper;

}

public ScreenDumpHelper() {

Dimension dime = Toolkit.getDefaultToolkit().getScreenSize();

this.setScreenArea(new Rectangle(dime));

}

private Rectangle screenArea;

public Rectangle getScreenArea() {

return this.screenArea;

}

public void setScreenArea(Rectangle screenArea) {

this.screenArea = screenArea;

}

public void setScreenArea(int x, int y, int width, int height) {

this.screenArea = new Rectangle(x, y, width, height);

}

private BufferedImage getBufferedImage() throws AWTException {

BufferedImage imgBuf = null;

;

imgBuf = (new Robot()).createScreenCapture(this.getScreenArea());

return imgBuf;

}

/**

* 将 图像数据写到 输出流中去,方便再处理

*

* @param fileFormat

* @param output

* @return

*/

public boolean saveToOutputStream(String fileFormat, OutputStream output) {

try {

ImageIO.write(this.getBufferedImage(), fileFormat, output);

} catch (AWTException e) {

return false;

// e.printStackTrace();

} catch (IOException e) {

return false;

// e.printStackTrace();

}

return true;

}

/**

* 根据文件格式 返回随机文件名称

*

* @param fileFormat

* @return

*/

public String getRandomFileName(String fileFormat) {

return "screenDump_" + (new Date()).getTime() + "." + fileFormat;

}

/**

* 抓取 指定区域的截图 到指定格式的文件中 -- 这个函数是核心,所有的都是围绕它来展开的 * 图片的编码并不是以后缀名来判断: 比如s.jpg

* 如果其采用png编码,那么这个图片就是png格式的

*

* @param fileName

* @param fileFormat

* @return boolean

*/

public boolean saveToFile(String fileName, String fileFormat) {

if (fileName == null)

fileName = getRandomFileName(fileFormat);

try {

FileOutputStream fos = new FileOutputStream(fileName);

this.saveToOutputStream(fileFormat, fos);

} catch (FileNotFoundException e) {

System.out.println("非常规文件或不能创建抑或覆盖此文件: " + fileName);

e.printStackTrace();

}

return true;

}

/**

* 抓取 指定 Rectangle 区域的截图 到指定格式的文件中

*

* @param fileName

* @param fileFormat

* @param screenArea

* @return

*/

public boolean saveToFile(String fileName, String fileFormat,

Rectangle screenArea) {

this.setScreenArea(screenArea);

return this.saveToFile(fileName, fileFormat);

}

/**

* 抓取 指定区域的截图 到指定格式的文件中

*

* @param fileName

* @param fileFormat

* @param x

* @param y

* @param width

* @param height

*/

public boolean saveToFile(String fileName, String fileFormat, int x, int y,

int width, int height) {

this.setScreenArea(x, y, width, height);

return this.saveToFile(fileName, fileFormat);

}

/**

* 将截图使用 JPG 编码

*

* @param fileName

*/

public void saveToJPG(String fileName) {

this.saveToFile(fileName, ImageType.JPG);

}

public void saveToJPG(String fileName, Rectangle screenArea) {

this.saveToFile(fileName, ImageType.JPG, screenArea);

}

public void saveToJPG(String fileName, int x, int y, int width, int height) {

this.saveToFile(fileName, ImageType.JPG, x, y, width, height);

}

/**

* 将截图使用 PNG 编码

*

* @param fileName

*/

public void saveToPNG(String fileName) {

this.saveToFile(fileName, ImageType.PNG);

}

public void saveToPNG(String fileName, Rectangle screenArea) {

this.saveToFile(fileName, ImageType.PNG, screenArea);

}

public void saveToPNG(String fileName, int x, int y, int width, int height) {

this.saveToFile(fileName, ImageType.PNG, x, y, width, height);

}

public void saveToGIF(String fileName) {

throw new UnsupportedOperationException("不支持保存到GIF文件");

// this.saveToFile(fileName, ImageType.GIF);

}

/**

* @param args

*/

public static void main(String[] args) {

for (int i = 0; i < 5; i++)

ScreenDumpHelper.getDefaultScreenDumpHelper().saveToJPG(null,

i * 150, i * 150, 400, 300);

}

}

98.计算文件MD5值

/*

import java.io.*;

import java.math.*;

import java.security.*;

import java.util.*;

*/

File file=new File(%%1);

if (!file.isFile()){

return null;

}

MessageDigest digest = null;

FileInputStream in=null;

byte buffer[] = new byte[1024];

int len;

try {

digest = MessageDigest.getInstance("MD5");

in = new FileInputStream(file);

while ((len = in.read(buffer, 0, 1024)) != -1) {

digest.update(buffer, 0, len);

}

in.close();

} catch (Exception e) {

e.printStackTrace();

return null;

}

BigInteger bigInt = new BigInteger(1, digest.digest());

return bigInt.toString(16);

}

99.计算获取文件夹中文件的MD5值

/*

import java.io.*;

import java.math.*;

import java.security.*;

import java.util.*;

*/

public static String getFileMD5(File file) {

if (!file.isFile()){

return null;

}

MessageDigest digest = null;

FileInputStream in=null;

byte buffer[] = new byte[1024];

int len;

try {

digest = MessageDigest.getInstance("MD5");

in = new FileInputStream(file);

while ((len = in.read(buffer, 0, 1024)) != -1) {

digest.update(buffer, 0, len);

}

in.close();

} catch (Exception e) {

e.printStackTrace();

return null;

}

BigInteger bigInt = new BigInteger(1, digest.digest());

return bigInt.toString(16);

}

/**

* 获取文件夹中文件的MD5值

* @param file

* @param listChild ;true递归子目录中的文件

* @return

*/

public static Map<String, String> getDirMD5(File file,boolean listChild) {

if(!file.isDirectory()){

return null;

}

//<filepath,md5>

Map<String, String> map=new HashMap<String, String>();

String md5;

File files[]=file.listFiles();

for(int i=0;i<files.length;i++){

File f=files[i];

if(f.isDirectory()&&listChild){

map.putAll(getDirMD5(f, listChild));

} else {

md5=getFileMD5(f);

if(md5!=null){

map.put(f.getPath(), md5);

}

}

}

return map;

}

getDirMD5(%%1,%%2);

备注:

%%1

Runtime.getRuntime().

89.模拟键盘输入字符串

96.全屏幕截取

98.计算文件MD5值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: