1、文件读取与存储

package com.day.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;public class MyFileOperate {//写文件public static FileWriter fileWriter;//往文件写字符串public static PrintWriter printWriter;public static void main(String args[]) {//方法1String readString = MyFileOperate.fileRead("src/main/resources/Content.txt");System.out.println(readString);//方法2List<File> tempFileList=MyFileOperate.filesGetByFolder("src/main/resources/");for(int i=0;i<tempFileList.size();i++){System.out.println(tempFileList.get(i).getName());}//方法3MyFileOperate.fileContentClear("src/main/resources/Content.txt");//方法4PrintWriter tempPrintWriter=MyFileOperate.filePrintWriterInit("src/main/resources/Content.txt");//方法5tempPrintWriter.println("中华人民共和国");tempPrintWriter.flush();MyFileOperate.filePrintWriterClose();}/*** 1.读取格式为UTF-8的文本内容(用电脑打开txt文本,另存为下方可以查看)*/public static String fileRead(String FilePath) {FileInputStream fileInputStream = null;InputStreamReader inputStreamReader = null;//用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。BufferedReader bufferedReader = null;try {String str = "";String strAnother = "";fileInputStream = new FileInputStream(FilePath);// FileInputStream//从文件系统中的某个文件中获取字节//InputStreamReader 是字节流通向字符流的桥梁,inputStreamReader = new InputStreamReader(fileInputStream);//从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象bufferedReader = new BufferedReader(inputStreamReader);while ((str = bufferedReader.readLine()) != null) {strAnother = strAnother + str + "\n";}//当读取的一行不为空时,把读到的str的值赋给strAnotherreturn strAnother;} catch (FileNotFoundException e) {return "找不到指定文件";} catch (IOException e) {return "读取文件失败";} finally {try {//最后开的先关闭,所以先关bufferedReader,再关inputStreamReader,最后关fileInputStream。bufferedReader.close();inputStreamReader.close();fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}/*** 2.遍历文件读取指定文件夹下的所有文件。如果有子文件也会列出*/public static List<File> filesGetByFolder(String filePath){File root = new File(filePath);List<File> files = new ArrayList<File>();if(!root.isDirectory()){files.add(root);}else{File[] subFiles = root.listFiles();for(File f : subFiles){files.addAll(filesGetByFolder(f.getAbsolutePath()));}}return files;}/*** 3.清空指定文件的内容*/public static void fileContentClear(String filePath){try{FileWriter fileWriter =new FileWriter(new File(filePath));fileWriter.write("");fileWriter.flush();fileWriter.close();}catch (Exception e){e.printStackTrace();}}/*** 4.初始化文本文件存储器*/public static PrintWriter filePrintWriterInit(String filePath){try {//如果文件存在,则追加内容;如果文件不存在,则创建文件File file=new File(filePath);fileWriter = new FileWriter(file, true);} catch (IOException e) {e.printStackTrace();}printWriter= new PrintWriter(fileWriter);return printWriter;}/*** 5.关闭文本文件存储器*/public static void filePrintWriterClose(){try {printWriter.flush();printWriter.close();fileWriter.close();} catch (IOException e) {e.printStackTrace();}}
}

2、录音文件+实时播放

