JAVA常用工具方法

第一章=>
1、文件读取存储           
2、录音文件+实时播放         
3、判断是否JSON           
4、使用Gson

第二章=>
5、ffmpeg转换音频     
6、邮件发送验证码               
7、生成随机验证码           
8、JDBC操作数据库

第三章=>
9、SHA256机密           
10、日期格式化(实践..)     
11、JSON关键字             
12、添加Jar包                   
13、WebScoket使用       
14、IO流、字节流实现文件复制

1、文件读取与存储
package com.day;
import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //读
        FileInputStream fileInputStream = new FileInputStream("src/resources/src.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //写
        FileOutputStream fileOutputStream = new FileOutputStream("src/resources/dst.txt");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            outputStreamWriter.write(line);
            System.out.print(line);
        }
        //写
        bufferedWriter.close();
        outputStreamWriter.close();
        fileOutputStream.close();
        //读
        bufferedReader.close();
        inputStreamReader.close();
        fileInputStream.close();
    }
}

-----------------------------------------------------
package com.day;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;


public class Main {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("src/resources/src.txt");
        byte[] byteArray = new byte[1024];
        int len;
        FileOutputStream fileOutputStream = new FileOutputStream("src/resources/dst.txt");
        while ((len = fileInputStream.read(byteArray)) != -1) {
            String temp = new String(byteArray, 0, len);
            fileOutputStream.write(new String(byteArray, 0, len).getBytes(StandardCharsets.UTF_8));
            System.out.print(temp);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}

----------------------------------------------------------------
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 + "
";
			}
			//当读取的一行不为空时,把读到的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
"+
                "2. 把wav转成16K的pcm
"+
                "3. 把mp3转成16K的pcm
"+
                "4. 把pcm转成16K的wav
"+
                "5. 把pcm转成16K的pcm
"+
                "6. 把wav转成16K的wav
"+
                "7. 把mp4转成mp3
"+
                "8. 切割mp4
"+
                "9. 切割pcm
"+
                "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 + " 条数据
");
            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);
实践证明:加个 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")都解决了,说明了技术在进步,新事物需要不断学习...

****************************************************************************************************************************************************************************

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
1631579350144041679.jpg
 【3】Build-XXX.jar-Build 即可自动指定

****************************************************************************************************************************************************************************

13、WebSocket调用
package com.day;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.HttpUrl;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
public class UserMain {
    public static final Gson gson = new Gson();
    public static final Decoder decoder = new Decoder();

    public static void main(String[] args) throws Exception {
        String hostUrl = "https://iat-api.xfyun.cn/v2/iat";
        String appid = "5e11538f";
        String apiSecret = "ff446b96b01252f80331ae6e4c64984a";
        String apiKey = "91205afe0d17e38c61be35fca346503c";
        String wsUrl = getAuthUrl(hostUrl, apiKey, apiSecret).replace("https://", "wss://");
        websocketWork(wsUrl);
    }

