JAVA TOOL-【1】配置

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[]) {
		//方法1
		String readString = MyFileOperate.fileRead("src/main/resources/Content.txt");
		System.out.println(readString);
		//方法2
		List<File> tempFileList=MyFileOperate.filesGetByFolder("src/main/resources/");
		for(int i=0;i<tempFileList.size();i++){
			System.out.println(tempFileList.get(i).getName());
		}
		//方法3
		MyFileOperate.fileContentClear("src/main/resources/Content.txt");
		//方法4
		PrintWriter tempPrintWriter=MyFileOperate.filePrintWriterInit("src/main/resources/Content.txt");
		//方法5
		tempPrintWriter.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的值赋给strAnother
			return 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));
	}
	//判断是不是JSON
	public 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.mp4
            Process 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.pcm
            Process 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");
 
			// 根据邮件会话属性和密码验证器构造一个发送邮件的session
			Session 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内容的MimeBodyPart
			BodyPart 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{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	}
	@Override
	protected 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如果是汉字或者是一个数学题库都可以生成的
		//随机产生的值保存到session
		SystemSession 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 即可自动指定

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值