package com.day.util;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class MyRecord {/**要按N结束,否则PCM生成有问题,边录音边播放*//**AudioFormat是指定声音流中数据的特定排列的类。*/static AudioFormat audioFormat=new AudioFormat(16000F, 16, 1,true,false);/**目标数据线是可DataLine读取音频数据的类型DataLine 。TargetDataLine接口提供了从目标数据线缓冲区读取捕获数据的方法。*/public static TargetDataLine targetDataLine;public static SourceDataLine sourceDataLine;private static byte[] bytes = new byte[1280];private static String recordFileStorePath="src/main/resources/myRecord.pcm";public static void main(String args[]) throws Exception{System.out.println("y开始录音,n结束录音");Scanner scanner = new Scanner(System.in);String startCmd = scanner.next();long startTime = System.currentTimeMillis();if(startCmd.equals("y")){System.out.println("正在录音...");RecordThread recordThread=new MyRecord().new RecordThread();recordThread.start();Scanner scannerAnother = new Scanner(System.in);String endCmd = scannerAnother.next();if(endCmd.equals("n")){System.out.println("录音关闭...");System.out.println("共录音了"+(System.currentTimeMillis()-startTime)/1000+"秒!");//这里必须停止关闭,否则导致无法正常播放sourceDataLine.drain();sourceDataLine.close();targetDataLine.stop();targetDataLine.close();System.exit(0);}}}public class RecordThread extends Thread{public void run(){int len = -1;DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);try {targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);//开启录音线程targetDataLine.open(audioFormat);targetDataLine.start();long startTime=System.currentTimeMillis();// 设置数据输入,开启播放监听DataLine.Info dataLineInfoOut = new DataLine.Info(SourceDataLine.class,audioFormat, AudioSystem.NOT_SPECIFIED);sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfoOut);sourceDataLine.open(audioFormat);sourceDataLine.start();File file = new File(recordFileStorePath);FileOutputStream fileOutputStream = new FileOutputStream(file);AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;while ((len = new AudioInputStream(targetDataLine).read(bytes)) != -1) {fileOutputStream.write(bytes= Arrays.copyOfRange(bytes, 0, len),0, len);sourceDataLine.write( Arrays.copyOfRange(bytes, 0, len), 0, len);long endTime=System.currentTimeMillis();if (endTime-startTime>60000) {//关闭实时播放流sourceDataLine.drain();sourceDataLine.close();targetDataLine.stop();targetDataLine.close();break;}}} catch (Exception e) {e.printStackTrace();}}}
}

3、 判断是否是JSON

package com.day.util;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.*;public class IsJSON {public static void main(String[] args) {String jsonString="{\"fileType\":\"pdf\",\"seq\":1}";String jsonStringAnother="{\"fileType\":\"pdf\",\"seq\":1'}";//多个单引号System.out.println(isJSON(jsonString));System.out.println(isJSON(jsonStringAnother));}//判断是不是JSONpublic static boolean isJSON(String str){if(isJSONObject(str)||isJSONArray(str)){return true;}else{return false;}}//判断是不是JSON对象public static boolean isJSONObject(String str) {// 此处应该注意,不要使用StringUtils.isEmpty(),// 因为当content为"  "空格字符串时,JSONObject.parseObject可以解析成功,if(StringUtils.isBlank(str)){return false;}try {JSONObject jsonObject = JSONObject.parseObject(str);return true;} catch (Exception e) {return false;}}//判断是不是JSON数组public static boolean isJSONArray(String str) {if(StringUtils.isBlank(str)){return false;}StringUtils.isEmpty(str);try {JSONArray jsonStr = JSONArray.parseArray(str);return true;} catch (Exception e) {return false;}}
}

4、 使用Gson解析JSON数据

package com.day.util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;public class GsonUtil {private static Gson gson=new Gson();public static void main(String args[]){String jsonString="{\"name\":\"小明\",age:26}";JsonParse tempJsonParse=gson.fromJson(jsonString,JsonParse.class);System.out.println(tempJsonParse.name+"---"+tempJsonParse.age);String jsonStringAnother="[{\"name\":\"小明\",age:26},{\"name\":\"小红\",age:22}]";Type type = new TypeToken<List<JsonParse>>(){}.getType();List<Object> jsonParseList = gson.fromJson(jsonStringAnother,type);for(int i=0;i<jsonParseList.size();i++){JsonParse tempJsonParseAnother= (JsonParse) jsonParseList.get(i);System.err.println(tempJsonParseAnother.name+"---"+tempJsonParseAnother.age);}}
}
class JsonParse{public String name;public int age;
}

5、FFMPEG转换音频

package com.day.util;
import java.io.*;
import java.util.*;public class AudioConvert {public static void main(String []args) {//1.合并音频String tempPath=System.getProperty("user.dir").replaceAll("\\\\","/");String rootPath=tempPath+"/src/main/resources/static/server/audioMerge/";Scanner tempScanner=new Scanner(System.in);System.out.println("1. 把pcm转成16K的mp3\n"+"2. 把wav转成16K的pcm\n"+"3. 把mp3转成16K的pcm\n"+"4. 把pcm转成16K的wav\n"+"5. 把pcm转成16K的pcm\n"+"6. 把wav转成16K的wav\n"+"7. 把mp4转成mp3\n"+"8. 切割mp4\n"+"9. 切割pcm\n"+"10. 合并mp3音频");System.out.println("请选择你需要的操作");String chooseID=tempScanner.next();//System.out.println(chooseID);String tempFolder="src/main/resources/static/server/audioConvert/";//2.实现音频格式批量转换List<File> fileList=MyFileOperate.filesGetByFolder(tempFolder);switch (chooseID) {case "1":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changePcmTo16KMp3(tempFile.getName(), tempFolder,targetFileName + ".mp3");}break;case "2":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changeWavTo16KPcm(tempFile.getName(), tempFolder,targetFileName + ".pcm");}break;case "3":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changeMp3To16KPcm(tempFile.getName(), tempFolder,targetFileName + ".pcm");}break;case "4":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changePcmTo16KWav(tempFile.getName(), tempFolder,targetFileName + ".wav");}break;case "5":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);//需要指定原采样率changePcmTo16KPcm("", tempFile.getName(),tempFolder,targetFileName + ".pcm");}break;case "6":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changeWavTo16KWav(tempFile.getName(),tempFolder,targetFileName + ".wav");}break;case "7":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);changeMp4ToMp3(tempFile.getName(),tempFolder,targetFileName + ".mp3");}break;case "8":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);cutMp4("", "", tempFile.getName(),tempFolder,targetFileName + ".mp4");}break;case "9":for (File tempFile : fileList) {String targetFileName = tempFile.getName().substring(0, tempFile.getName().length() - 4);cutPCM("", "", tempFile.getName(),tempFolder,targetFileName + ".pcm");}break;case "10":StringBuilder cmd = new StringBuilder("ffmpeg -i \"concat:");List<File> files = MyFileOperate.filesGetByFolder(rootPath);for (File tempFile : files) {cmd.append(tempFile.getName()).append("|");}cmd.append("\" -c copy ").append(rootPath).append(new Date().getTime()).append("All.mp3");System.out.println(cmd);//拼接命令完毕后调用合并方法audioMerge(cmd.toString(), rootPath);break;}}/**1.合并音频*/public static void audioMerge(String cmd,String rootPath) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start = System.currentTimeMillis();//在指定目录下执行cmd命令,需要管理员权限才能执行Process process = runTime.exec("cmd /c "+cmd,null,new File(rootPath));//释放进程process.getOutputStream().close();process.getInputStream().close();process.getErrorStream().close();try {int mark=process.waitFor();System.out.println("返回的Mark值:"+mark);if(mark==0){long end = System.currentTimeMillis();System.out.println("合并成功, 耗时:" + (end - start) + "ms");}else{System.out.println(rootPath+"合并失败, mark值:" +mark);}} catch (InterruptedException e) {System.out.println("发生错误异常"+e);}} catch (Exception e) {e.printStackTrace();} finally {assert runTime != null;runTime.freeMemory();}}/**2.Mp4转换为Mp3*/public static void changeMp4ToMp3(String srcFileName,String rootPath,String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令System.out.println("cmd /c ffmpeg -y -i "+srcFileName+" "+targetFileName);Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" "+targetFileName,null,new File(rootPath));//释放进程//System.err.println("ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName);//System.err.println(rootPath);closeStream(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}//抽取出来的方法private static void closeStream(String srcFileName, String rootPath, long start, Process process) throws IOException, InterruptedException {process.getOutputStream().close();process.getInputStream().close();process.getErrorStream().close();int mark=process.waitFor();if(mark==0){long end=System.currentTimeMillis();System.out.println("转换成功, 耗时:"+(end-start)+"ms");System.out.println("路径保存在: "+rootPath);}else{System.out.println(srcFileName+"操作失败,mark值:"+mark);}}/**3.Wav转换为16K的PCM*/public static void changeWavTo16KPcm(String srcFileName,String rootPath,String targetFileName) {changeWavTo16KPcmPathAndFile(srcFileName, rootPath, targetFileName);}private static void changeWavTo16KPcmPathAndFile(String srcFileName, String rootPath, String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));//释放进程//System.err.println("ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName);//System.err.println(rootPath);closeStream(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}/**4.Mp3转换为16K的PCM*/public static void changeMp3To16KPcm(String srcFileName,String rootPath,String targetFileName) {changeWavTo16KPcmPathAndFile(srcFileName, rootPath, targetFileName);}public static void changePcmTo16KWav(String srcFileName,String rootPath,String targetFileName) {pathAndFile(srcFileName, rootPath, targetFileName);}//抽取出来的方法private static void pathAndFile(String srcFileName, String rootPath, String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//System.out.println("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName);//在指定目录下执行cmd命令Process process=runTime.exec("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName,null,new File(rootPath));//释放进程closeStream(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}/**6.PCM转换为16K的Mp3*/public static void changePcmTo16KMp3(String srcFileName,String rootPath,String targetFileName) {pathAndFile(srcFileName, rootPath, targetFileName);}/**7.PCM转换为16K的PCM*/public static void changePcmTo16KPcm(String ar,String srcFileName,String rootPath,String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令Process process=runTime.exec("cmd /c ffmpeg -y -f s16le -ar "+ar+" -ac 1 -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));//释放进程closeStream(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}/**8.Wav转换为16K的Wav*/public static void changeWavTo16KWav(String srcFileName,String rootPath,String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -b 16000 -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));//释放进程closeStream(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}/**10.Mp4视频的切割*/public static void cutMp4(String startTime,String endTime,String srcFileName,String rootPath,String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令//ffmpeg -ss 00:00:00 -t 00:00:03 -i source.mp4 -vcodec copy -acodec copy myCut.mp4Process process=runTime.exec("cmd /c ffmpeg -ss " +startTime+" -t "+endTime+" -i "+srcFileName+" -vcodec copy -acodec copy "+targetFileName,null,new File(rootPath));//释放进程abstractMethod3(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}private static void abstractMethod3(String srcFileName, String rootPath, long start, Process process) throws IOException, InterruptedException {process.getOutputStream().close();process.getInputStream().close();process.getErrorStream().close();int mark=process.waitFor();if(mark==0){long end=System.currentTimeMillis();System.out.println("分割成功, 耗时:"+(end-start)+"ms");System.out.println("路径保存在: "+rootPath);}else{System.out.println(srcFileName+"操作失败,mark值:"+mark);}}/**11.PCM音频的切割*/public static void cutPCM(String startTime,String endTime,String srcFileName,String rootPath,String targetFileName) {Runtime runTime = null;try {runTime = Runtime.getRuntime();long start=System.currentTimeMillis();//在指定目录下执行cmd命令//ffmpeg -f s16le -ar 16000 -acodec pcm_s16le -i source.pcm -ss 00:00:00 -t 00:00:03  -f s16le -ar 16000 -ac 1 myCut.pcmProcess process=runTime.exec("cmd /c ffmpeg -f s16le -ar 16000 -acodec pcm_s16le -i "+srcFileName+" -ss "+startTime+" -t "+endTime+" -f s16le -ar 16000 -ac 1 "+targetFileName,null,new File(rootPath));//释放进程abstractMethod3(srcFileName, rootPath, start, process);} catch (Exception e) {e.printStackTrace();}finally{//run调用lame解码器最后释放内存assert runTime != null;runTime.freeMemory();}}
}

6、邮箱发送验证码

package com.day.util.mail;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/*** 邮件处理类* */
public class MailUtil {//配置信息private static final String FROM_MAIL_SMTP = "220.181.15.111";private static final String FROM_MAIL_NAME = "您的邮箱";private static final String FROM_MAIL_PASS = "您邮箱的服务密码";/*** 发送邮件(灵活度高,通用版)* @param from 发件人* @param to 收件人, 多个Email以英文逗号分隔* @param cc 抄送, 多个Email以英文逗号分隔* @param subject 主题* @param content 内容* @param fileList 附件列表* @return*/public static void sendMail(String to, /*String cc,*/ String subject, String content/*, String[] fileList*/){try {Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";final Properties properties = System.getProperties() ;properties.setProperty("mail.smtp.host", FROM_MAIL_SMTP);properties.setProperty("mail.smtp.auth", "true");properties.setProperty("mail.smtp.user", FROM_MAIL_NAME);properties.setProperty("mail.smtp.pass", FROM_MAIL_PASS);properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);properties.setProperty("mail.smtp.socketFactory.fallback", "false");//邮箱发送服务器端口,这里设置为465端口properties.setProperty("mail.smtp.port","465");properties.setProperty("mail.smtp.socketFactory.port","465");// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession session = Session.getInstance(properties, new Authenticator(){protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(properties.getProperty("mail.smtp.user"),properties.getProperty("mail.smtp.pass"));}});session.setDebug(true);Message message = new MimeMessage(session);//消息发送的主题message.setSubject(subject);//接受消息的人message.setReplyTo(InternetAddress.parse(FROM_MAIL_NAME));//消息的发送者message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.user"),"Now For Dreams"));// 创建邮件的接收者地址,并设置到邮件消息中String[] split = to.split(",");InternetAddress []tos = new InternetAddress[split.length];for (int i = 0; i < split.length; i++) {tos[i]=new InternetAddress(split[i]);}// 设置抄送人/*if (cc != null && cc.length() > 0) {message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); }*/message.setRecipients(Message.RecipientType.TO, tos);// 消息发送的时间message.setSentDate(new Date());Multipart mainPart = new MimeMultipart();// 创建一个包含HTML内容的MimeBodyPartBodyPart html = new MimeBodyPart();// 设置HTML内容html.setContent(content, "text/html; charset=utf-8");mainPart.addBodyPart(html);// 将MiniMultipart对象设置为邮件内容message.setContent(mainPart);// 设置附件/*if (fileList != null && fileList.length > 0) {for (int i = 0; i < fileList.length; i++) {html = new MimeBodyPart();FileDataSource fds = new FileDataSource(fileList[i]); html.setDataHandler(new DataHandler(fds)); html.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));mainPart.addBodyPart(html); }}*/message.setContent(mainPart); message.saveChanges(); Transport.send(message);} catch (MessagingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}/*** 测试Mian方法* * @param args*/public static void main(String[] args) {/*String content = "<html><head><style type='text/css'>p{padding-left:50px;font-family:'楷体';font-size:20px;}table{padding-left:50px;border:0;font-family:'楷体';font-size:30px;}</style></head><body>您好:<br/><p>申请编号为"+"测试测试内容"+"的经销商对订单发起放弃签约,具体信息如下:</p><table border='1'  cellpadding='10' cellspacing='0'> <tr align='center'><td width='200'>经销商</td> <td width='300'>"+"无需回复"+"</td> </tr> <tr align='center'><td>申请编号</td><td>"+"测试测试内容"+"</td></tr> <tr align='center'><td>取消时间</td><td>"+"无需回复"+"</td></tr> <tr align='center'><td>加装GPS数量</td><td>"+"测试测试内容"+"</td></tr> <tr align='center'><td>GPS IMEI号</td><td>"+"测试测试内容"+"</td></tr><tr align='center'><td>店铺地址</td><td>"+"测试测试内容"+"</td></tr> <tr align='center'><td>店铺联系人姓名</td><td>"+"测试测试内容"+"</td></tr> <tr align='center'><td>店铺联系人电话</td><td>"+"测试测试内容"+"</td></tr> </table><p>请及时联系GPS相关人员,安排上门拆装,谢谢!</p>------------------------------------------------------------------------------</body></html>";content = "<html><head><style type='text/css'>p{padding-left:50px;font-family:'楷体';font-size:20px;}table{padding-left:50px;border:0;font-family:'楷体';font-size:30px;}</style></head><body>Hey:<br/><p>我们发现您的用户评测报告已经出来了,赶紧来看看:</p><p>用户:吕坤     手机号:17697182873    评测进度:3/9 (评测越多,报告越丰富哦):</p><p>河马小提示:点击链接查看报告</p><p>个人信用报告:<a href='https://axhub.im/pro/dbf03b6626db7bde/' target='_blank'>https://axhub.im/pro/dbf03b6626db7bde/</a></p><p>联系人信息:<a href='https://axhub.im/pro/dbf03b6626db7bde/' target='_blank'>https://axhub.im/pro/dbf03b6626db7bde/</a></p></body></html>";System.out.println(content);String[] fileList = new String[1];fileList[0] = "d:/pac.txt";*/sendMail("wdfgdzx@163.com", "wdfgdzx.top信息种类","IT");}
}

 7、生成随机验证码

package com.day.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.day.pojo.MySession;
import com.day.pojo.SystemSession;
import com.day.util.mail.MailUtil;
public class MakeCode extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubdoPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {resp.setContentType("text/html");req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");//6禁止缓存随机图片resp.setDateHeader("Expires", -1);resp.setHeader("Cache-Control", "no-cache");resp.setHeader("Pargam","no-cache");//7通知客户机以图片的方式打开发送过去的数据resp.setHeader("Content-Type", "image/jpeg");//1在内存中创建背景图片//BufferedImage bufferedImage=new BufferedImage(70,22,BufferedImage.TYPE_INT_RGB);BufferedImage bufferedImage=new BufferedImage(63,22,BufferedImage.TYPE_INT_RGB);//2向图片上写数据Graphics graphics=bufferedImage.getGraphics();//3设置背景色graphics.setColor(new Color(79,148,205));//graphics.fillRect(0, 0, 70, 22);graphics.fillRect(0, 0, 63, 22);//设置写入数据的颜色和字体graphics.setColor(Color.white);graphics.setFont(new Font(null, Font.ITALIC, 20));//4向图片写数据String temp=makeRandom();//temp如果是汉字或者是一个数学题库都可以生成的//随机产生的值保存到sessionSystemSession systemSession=null;if(req.getSession().getAttribute("systemSession")==null){systemSession=new SystemSession();}else{systemSession=(SystemSession) req.getSession().getAttribute("systemSession");}systemSession.setVerifyCode(temp);//设置到会话中去req.getSession().setAttribute("systemSession", systemSession);//设置系统产生会话//设置一个隐藏参数ajax请求后返回对比,这是"历史性"的一步graphics.drawString(temp, 5, 20);//5把写好的图片数据给浏览器ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());}//产生4位随机数public String makeRandom(){Random random=new Random();//明显9999999和7控制了  到底产生几位数String temp=random.nextInt(9999)+"";StringBuffer sringBuffer=new StringBuffer();for(int i=0;i<4-temp.length();i++){//为什么随机数不够7位补充0用的sringBuffer.append("0");}temp=temp+sringBuffer.toString();return temp;}
}

 8、JDBC操作数据库

package com.day.controller;
import java.sql.*;public class JDBC {public static Connection connection;public static Statement statement;public static void main(String[] args) {//增insert("insert into my_table1 (name,score) values ('lucy',46.97);");//改//update("update my_table1 set name='mark' where id=5;");//删//delete("delete from my_table1 where id=2;");//查select("select * from my_table1;");}public static Connection getConnection() {Connection connection = null;   //创建用于连接数据库的Connection对象try {// 载入Mysql数据驱动Class.forName("com.mysql.jdbc.Driver");// 创建数据连接,指定名为text的database进行操作。connection = DriverManager.getConnection("jdbc:mysql://您的IP:3306/text?serverTimezone=UTC", "数据库用户名", "数据库密码");} catch (Exception e) {System.out.println("数据库连接失败" + e.getMessage());}//返回所建立的数据库连接return connection;}//增public static void insert(String SQL) {connection = getConnection();    // 首先要获取连接,即连接到数据库try {// 创建用于运行静态SQL语句的Statement对象statement = (Statement) connection.createStatement();// 运行插入操作的SQL语句,并返回插入数据的个数int count = statement.executeUpdate(SQL);//输出插入操作的处理结果System.out.println("向指定表中插入 " + count + " 条数据");//关闭数据库连接connection.close();} catch (Exception e) {System.out.println("插入数据失败" + e.getMessage());}}//查public static void select(String SQL) {connection = getConnection();try {statement = (Statement) connection.createStatement();ResultSet resultSet = statement.executeQuery(SQL);System.out.println("最后的查询结果为:");while (resultSet.next()) {   // 推断是否还有下一个数据// 依据字段名获取对应的值int id = resultSet.getInt("id");String name = resultSet.getString("name");float score = resultSet.getFloat("score");//输出查到的记录的各个字段的值System.out.println("ID: "+id+"--- 姓名: "+name + "--- 分数: " + score);}connection.close(); //关闭数据库连接} catch (Exception e) {System.out.println("查询数据失败");}}//改public static void update(String SQL) {connection = getConnection();try {statement = (Statement) connection.createStatement();int count = statement.executeUpdate(SQL);System.out.println("staff表中更新 " + count + " 条数据");connection.close();} catch (SQLException e) {System.out.println("更新数据失败");}}//删public static void delete(String SQL) {connection = getConnection();try {statement = (Statement) connection.createStatement();int count = statement.executeUpdate(SQL);System.out.println("指定表中删除 " + count + " 条数据\n");connection.close();} catch (SQLException e) {System.out.println("删除数据失败");}}
}

9、 SHA256加密

package com.day.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*** 利用java原生的摘要实现SHA256加密* 不要用123这种简单容易根据结果破解的密码*/
public class SHA256{public static String getSHA256StrJava(String str){MessageDigest messageDigest;String encodeStr = "";try {messageDigest = MessageDigest.getInstance("SHA-256");messageDigest.update(str.getBytes("UTF-8"));encodeStr = byte2Hex(messageDigest.digest());} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return encodeStr;}/*** 将byte转为16进制* @param bytes* @return*/private static String byte2Hex(byte[] bytes){StringBuffer stringBuffer = new StringBuffer();String temp = null;for (int i=0;i<bytes.length;i++){temp = Integer.toHexString(bytes[i] & 0xFF);if (temp.length()==1){//1得到一位的进行补0操作stringBuffer.append("0");}stringBuffer.append(temp);}return stringBuffer.toString();}
}

10、 日期格式化

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String nowDateStr=simpleDateFormat.format(new Date());System.out.println("当前时间为: "+nowDateStr);

11、JSON带关键字解析

{"char": [[36,"届","解","char"]]
}
class JsonParseInner{   @SerializedName("char")ArrayList char1;
}

12、添加JAR包

(1)手动添加

java -Xbootclasspath/a:lfasr-sdk-3.0.1.jar;log4j-1.2.17.jar;commons-codec-1.9.jar;commons-logging-1.2.jar;fastjson-1.2.67.jar;httpclient-4.5.jar;httpcore-4.4.1.jar;httpmime-4.5.jar -jar demo-3.0-1.0-SNAPSHOT.jar

(2)通过项目自动指定

【1】把所有JAR包拷贝到IDEA项目的lib下

【2】IDEA下File-Project Structure-Artifacts

【3】Build-XXX.jar-Build 即可自动指定

JAVA TOOL-【1】配置相关推荐

  1. Java程序设计(Java9版):第1章 Java开发环境配置 (Set up Java development environment)

    第1章Java开发环境配置(Set up Java development environment) 工欲善其事,必先利其器. - <论语·卫灵公> Write once, run any ...

  2. JAVA环境变量配置与配置后CMD的使用

    JAVA环境变量配置: 直接在环境变量Path(或PATH,大小写无所谓)里加上 :JDK安装路径名/bin 也可以先设JAVA_HOME然后再设JAVA_HOME/bin,但必须是在同一区域中进行设 ...

  3. java读取ES配置生成ES管理类,获取ES连接

    java读取ES配置生成ES管理类,获取ES连接 1.Elasticsearch是基于Lucene开发的一个分布式全文检索框架,向Elasticsearch中存储和从Elasticsearch中查询, ...

  4. java 开发环境配置_Java 开发环境配置

    在本章节中我们将为大家介绍如何搭建Java开发环境.Windows 上安装开发环境 Linux 上安装开发环境 安装 Eclipse 运行 Java window系统安装java 下载JDK 首先我们 ...

  5. Java中classpath配置

    Java中classpath配置 一.DOS常用命令 二.DOS常用命令实例 2.1 转换目录 cd 1.6* 2.2 删除文件 del 删除文件(windows删除从里往外删) del *.txt ...

  6. u盘可以安装java吗_java下载安装 (三)Java 开发环境配置

    下载后JDK的安装根据提示进行,还有安装JDK的时候也会安装JRE,一并安装就可以了. 安装JDK,安装过程中可以自定义安装目录等信息,例如我们选择安装目录为C:\Program Files (x86 ...

  7. Spring-基于Java类的配置

    概述 使用Java类提供Bean定义信息 实例 分析 使用基于Java类的配置信息启动Spring容器 直接通过Configuration启动Spring容器 通过AnnotationConfigAp ...

  8. Java环境变量配置详细步骤

    引言 很多初学Java的小伙伴可能都会听别人说想要编译运行Java程序需要配置环境变量,所以在这里我就手把手教给你如何配置Java环境变量: 再多说一句,可能会有小伙伴想:我编译运行Java程序干嘛要 ...

  9. java EE 5配置邮件发送 qq企业邮箱

    为什么80%的码农都做不了架构师?>>>    java EE 5配置QQ企业邮件发送 1.在项目的WebRoot/META-INF/新建context.xml 具体内容如下: &l ...

  10. 图文详解Java环境变量配置方法

    今天动力节点java学院小编为大家介绍"图文详解Java环境变量配置方法",希望对各位小伙伴有帮助,下面就和小编一起来看看Java环境变量配置方法吧. 首先是要安装JDK,JDK安 ...

最新文章

  1. Pandas 基础 (3)—— 重新索引
  2. spring 中 Hibernate 事务和JDBC事务嵌套问题
  3. 《童梦奇缘-梦幻般的羁绊》第一章-朦胧
  4. 一个JSP大马的源码
  5. matlab 纵坐标 科学计数法,echarts纵坐标使用科学计数法表示
  6. Idea的svn新建分支,切换分支,合并分支
  7. cenetos 查看字体库_Centos7 安装字体库中文字体
  8. 【ICPC-303】hau 1874 畅通工程续
  9. 解决ERROR: text file '***' contains disallowed UTF-8 whitespace character(s)
  10. thinkPHP基于php的枣院二手图书交易系统-计算机毕业设计
  11. 红外光谱图解析知识大全(图文并茂)
  12. 调试工具-DEBUG
  13. Windows环境下安装pkg-config
  14. qgis 图片_QGIS简介
  15. Gbox开源:比RN和WebView更轻的高性能动态化业务容器,解决首页动态化的痛点
  16. 关于printf输出格式%#08x的解释
  17. ACM传奇之路(紧握着自己颤抖的双手)
  18. javaee之http协议、request请求
  19. 动效给程序员用什么格式_UI动效敲砖篇
  20. vite配置cdn优化打包体积

热门文章

  1. 清理win10不常用服务
  2. 【初创期】企业的安全建设之路到底有多难?
  3. Vue打包后出现的bug -favicon.ico' because it violates the following Content Security Policy direc
  4. 常见计算机主机内部硬件设备,计算机的硬件主要包括中央处理器、储存器、输出设备和...
  5. UE4_直播RT输出到OBS教程
  6. 著名画家赵准旺的名人评语
  7. UML图中类之间的关系:依赖,泛化,关联,聚合,组合,实现
  8. 微信小程序云端增强 SDK接入
  9. android 8.0 ps 命令,全网最全adb命令 - osc_8exjk9uk的个人空间 - OSCHINA - 中文开源技术交流社区...
  10. 蓝桥杯比赛准备总结(大学编程学习历程)