    //Websocket方法
    public static void websocketWork(String wsUrl) {
        try {
            URI uri = new URI(wsUrl);
            WebSocketClient webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("建立连接成功...");
                }

                @Override
                public void onMessage(String text) {
                    //System.out.println(text);
                    ResponseData responseData = gson.fromJson(text, ResponseData.class);
                    if (responseData != null) {
                        if (responseData.getCode() != 0) {
                            System.out.println("code=>" + responseData.getCode() + " sid=" + responseData.getSid());
                        }
                        if (responseData.getData() != null) {
                            if (responseData.getData().getResult() != null) {
                                Text te = responseData.getData().getResult().getText();
                                try {
                                    decoder.decode(te);
                                    System.out.println("中间识别结果 ==》" + decoder.toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            if (responseData.getData().getStatus() == 2) {
                                // 可以关闭连接,释放资源
                                System.out.println("最终识别结果 ==》" + decoder.toString());
                                System.out.println("本次识别sid ==》" + responseData.getSid());
                                System.exit(1000);
                            } else {
                                // todo 根据返回的数据处理
                            }
                        }
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                }

                @Override
                public void onError(Exception e) {
                    System.out.println(e.getMessage());
                }
            };
            // 建立连接
            webSocketClient.connect();
            while (!webSocketClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                //System.out.println("正在连接...");
                Thread.sleep(100);
            }
            MyThread webSocketThread = new MyThread(webSocketClient);
            webSocketThread.start();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    // 鉴权方法
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "
" +
                "date: " + date + "
" +
                "GET " + url.getPath() + " HTTP/1.1";
        //System.out.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key="%s", algorithm="%s", headers="%s", signature="%s"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        return httpUrl.toString();
    }

    // 线程来发送音频与参数
    static class MyThread extends Thread {
        WebSocketClient webSocketClient;

        public MyThread(WebSocketClient webSocketClient) {
            this.webSocketClient = webSocketClient;
        }

        public void run() {
            int frameSize = 1280;//帧大小
            byte[] bufferArray = new byte[frameSize];//字节数组1280
            int interval = 40;//间隔40ms发送一次
            int status = 0;//初始发送为0、中间1、最后2
            int len;//标记文件读取结果
            String requestJson;//请求json串
            try {
                FileInputStream fileInputStream = new FileInputStream("src/resources/1.pcm");
                // 循环发送音频文件内容
                while (true) {
                    len = fileInputStream.read(bufferArray);
                    if (len == -1) {
                        status = 2;// 标志读取完毕
                    }
                    switch (status) {
                        case 0: //首次发音频
                            requestJson = "{
" +
                                    "  "common": {
" +
                                    "    "app_id": "5e11538f"
" +
                                    "  },
" +
                                    "  "business": {
" +
                                    "    "language": "zh_cn",
" +
                                    "    "domain": "iat",
" +
                                    "    "accent": "mandarin",
" +
                                    "    "dwa": "wpgs"
" +
                                    "  },
" +
                                    "  "data": {
" +
                                    "    "status": 0,
" + //首帧
                                    "    "format": "audio/L16;rate=16000",
" +
                                    "    "encoding": "raw",
" +
                                    "    "audio": "" + Base64.getEncoder().encodeToString(Arrays.copyOf(bufferArray, len)) + ""
" +
                                    "  }
" +
                                    "}";
                            webSocketClient.send(requestJson);
                            status = 1;
                            break;
                        case 1: //中间音频
                            requestJson = "{
" +
                                    "  "data": {
" +
                                    "    "status": 1,
" + //中间帧
                                    "    "format": "audio/L16;rate=16000",
" +
                                    "    "encoding": "raw",
" +
                                    "    "audio": "" + Base64.getEncoder().encodeToString(Arrays.copyOf(bufferArray, len)) + ""
" +
                                    "  }
" +
                                    "}";
                            webSocketClient.send(requestJson);
                            break;
                        case 2: //最后音频
                            requestJson = "{
" +
                                    "  "data": {
" +
                                    "    "status": 2,
" +
                                    "    "format": "audio/L16;rate=16000",
" +
                                    "    "encoding": "raw",
" +
                                    "    "audio": ""
" +
                                    "  }
" +
                                    "}";
                            webSocketClient.send(requestJson);
                            break;
                    }
                    if (status == 2) {
                        break;
                    }
                    Thread.sleep(interval); //模拟音频采样延时
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 返回结果拆解
    public static class ResponseData {
        private int code;
        private String message;
        private String sid;
        private Data data;

        public int getCode() {
            return code;
        }

        public String getMessage() {
            return this.message;
        }

        public String getSid() {
            return sid;
        }

        public Data getData() {
            return data;
        }
    }

    public static class Data {
        private int status;
        private Result result;

        public int getStatus() {
            return status;
        }

        public Result getResult() {
            return result;
        }
    }

    public static class Result {
        int bg;
        int ed;
        String pgs;
        int[] rg;
        int sn;
        Ws[] ws;
        boolean ls;
        JsonObject vad;

        public Text getText() {
            Text text = new Text();
            StringBuilder sb = new StringBuilder();
            for (Ws ws : this.ws) {
                sb.append(ws.cw[0].w);
            }
            text.sn = this.sn;
            text.text = sb.toString();
            text.sn = this.sn;
            text.rg = this.rg;
            text.pgs = this.pgs;
            text.bg = this.bg;
            text.ed = this.ed;
            text.ls = this.ls;
            text.vad = this.vad == null ? null : this.vad;
            return text;
        }
    }

    public static class Ws {
        Cw[] cw;
        int bg;
        int ed;
    }

    public static class Cw {
        int sc;
        String w;
    }

    public static class Text {
        int sn;
        int bg;
        int ed;
        String text;
        String pgs;
        int[] rg;
        boolean deleted;
        boolean ls;
        JsonObject vad;

        @Override
        public String toString() {
            return "Text{" +
                    "bg=" + bg +
                    ", ed=" + ed +
                    ", ls=" + ls +
                    ", sn=" + sn +
                    ", text='" + text + ''' +
                    ", pgs=" + pgs +
                    ", rg=" + Arrays.toString(rg) +
                    ", deleted=" + deleted +
                    ", vad=" + (vad == null ? "null" : vad.getAsJsonArray("ws").toString()) +
                    '}';
        }
    }

    public static class Decoder {
        private Text[] texts;
        private int defc = 10;

        public Decoder() {
            this.texts = new Text[this.defc];
        }

        public synchronized void decode(Text text) {
            if (text.sn >= this.defc) {
                this.resize();
            }
            if ("rpl".equals(text.pgs)) {
                for (int i = text.rg[0]; i <= text.rg[1]; i++) {
                    this.texts[i].deleted = true;
                }
            }
            this.texts[text.sn] = text;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (Text t : this.texts) {
                if (t != null && !t.deleted) {
                    sb.append(t.text);
                }
            }
            return sb.toString();
        }

        public void resize() {
            int oc = this.defc;
            this.defc <<= 1;
            Text[] old = this.texts;
            this.texts = new Text[this.defc];
            for (int i = 0; i < oc; i++) {
                this.texts[i] = old[i];
            }
        }

        public void discard() {
            for (int i = 0; i < this.texts.length; i++) {
                this.texts[i] = null;
            }
        }
    }
}
--------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>Websocket</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <!-- TODO project name  -->
    <name>quickstart</name>
    <description></description>


    <dependencies>
        <!-- okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.1</version>
        </dependency>
        <!-- Java-WebSocket -->
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.8</version>
        </dependency>
        <!--fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.79</version>
        </dependency>
        <!-- gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.0</version>
        </dependency>


    </dependencies>


</project>

Websocket.rar

form_recognition_java_demo.rar

JAVA实现Excel的LOOK UP功能
1、依赖
<!--Excel工具-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.20</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
2、代码
package com.day.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws Exception {
        InputStream inputStream = new FileInputStream("src/main/resources/src.xlsx");
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
        // 忽略表头文件,直接读取内容
        List<List<Object>> list = excelReader.read(1);
        List<String> srcUidList = CollUtil.newArrayList();
        for (List<Object> row : list) {
            srcUidList.add(row.get(0).toString());
        }
        inputStream = new FileInputStream("src/main/resources/tar.xlsx");
        excelReader = ExcelUtil.getReader(inputStream);
        // 忽略表头文件,直接读取内容
        List<List<Object>> list2 = excelReader.read(1);
        List<User> tarUidList = CollUtil.newArrayList();
        for (List<Object> row : list2) {
            User tempUser = new User();
            tempUser.setUid(row.get(0).toString());
            tempUser.setPhone(row.get(1).toString());
            tempUser.setReg_time(row.get(2).toString());
            tempUser.setOrderNum(row.get(3).toString());
            tempUser.setOrderPay(row.get(4).toString());
            tempUser.setText(row.get(5).toString());
            tempUser.setImage(row.get(6).toString());
            tempUser.setAudio(row.get(7).toString());
            tempUser.setVideo(row.get(8).toString());
            tarUidList.add(tempUser);
        }
        Map<String, Object> tarUidMap = new HashMap<>();
        for (User user : tarUidList) {
            tarUidMap.put(user.getUid(), user);
        }
        List<User> outUserList = new ArrayList<>();
        int i = 0;
        for (String srcUid : srcUidList) {
            if (tarUidMap.containsKey(srcUid)) {
                outUserList.add((User) tarUidMap.get(srcUid));
            } else {
                User user = new User();
                user.setUid(srcUid);
                outUserList.add(user);
            }
            i++;
            System.out.println("运行中..." + i);
        }
        ExcelWriter excelWriter = ExcelUtil.getWriter(true);
        FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/" + "outExcel.xlsx");
        excelWriter.write(outUserList);
        excelWriter.flush(fileOutputStream);
        excelWriter.close();
    }
}
3、实体类
package com.day.controller;

import lombok.Data;

@Data
public class User {
    private String uid;
    private String phone;
    private String reg_time;
    private String orderNum;
    private String orderPay;
    private String text;
    private String image;
    private String audio;
    private String video;
}

****************************************************************************************************************************************************************************

14、IO流、字节流复制文件
package com.day.controller;
import java.io.*;
public class Hello {
    public static void main(String[] args) throws Exception {
        long startTime=System.currentTimeMillis();
        FileInputStream fileInputStream=new FileInputStream("src/main/resources/src.pptx");
        FileOutputStream fileOutputStream=new FileOutputStream("src/main/resources/out.pptx");
        // 使用确实变快了,不用也可以,代码不用变
        BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
        // 使用确实变快了,不用也可以,代码不用变
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream);
        byte[] byteArray=new byte[1024];
        int len;
        while((len=bufferedInputStream.read(byteArray))!=-1){
            bufferedOutputStream.write(byteArray,0,len);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("耗时"+(endTime-startTime)+"ms");
    }
}
读取文本中的内容
package com.day.controller;
import java.io.*;
public class Hello {
    public static void main(String[] args) throws Exception {
        long startTime=System.currentTimeMillis();
        FileInputStream fileInputStream=new FileInputStream("src/main/resources/1.txt");
        FileOutputStream fileOutputStream=new FileOutputStream("src/main/resources/out.pptx");
        // 使用确实变快了,不用也可以,代码不用变
        BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
        // 使用确实变快了,不用也可以,代码不用变
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream);
        byte[] byteArray=new byte[1024];
        int len;
        while((len=bufferedInputStream.read(byteArray))!=-1){
            System.out.println(new String(byteArray,"UTF-8"));
        }
        long endTime=System.currentTimeMillis();
        System.out.println("耗时"+(endTime-startTime)+"ms");
    }
}
  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值