翻译软件怎么实现的?我用Java教你实现私人自用翻译软件

翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第1张图片
很多人问博主:市面上很多翻译软件,他们是怎么实现的呢?
比如腾讯QQ最新版本的QQ可实现截图翻译:
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第2张图片
博主实现的软件预览:

翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第3张图片
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第4张图片
本原创软件下载地址:点击下载源码

    博主今天就来给大家讲解一下基础版本的翻译软件是如何实现的,首先申明一下,本文采用的翻译接口是由有道云,腾讯,谷歌提供的翻译接口API,基于Java语言实现图形界面化,采用Java-SWT框架快速生成自定义图形界面。使用阿里的json-jar即fast-json进行json字符串解析,使用自定义解析算法实现字符串提取,这里的算法实际上就是基础代码的重复调用减少中间环节。除此之外,博主根据网络教程,实现了读取图片,识别图片中文字从而一键翻译。文本识别jar来自腾讯AI开放平台。至此,基础的实现技术原理介绍到此结束。我们用一张mind脑图来罗列清晰我们的基本思路。翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第5张图片
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第6张图片
软件的结构图:(本软件开发采用eclispe-4.5版本,idea不支持SWT拓展)
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第7张图片
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第8张图片
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第9张图片
使用到的lib包:
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第10张图片
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第11张图片

    好了,框架图介绍到这里,我们接下来,直接上代码:(所有源代码开源,欢迎各位下载后自行尝试,有任何问题请及时在文章下方留言评论,博主会一一解答)

  1. 主窗口代码
package com.sinsy;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.wb.swt.SWTResourceManager;
import com.sinsy.fanyi.baidu.Fanyi_baidu;
import com.sinsy.fanyi.google.fanyi_google;
import com.sinsy.fanyi.tencent.fanyi_tencent;
import com.sinsy.fanyi.youdaoyun.fanyi_youdaoyun;
import com.sinsy.fntp.ClipboradUtils;
import com.sinsy.fntp.shibie.aiscan;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
public class MainWindows {
     
	protected Color themecolor;
	protected Shell shell;
	private Text shurukuang;
	private Text shuchu;
	protected int style;
	protected String imagepathString;
	protected boolean flag=false;
	protected boolean flag2=false;
	private final FormToolkit formToolkit = new FormToolkit(Display.getDefault());
	public ClipboradUtils yUtils = new ClipboradUtils();
	private String result=null;
	private boolean baidu=true;
	private boolean tengxun=false;
	private boolean youdaoyun=false;
	private boolean google=false;
	private JPanel yu= new JPanel();
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
     
		try {
     
			MainWindows window = new MainWindows();
//			MessageDialog.openInformation(null, "", "hello");
			window.open();
		} catch (Exception e) {
     
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
     
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
     
			if (!display.readAndDispatch()) {
     
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
     
//		禁用窗口最大化
		shell = new Shell(style|SWT.MIN);
		shell.setImage(SWTResourceManager.getImage(MainWindows.class, "/img/2.png"));
		shell.setSize(631, 517);
		shell.setText("鑫软翻译");
		shell.setLayout(null);
		shell.setBackground(themecolor);
//		开始写输入框文本内容
		shurukuang = new Text(shell, SWT.BORDER | SWT.V_SCROLL|SWT.MULTI|SWT.WRAP);

		shurukuang.setBounds(10, 10, 396, 189);
//		获取剪切板和手动输入两类:
//		获取剪切板输入:
		
		Button btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.setText("一键翻译文字");
		btnNewButton.setBounds(10, 205, 109, 30);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
//				从这里开始判断翻译来源 首选百度
//				GetHtmlContentUtils yUtils = new GetHtmlContentUtils();
				if(baidu==true&&tengxun==false&&youdaoyun==false&&google==false) {
     
				try {
     
					Fanyi_baidu fanyi = new Fanyi_baidu();
					 result="鑫软提示:以下翻译来自----<百度翻译>---\n"+
							 "------------------------------------------------------------\r\n" + 
								"------------------------翻译结果--------------------------\r\n"+
							 fanyi.fanyi_baidu(shurukuang.getText());
					shuchu.setText(result);
				} catch (Exception e1) {
     
					shuchu.setText("鑫软翻译提示:出错了!百度君说这种问题他也没遇见过!");
				}
				}
//				腾讯翻译
				if(tengxun==true&&youdaoyun==false&&baidu==false&&google==false) {
     
					if(new fanyi_tencent().isChinese(shurukuang.getText())) {
     
					result="鑫软提示:以下翻译来自腾讯云翻译\n"+
							"------------------------------------------------------------\r\n" + 
							"------------------------翻译结果--------------------------\r\n"+
							new fanyi_tencent().fanyi_tx_auto_to_en(shurukuang.getText());
					shuchu.setText(result);
					}else if(new fanyi_tencent().isEnglish(shurukuang.getText())) {
     
						result="鑫软提示:以下翻译来自腾讯云翻译\n"+
								"------------------------------------------------------------\r\n" + 
								"------------------------翻译结果--------------------------\r\n"+
								new fanyi_tencent().fanyi_tx_auto_to_zh(shurukuang.getText());
//						System.out.println("编码格式为:"+new encode().getEncoding(auto_to_zh(text)));
						shuchu.setText(result);
					}else {
     
						result="鑫软提示:以下翻译来自腾讯云翻译\n"+
								"------------------------------------------------------------\r\n" + 
								"------------------------翻译结果--------------------------\r\n"+
								"亲爱的小主:腾讯云翻译君有误,请重新输入!";
						
						shuchu.setText(result);
					}
			}
//			有道云翻译
			if(youdaoyun==true&&baidu==false&&tengxun==false&&google==false) {
     
				try {
     
					fanyi_youdaoyun fanyi = new fanyi_youdaoyun();
					result="鑫软提示:以下翻译来自有道云\n"+
					"------------------------------------------------------------\r\n" + 
					"------------------------翻译结果--------------------------\r\n"+
					fanyi.youdaoyun_fanyi(shurukuang.getText());
					shuchu.setText(result);
				} catch (Exception e2) {
     
					e2.printStackTrace();
					shuchu.setText("哇哦,可惜了,这么优美的词汇(句子)有道云不支持这种长句子翻译奥!推荐使用谷歌或者百度,嘿嘿!");
				}
			}
//			google翻译
			if(google==true&&youdaoyun==false&&baidu==false&&tengxun==false) {
     
				try {
     
					fanyi_google fanyi = new fanyi_google();
					if(fanyi.isEnglish(shurukuang.getText())) {
     
						fanyi.fanyi_Google(shurukuang.getText(), "zh");
						result="鑫软提示:以下翻译来谷歌翻译(已破解可以无限制使用!)\n"+
								"------------------------------------------------------------\r\n" + 
								"------------------------翻译结果--------------------------\r\n"+
								fanyi.fanyi_Google(shurukuang.getText(), "zh");
								shuchu.setText(result);
					}else if(fanyi.isChinese(shurukuang.getText())) {
     
						fanyi.fanyi_Google(shurukuang.getText(), "en");
						result="鑫软提示:以下翻译来谷歌翻译(已破解可以无限制使用!)\n"+
								"------------------------------------------------------------\r\n" + 
								"------------------------翻译结果--------------------------\r\n"+
								fanyi.fanyi_Google(shurukuang.getText(), "en");
								shuchu.setText(result);
					}
				} catch (Exception e2) {
     
					shuchu.setText("鑫软翻译提示:长文本翻译请使用百度(推荐)");
				}
			}
		}
	});
		shuchu = new Text(shell, SWT.BORDER | SWT.V_SCROLL|SWT.MULTI|SWT.WRAP);
		shuchu.setBounds(10, 241, 396, 199);
		
		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);
		
		MenuItem menuItem = new MenuItem(menu, SWT.NONE);
		menuItem.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				new about().open();
			}
		});
		menuItem.setText("关于软件");
		
		MenuItem menuItem_1 = new MenuItem(menu, SWT.NONE);
		menuItem_1.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				new chat().open();
			}
		});
		menuItem_1.setText("联系作者");
		
		Button btnNewButton_1 = new Button(shell, SWT.NONE);

		btnNewButton_1.addSelectionListener(new SelectionAdapter(){
     
			public void widgetSelected(SelectionEvent e){
     
//				MessageDialog.openInformation(null, "", "hello");
				if(flag==true) {
     
					aiscan yu = new aiscan();
					shurukuang.setText(yu.ceshi());;
				}else {
     
					JOptionPane.showMessageDialog(yu, "请在截图后勾选切换文字识别!", "鑫软翻译提醒",JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		
		btnNewButton_1.setBounds(297, 205, 109, 30);
		btnNewButton_1.setText("一键识别文字");
		
		Button xuanfu = new Button(shell, SWT.CHECK);
		xuanfu.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
//				全局悬浮
				if(xuanfu.getSelection()) {
     
					style =16384;	
					OS . SetWindowPos (shell.handle,OS.HWND_TOPMOST,396,189,604 ,521,SWT.NULL) ;
				}
				else {
     
					style = 32;
					OS . SetWindowPos (shell.handle,OS.HWND_NOTOPMOST,396,189 ,604 ,521,SWT.NULL);
				}
			}
		});
		xuanfu.setBounds(412, 13, 151, 20);
		xuanfu.setText("是否开启全局悬浮");
		
		Button switchmode = new Button(shell, SWT.CHECK);
		switchmode.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
//				此处切换模式
				if(switchmode.getSelection()) {
     
					flag=true;
				}else {
     
					flag=false;
				}
			}
		});
		switchmode.setBounds(412, 55, 151, 20);
		switchmode.setText("\u5207\u6362\u4E3A\u6587\u5B57\u8BC6\u522B");
		
		Button button_1 = new Button(shell, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				shurukuang.setText("");
			}
		});
		button_1.setBounds(153, 205, 109, 30);
		button_1.setText("一键清空输入");
		
		
		
		
		
		Combo combo = new Combo(shell, SWT.NONE);
		combo.setItems(new String[] {
     "百度翻译(默认推荐)", "腾讯翻译(单词)", "有道翻译(单词/词组)", "谷歌翻译(通用已破解)"});
		combo.setBounds(412, 205, 180, 28);
		combo.setText("请自助选择翻译来源");
//		使用键盘上下左右控制选择
		combo.addKeyListener(new KeyAdapter() {
     
			public void keyPressed(KeyEvent e){
     
				//如果单击了向左的箭头按键,则选中上一个选项
				if (e.keyCode == SWT .ARROW_LEFT)
				combo.select(combo.getSelectionIndex() - 1); 
				//如果单击了向右的箭头按键,则选中下一个选项
				else if (e.keyCode == SWT.ARROW_RIGHT)
				combo.select(combo.getSelectionIndex() + 1);
		}
		});
		combo.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				
			System.out.println("组合框"+combo.getSelectionIndex()+"被点击,被点击的选项是:"+combo.getItem(combo.getSelectionIndex()));
//			------------------------------百度翻译------------------------------------
//			Fanyi_baidu fanyi = new Fanyi_baidu();
//				 result=fanyi.fanyi_baidu(shurukuang.getText());
//			切换为百度翻译
			if(combo.getSelectionIndex()==0&&combo.getSelectionIndex()!=1&&combo.getSelectionIndex()!=2&&combo.getSelectionIndex()!=3) {
     
				baidu=true;
				tengxun=false;
				youdaoyun=false;
				google=false;
//				切换为腾讯翻译
			}else if(combo.getSelectionIndex()==1&&combo.getSelectionIndex()!=0&&combo.getSelectionIndex()!=2&&combo.getSelectionIndex()!=3) {
     
				tengxun=true;
				baidu=false;
				youdaoyun=false;
				google=false;
				}else if(combo.getSelectionIndex()==2&&combo.getSelectionIndex()!=0&&combo.getSelectionIndex()!=1&&combo.getSelectionIndex()!=3) {
     
					youdaoyun=true;
					baidu=false;
					tengxun=false;
					google=false;
				}else if(combo.getSelectionIndex()!=0&&combo.getSelectionIndex()!=1&&combo.getSelectionIndex()!=2&&combo.getSelectionIndex()==3) {
     
					google=true;
					baidu=false;
					tengxun=false;
					youdaoyun=false;
				}
			}
		});
		
		
		
		
		
		Label label = new Label(shell, SWT.NONE);
		label.setBackground(SWTResourceManager.getColor(240, 240, 240));
		label.setBounds(412, 400, 176, 20);
		formToolkit.adapt(label, true, true);
		label.setText("  \u626B\u63CF\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u6253\u8D4F\u4F5C\u8005");
		
		Link link = new Link(shell, SWT.NONE);
		link.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				try {
     
					Runtime.getRuntime().exec(
							"rundll32 url.dll,FileProtocolHandler http://www.sinsy.club");
				} catch (IOException e1) {
     
					
					e1.printStackTrace();
				}
			}
		});
		link.setBackground(SWTResourceManager.getColor(240, 240, 240));
		link.setBounds(444, 420, 119, 20);
		formToolkit.adapt(link, true, true);
		link.setText("www.sinsy.club");
		
		Label lableforimg = new Label(shell, SWT.NONE);
		lableforimg.setBounds(426, 244, 150, 150);
		formToolkit.adapt(lableforimg, true, true);
		lableforimg.setText("");
		lableforimg.setImage(SWTResourceManager.getImage("F:\\Program Files\\eclipse ee\\resources\\new task one\\\u946B\u8F6F\u7FFB\u8BD1\\src\\img\\c.png"));
		
		Button readClib = new Button(shell, SWT.NONE);
		readClib.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
					
//					如果是图片,则保存在本地后选择复制到剪切板但是不会复制到输入框
//					savaimage yuSavaimage = new savaimage();
//					shurukuang.setText(yuSavaimage.getSysClipboardText());
//					imagepathString = yuSavaimage.getpath();   
				if(!flag2) {
     
					  try {
     
						shurukuang.setText(shurukuang.getText()+yUtils.getClipboardText());
					} catch (Exception c) {
     
						// 
						c.printStackTrace();
					}
				}


			}
		});
		readClib.setBounds(412, 169, 180, 30);
		formToolkit.adapt(readClib, true, true);
		readClib.setText("\u8BFB\u53D6\u526A\u5207\u677F\u5185\u5BB9");
		
		Button setempty = new Button(shell, SWT.NONE);
		setempty.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				 yUtils.setempty();
			}
		});
		setempty.setBackground(SWTResourceManager.getColor(169, 169, 169));
		setempty.setBounds(412, 135, 180, 30);
		formToolkit.adapt(setempty, true, true);
		setempty.setText("\u6E05\u7A7A\u526A\u5207\u677F");
		
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBackground(SWTResourceManager.getColor(192, 192, 192));
		lblNewLabel.setBounds(412, 99, 180, 20);
		formToolkit.adapt(lblNewLabel, true, true);
		lblNewLabel.setText("\u611F\u8C22\u60A8\u4F7F\u7528SINSY\u5FEB\u6377\u7FFB\u8BD1");

	}
//	public String auto_to_zh(String text) {
     
//     return new fanyi_tencent(). fanyi_tx_auto_to_zh(text);
//	}
//	public String auto_to_en() {
     
//		encode en= new encode();
//		System.out.println("输入框的文字编码格式是:"+en.getEncoding(shurukuang.getText()));
//		en.translate(shurukuang.getText(),"GB2312","utf-8");
//     	System.out.println("转换后文字编码格式是:"+en.getEncoding(en.translate(shurukuang.getText(),"GB2312","utf-8")));
//     	System.out.println(en.translate(shurukuang.getText(),"GB2312","gbk"));
//		return new fanyi_tencent().fanyi_tx_auto_to_en(en.translate(shurukuang.getText(),"GB2312","gb2312"));
//	}
}

与作者交流界面代码:

package com.sinsy;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Label;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Link;

public class chat {
     
//shell进程的主进程:创建一个shell对象
	protected Shell shell;
/**	main方法()调用,用void java.lang.Throwable.printStackTrace()
 * 打出异常
 * @param fntp
 */
	public static void main(String[] args) {
     
		try {
     
			chat window = new chat();
			window.open();
		} catch (Exception e) {
     
			e.printStackTrace();
		}
		
	}


	/**
	 * Open the window.问题bug出在这里:
	 */
	public synchronized void open() {
     
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
     
			if (!display.readAndDispatch()) {
     
				display.sleep();
			}
		}
	}
//	处理异常问题:
//	public void start() {
     
//        Display.getDefault().asyncExec(new Runnable() {
     
//            @Override
//            public void run() {
     
//               createContents();
//            }
//        });
//    }

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
     

//		shell = new Shell(new Display(), SWT.MIN);
        shell = new Shell(SWT.CLOSE);              
		shell.setImage(SWTResourceManager.getImage(chat.class, "/img/1.png"));
		shell.setSize(466, 363);
		shell.setText("\u4E0E\u4F5C\u8005\u4EA4\u6D41");
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setImage(SWTResourceManager.getImage(chat.class, "/img/2.png"));
		lblNewLabel.setBounds(133, 21, 168, 173);
		Link link = new Link(shell, SWT.NONE);
		link.setBounds(167, 203, 131, 31);
		link.setText("\u70B9\u51FB\u6B64\u5904\u8054\u7CFB\u4F5C\u8005");
		
		Label label = new Label(shell, SWT.NONE);
		label.setBounds(31, 238, 403, 20);
		label.setText("\u66F4\u591A\u5B9E\u7528\u5DE5\u5177\u8BF7\u5173\u6CE8\u946B\u8F6F\u5DE5\u4F5C\u5BA4\u5B98\u7F51\uFF0C\u5173\u6CE8\u5FAE\u7C73\u5DE5\u4F5C\u5BA4\u5B98\u7F51");
		
		Label label_1 = new Label(shell, SWT.NONE);
		label_1.setBounds(91, 264, 314, 20);
		label_1.setText("\u6B22\u8FCE\u5404\u4F4D\u5F00\u53D1\u8005\u4EE5\u53CA\u7528\u6237\u4E3A\u6211\u4EEC\u63D0\u4F9B\u5B9D\u8D35\u5EFA\u8BAE");
		link.addSelectionListener(new SelectionAdapter(){
     
	public void widgetSelected(SelectionEvent event){
     
		try {
     
			Runtime.getRuntime().exec(
			"rundll32 url.dll,FileProtocolHandler http://wpa.qq.com/msgrd?v=3&uin=358566760&site=qq&menu=yes");
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}
});
		
	}

}

关于软件的代码:

package com.sinsy;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class about {
     

	protected Shell shell;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
     
		try {
     
			about window = new about();
			window.open();
		} catch (Exception e) {
     
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Open the window.
	 */
	public void open() {
     
		Display display = Display.getDefault();
		 Display.getDefault().syncExec(new Runnable() {
     
			    public void run() {
     
			    	createContents();
			    }
			    }); 
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
     
			if (!display.readAndDispatch()) {
     
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 * @wbp.parser.entryPoint
	 */
	protected void createContents() {
     
		shell = new Shell(SWT.MIN);
		shell.setImage(SWTResourceManager.getImage(about.class, "/img/1.png"));
		shell.setSize(406, 378);
		shell.setText("\u5173\u4E8E\u672C\u8F6F\u4EF6");
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(147, 222, 102, 20);
		lblNewLabel.setText("\u946B\u8F6F\u7FFB\u8BD1beta");
		Label lblNewLabel_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1.setImage(SWTResourceManager.getImage("F:\\Program Files\\eclipse ee\\resources\\new task one\\鑫软翻译\\src\\img\\logo.png"));
		lblNewLabel_1.setBounds(-73, -79, 420, 303);
		
		Label label = new Label(shell, SWT.NONE);
		label.setBounds(36, 302, 339, 20);
		label.setText("\u7834\u89E3\u63A5\u53E3\u4EC5\u4F9B\u5B66\u4E60\u4EA4\u6D41\uFF0C\u5176\u4ED6\u63A5\u53E3\u8BBF\u95EE\u53D7\u9650\u8BF7\u8C05\u89E3!");
		
		Link link = new Link(shell, SWT.NONE);
		link.setBounds(36, 276, 361, 20);
		link.setText("\u5144\u5F1F\u56E2\u961F\uFF1A\u5FAE\u7C73\u5DE5\u4F5C\u5BA4www.micronnetwork.com");
		
		Link link_1 = new Link(shell, SWT.NONE);
		link_1.addSelectionListener(new SelectionAdapter() {
     
			@Override
			public void widgetSelected(SelectionEvent e) {
     
				
			}
		});
		link_1.setBounds(94, 250, 264, 20);
		link_1.setText("\u946B\u8F6F\u5DE5\u4F5C\u5BA4\u5B98\u7F51:www.sinsy.club");

	}
}

重磅的来了:百度的API使用:

1.百度翻译核心代码

package com.sinsy.fanyi.baidu;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Fanyi_baidu {
     

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "您的APPID";
    private static final String SECURITY_KEY = "APPKEY";

//    public static void main(String[] args) {
     
    public  String fanyi_baidu(String string) {
     
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);

        String query = string;
        String str = api.getTransResult(query, "auto", "auto"); //中文翻译英文
//        System.out.println(str);   //输出结果即json字段
        JsonObject  jsonObj = (JsonObject)new JsonParser().parse(str);//解析json字段
        String res = jsonObj.get("trans_result").toString();//获取json字段中的 result字段,因为result字段本身即是�?个json数组字段,所以要进一步解�?
        JsonArray  js = new JsonParser().parse(res).getAsJsonArray();//解析json数组字段
        jsonObj = (JsonObject)js.get(0);//result数组中只有一个元素,�?以直接取第一个元�?
//        ssSystem.out.println(jsonObj.get("dst").getAsString());//得到dst字段,即译文,并输出
//        System.out.println(api.getTransResult(query, "auto", "en"));
		return jsonObj.get("dst").getAsString();
    }
//public static void main(String[] args) {
     
//	System.out.println(fanyi_baidu("System out println(api.getTransResult(query, \"auto\", \"en\"));"));
//}
}

2.Http访问代码:

package com.sinsy.fanyi.baidu;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

class HttpGet {
     
    protected static final int SOCKET_TIMEOUT = 10000; // 10S
    protected static final String GET = "GET";

    public static String get(String host, Map<String, String> params) {
     
        try {
     
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] {
      myX509TrustManager }, null);

            String sendUrl = getUrlWithQueryString(host, params);

            // System.out.println("URL:" + sendUrl);

            URL uri = new URL(sendUrl); // 创建URL对象
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            if (conn instanceof HttpsURLConnection) {
     
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }

            conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
            conn.setRequestMethod(GET);
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
     
                System.out.println("Http错误码:" + statusCode);
            }

            // 读取服务器的数据
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
     
                builder.append(line);
            }

            String text = builder.toString();

            close(br); // 关闭数据�?
            close(is); // 关闭数据�?
            conn.disconnect(); // 断开连接

            return text;
        } catch (MalformedURLException e) {
     
            e.printStackTrace();
        } catch (IOException e) {
     
            e.printStackTrace();
        } catch (KeyManagementException e) {
     
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
     
            e.printStackTrace();
        }

        return null;
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) {
     
        if (params == null) {
     
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
     
            builder.append("&");
        } else {
     
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
     
            String value = params.get(key);
            if (value == null) {
      // 过滤空的key
                continue;
            }

            if (i != 0) {
     
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    protected static void close(Closeable closeable) {
     
        if (closeable != null) {
     
            try {
     
                closeable.close();
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     * 
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原�?
     */
    public static String encode(String input) {
     
        if (input == null) {
     
            return "";
        }

        try {
     
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        }

        return input;
    }

    private static TrustManager myX509TrustManager = new X509TrustManager() {
     

        @Override
        public X509Certificate[] getAcceptedIssuers() {
     
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
     
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
     
        }
    };

}

3.MD5代码:

package com.sinsy.fanyi.baidu;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5编码相关的类
 * 
 * @author wangjingtao
 * 
 */
public class MD5 {
     
    // 首先初始化一个字符数组,用来存放每个16进制字符
    private static final char[] hexDigits = {
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * 获得�?个字符串的MD5�?
     * 
     * @param input 输入的字符串
     * @return 输入字符串的MD5�?
     * 
     */
    public static String md5(String input) {
     
        if (input == null)
            return null;

        try {
     
            // 拿到�?个MD5转换器(如果想要SHA1参数换成”SHA1”)
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数�?
            byte[] inputByteArray = null;
			try {
     
				inputByteArray = input.getBytes("utf-8");
			} catch (UnsupportedEncodingException e) {
     
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            // inputByteArray是输入字符串转换得到的字节数�?
            messageDigest.update(inputByteArray);
            // 转换并返回结果,也是字节数组,包�?16个元�?
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
     
            return null;
        }
    }
    public static String md5(File file) {
     
        try {
     
            if (!file.isFile()) {
     
                System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文�?");
                return null;
            }

            FileInputStream in = new FileInputStream(file);

            String result = md5(in);

            in.close();

            return result;

        } catch (FileNotFoundException e) {
     
            e.printStackTrace();
        } catch (IOException e) {
     
            e.printStackTrace();
        }

        return null;
    }

    public static String md5(InputStream in) {
     

        try {
     
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
     
                messagedigest.update(buffer, 0, read);
            }

            in.close();

            String result = byteArrayToHex(messagedigest.digest());

            return result;
        } catch (NoSuchAlgorithmException e) {
     
            e.printStackTrace();
        } catch (FileNotFoundException e) {
     
            e.printStackTrace();
        } catch (IOException e) {
     
            e.printStackTrace();
        }

        return null;
    }

    private static String byteArrayToHex(byte[] byteArray) {
     
        // new�?个字符数组,这个就是用来组成结果字符串的(解释一下:�?个byte是八位二进制,也就是2位十六进制字符(2�?8次方等于16�?2次方))
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍历字节数组,�?�过位运算(位运算效率高),转换成字符放到字符数组中�?
        int index = 0;
        for (byte b : byteArray) {
     
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }

        // 字符数组组合成字符串返回
        return new String(resultCharArray);

    }

}

4.翻译的API配置核心:

package com.sinsy.fanyi.baidu;

import java.util.HashMap;
import java.util.Map;

public class TransApi {
     
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    public TransApi(String appid, String securityKey) {
     
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getTransResult(String query, String from, String to) {
     
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
     
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机�?
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
}
}

谷歌翻译API使用:

1.谷歌Http服务代码:

package com.sinsy.fanyi.google;

import java.net.InetSocketAddress;
import java.net.Proxy;

public class Browser {
     

    public Proxy proxy;
    public String url;

    public String getUrl() {
     
        return this.url;
    }

    public void setUrl(String url) {
     
        this.url = url;
    }

    public Proxy getProxy() {
     
        return this.proxy;
    }

    public void setProxy(String ip, Integer port) {
     
        this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port.intValue()));
    }

    public String executeGet()
            throws Exception {
     
        String result;
        if (this.proxy != null)
            result = HttpClientUtil.doGetWithProxy(this.url, this.proxy);
        else {
     
            result = HttpClientUtil.doGet(this.url);
        }

        return result;
    }
}

2.最终json处理实现代码:

package com.sinsy.fanyi.google;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class fanyi_google {
     
//	public static void main(String[] args) throws Exception {
     
//		   // 普通方式初始化
//        GoogleApi googleApi = new GoogleApi();
//        // 通过代理
        GoogleApi googleApi = new GoogleApi("122.224.227.202", 3128);
//        String result = googleApi.translate("哈哈",  "auto");
//        String result2= googleApi.translate("Your mother die",  "auto");
//        System.out.println(result);
//        System.out.println(result2);
//	Your mother die
//	Your mother die
//	}
	 public String fanyi_Google(String str,String target_en_zh) throws Exception {
     
	        // 普通方式初始化
	        GoogleApi googleApi = new GoogleApi();
	        // 通过代理
//	        GoogleApi googleApi = new GoogleApi("122.224.227.202", 3128);
	        String result = googleApi.translate(str,  target_en_zh);
//	        System.out.println(result);
			return result;
	    }
	   public  boolean isEnglish(String charaString){
     
//		   ^[[A-Za-z]|\\s]+$
//	      return charaString.matches("^[a-zA-Z]*");
		   return charaString.matches("^[[A-Za-z]|\\s]+$");
	    }
	//   是否是中文判断(正则表达式)
	  public  boolean isChinese(String str){
     
	      String regEx = "[\\u4e00-\\u9fa5]+";
	      Pattern p = Pattern.compile(regEx);
	      Matcher m = p.matcher(str);
	     if(m.find())
	       return true;
	     else
	       return false;
	   }
}

3.谷歌接口API代码

package com.sinsy.fanyi.google;
import com.alibaba.fastjson.JSONArray;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLEncoder;

public class GoogleApi {
     

    private static final String PATH = "./gettk.js";

    static ScriptEngine engine = null;

    private Browser browser = null;

    static {
     
        ScriptEngineManager maneger = new ScriptEngineManager();
        engine = maneger.getEngineByName("javascript");
        FileInputStream fileInputStream = null;
        Reader scriptReader = null;

        try {
     
            scriptReader = new InputStreamReader(GoogleApi.class.getResourceAsStream(PATH), "utf-8");
            engine.eval(scriptReader);
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            if (fileInputStream != null) {
     
                try {
     
                    fileInputStream.close();
                } catch (IOException e) {
     
                    e.printStackTrace();
                }
            }
            if (scriptReader != null) {
     
                try {
     
                    scriptReader.close();
                } catch (IOException e) {
     
                    e.printStackTrace();
                }
            }
        }
    }

    public GoogleApi() {
     
        this.browser = new Browser();
    }

    public GoogleApi(String ip, Integer port) {
     
        this.browser = new Browser();
        this.browser.setProxy(ip, port);
    }

    public String getTKK() throws Exception {
     
        browser.setUrl("https://translate.google.cn/");

        try {
     
            String result = browser.executeGet();
            if (StringUtils.isNotBlank(result)) {
     
                if (result.indexOf("tkk") > -1) {
     
                    String matchString = RegularUtil.findMatchString(result, "tkk:.*?',");
                    String tkk = matchString.substring(5, matchString.length() - 2);
                    return tkk;
                }
            }
        } catch (Exception e) {
     
            throw new RuntimeException("获取 tkk 出错");
        }

        return null;
    }

    public static String getTK(String word, String tkk) {
     
        String result = null;

        try {
     
            if (engine instanceof Invocable) {
     
                Invocable invocable = (Invocable) engine;
                result = (String) invocable.invokeFunction("tk", new Object[]{
     word, tkk});
            }
        } catch (Exception e) {
     
            throw new RuntimeException("获取 tk 出错");
        }

        return result;
    }

    public String translate(String word, String from, String to) throws Exception {
     
        if (StringUtils.isBlank(word)) {
     
            return null;
        }

        String tkk = getTKK();

        if (StringUtils.isBlank(tkk)) {
     
            throw new RuntimeException("无法获取 tkk");
        }

        String tk = getTK(word, tkk);

        try {
     
            word = URLEncoder.encode(word, "UTF-8");
        } catch (Exception e) {
     
            e.printStackTrace();
        }

        StringBuffer buffer = new StringBuffer("https://translate.google.cn/translate_a/single?client=t");

        if (StringUtils.isBlank(from)) {
     
            from = "auto";
        }

        buffer.append("&sl=" + from);
        buffer.append("&tl=" + to);
        buffer.append("&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&kc=0");
        buffer.append("&tk=" + tk);
        buffer.append("&q=" + word);
        browser.setUrl(buffer.toString());

        try {
     
            String result = browser.executeGet();
            JSONArray array = (JSONArray) JSONArray.parse(result);
            JSONArray rArray = array.getJSONArray(0);
            StringBuffer rBuffer = new StringBuffer();
            for (int i = 0; i < rArray.size(); i++) {
     
                String r = rArray.getJSONArray(i).getString(0);
                if (StringUtils.isNotBlank(r)) {
     
                    rBuffer.append(r);
                }
            }

            return rBuffer.toString();
        } catch (Exception e) {
     
            throw new RuntimeException("结果集解析出错");
        }
    }

    /**
     * 自动检测源语言
     *
     * @param word 要翻译的词
     * @param to   翻译的目标语言, 参考谷歌接口
     * @return
     * @throws Exception
     */
    public String translate(String word, String to) throws Exception {
     
        return translate(word, null, to);
    }
}

4.谷歌工具类:

package com.sinsy.fanyi.google;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.Proxy;
import java.net.URI;
import java.util.Map;

public class HttpClientUtil {
     

    public static final int SO_TIMEOUT_MS = 8000;
    public static final int CONNECTION_TIMEOUT_MS = 1000;

    public static String doGet(String url, Map<String, String> param) {
     
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
     
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
     
                for (String key : param.keySet()) {
     
                    builder.addParameter(key, (String) param.get(key));
                }
            }
            URI uri = builder.build();

            HttpGet httpGet = new HttpGet(uri);

            response = httpclient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200)
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            try {
     
                if (response != null) {
     
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url, Map<String, String> param, Proxy proxy) throws Exception {
     
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
     
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
     
                for (String key : param.keySet()) {
     
                    builder.addParameter(key, (String) param.get(key));
                }
            }
            URI uri = builder.build();

            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(buildRequestConfig(proxy));

            response = httpclient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200)
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
     
            throw e;
        } finally {
     
            try {
     
                if (response != null) {
     
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGetWithProxy(String url, Proxy proxy) throws Exception {
     
        return doGet(url, null, proxy);
    }

    public static String doGet(String url) {
     
        return doGet(url, null);
    }

    public static RequestConfig buildRequestConfig(Proxy proxy) {
     
        String address = proxy.address().toString();
        String[] addressArr = address.replace("/", "").split(":");
        String ip = addressArr[0].trim();
        String host = addressArr[1].trim();

        if ((proxy != null) && (!(StringUtils.isBlank(ip))) && (!(StringUtils.isBlank(host)))) {
     
            HttpHost httpHost = new HttpHost(ip, Integer.parseInt(host));
            RequestConfig requestConfig = RequestConfig.custom().setProxy(httpHost)
                    .setSocketTimeout(SO_TIMEOUT_MS)
                    .setConnectTimeout(CONNECTION_TIMEOUT_MS).build();
            return requestConfig;
        }

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SO_TIMEOUT_MS)
                .setConnectTimeout(CONNECTION_TIMEOUT_MS).build();
        return requestConfig;
    }
}

5.谷歌正则工具类(CSDN网友提供的开源代码:作者:huangwenjun)

package com.sinsy.fanyi.google;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularUtil {
     

    public static String extractByStartAndEnd(String str, String startStr, String endStr) {
     
        String regEx = startStr + ".*?"+endStr;
        String group = findMatchString(str, regEx);
        String trim = group.replace(startStr, "").replace(endStr, "").trim();
        return trim(trim);
    }

    public static String findMatchString(String str, String regEx) {
     
        try {
     
            // 编译正则表达式
            Pattern pattern = Pattern.compile(regEx);
            // 忽略大小写的写法
            Matcher matcher = pattern.matcher(str);
            // 字符串是否与正则表达式相匹配
            return findFristGroup(matcher);
        } catch (Exception e) {
     
            e.printStackTrace();
        }

        return null;
    }

    private static String findFristGroup(Matcher matcher) {
     
        matcher.find();
        return matcher.group(0);
    }

    /**
     * 去除字符串中所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
     * @param s
     * @return
     */
    public static String removeAllBlank(String s){
     
        String result = "";
        if(null!=s && !"".equals(s)){
     
            result = s.replaceAll("[ *| *| *|//s*]*", "");
        }
        return result;
    }

    /**
     * 去除字符串中头部和尾部所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
     * @param s
     * @return
     */
    public static String trim(String s){
     
        String result = "";
        if(null!=s && !"".equals(s)){
     
            result = s.replaceAll("^[ *| *| *|//s*]*", "").replaceAll("[ *| *| *|//s*]*$", "");
        }
        return result;
    }
}

7.谷歌字符串自定义方法:

package com.sinsy.fanyi.google;

/**
fntp
 **/
public class StringUtils {
     

    public static boolean isBlank(String string) {
     
        if (string == null || "".equals(string.trim())) {
     
            return true;
        }

        return false;
    }

    public static boolean isNotBlank(String string) {
     
        return !isBlank(string);
    }
}

8.工具js

var b = function (a, b) {
     
	for (var d = 0; d < b.length - 2; d += 3) {
     
		var c = b.charAt(d + 2),
			c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
			c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
		a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
	}
	return a
}

var tk =  function (a,TKK) {
     
	for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
     
		var c = a.charCodeAt(f);
		128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
	}
	a = h;
	for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
	a = b(a, "+-3^+b+-f");
	a ^= Number(e[1]) || 0;
	0 > a && (a = (a & 2147483647) + 2147483648);
	a %= 1E6;
	return a.toString() + "." + (a ^ h)
}

腾讯翻译代码:

1.基础实现类:


package com.sinsy.fanyi.tencent;

import java.io.UnsupportedEncodingException;

public class encode {
     
	 public String translate(String str, String srcEncode,String dstEncode) {
     
		      String tempStr = "";
		    try {
     
		         tempStr = new String(str.getBytes(srcEncode),dstEncode);
		     } catch (UnsupportedEncodingException e) {
     
		         // TODO Auto-generated catch block
		         e.printStackTrace();
		     }
		     return tempStr;
		}
	 public  String getEncoding(String str) {
     
		 String encode = "GB2312";
		 try {
     
		 if (str.equals(new String(str.getBytes(encode), encode))) {
     
		 String s = encode;
		 return s;
		 }
		 } catch (Exception exception) {
     
		 }
		 encode = "ISO-8859-1";
		 try {
     
		 if (str.equals(new String(str.getBytes(encode), encode))) {
     
		 String s1 = encode;
		 return s1;
		 }
		 } catch (Exception exception1) {
     
		 }
		 encode = "UTF-8";
		 try {
     
		 if (str.equals(new String(str.getBytes(encode), encode))) {
     
		 String s2 = encode;
		 return s2;
		 }
		 } catch (Exception exception2) {
     
		 }
		 encode = "GBK";
		 try {
     
		 if (str.equals(new String(str.getBytes(encode), encode))) {
     
		 String s3 = encode;
		 return s3;
		 }
		 } catch (Exception exception3) {
     
		 }
		 return "";
		 }
}

2.实现方法

package com.sinsy.fanyi.tencent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.widgets.Text;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sinsy.MainWindows;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
public class fanyi_tencent
{
     
//	//测试判断中英文:
//	   public static void main(String[] args){
     
//		if(new fanyi_tencent().isEnglish("Hello I am pitty")) {
     
//			System.out.println(new fanyi_tencent().fanyi_tx_auto_to_zh("you are a boy"));
//		}
//		if(new fanyi_tencent().isChinese("梦想并非都是和遥不可及")) {
     
//			System.out.println(new fanyi_tencent().fanyi_tx_auto_to_en("梦想并非都是和遥不可及"));
//		}
//	}
//	public String result_zh="";
//	public String result_EN="";
//	 public fanyi_tencent(Text text) {
     
//			if(isEnglish(text.getText())) {
     
//			result_EN+=fanyi_tx_auto_to_zh(text.getText());
//		}
//		if(isChinese(text.getText())) {
     
//			result_zh+=fanyi_tx_auto_to_en(text.getText());
//		}
//	 }
//	测试方法被我屏蔽了	
//    public static void main(String [] args) {
     

//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("tmt.tencentcloudapi.com");
//
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//            
//            TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
//            
//            String params = "{\"SourceText\":\"你好!\",\"Source\":\"auto\",\"Target\":\"en\",\"ProjectId\":1183364}";
//            TextTranslateRequest req = TextTranslateRequest.fromJsonString(params, TextTranslateRequest.class);
//            
//            TextTranslateResponse resp = client.TextTranslate(req);
//            
//            System.out.println(TextTranslateRequest.toJsonString(resp));
            测试中英文互译
            测试第一个英文:
//            System.out.println("梦想并非都是遥不可及!"+"调用腾讯翻译(auto--en)结果为:"
//            			+new fanyi_tencent().fanyi_tx_auto_to_en("梦想并非都是遥不可及!"));
//            System.out.println("I love you"+"调用腾讯翻译(auto--zh)结果为:"
//        			+new fanyi_tencent().fanyi_tx_auto_to_zh("I love you"));
//        } catch (TencentCloudSDKException e) {
     
//                System.out.println(e.toString());
//        }
//
//    }
	 public static void main(String[] args) {
     
		fanyi_tencent yu= new fanyi_tencent();
		System.out.println(yu.fanyi_tx_auto_to_en("我不知道为什么腾讯云的产品会出错"));
	}
//    这里是中译英
	 public  String fanyi_tx_auto_to_en(String str) {
     
	    	String result = null;
//	    	System.out.println("腾讯翻译中文译英文接收到的对象是:"+str);
	        try{
     
	            Credential cred = new Credential("您的APPID", "您的APPKEY");
	            HttpProfile httpProfile = new HttpProfile();
	            httpProfile.setEndpoint("tmt.tencentcloudapi.com");
	            ClientProfile clientProfile = new ClientProfile();
	            clientProfile.setHttpProfile(httpProfile);
	            TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
	            String params = "{\"SourceText\":\""+str+"\",\"Source\":\"auto\",\"Target\":\"en\",\"ProjectId\":1183364}";
	            TextTranslateRequest req = TextTranslateRequest.fromJsonString(params, TextTranslateRequest.class);
	            TextTranslateResponse resp = client.TextTranslate(req);
//	            创建一个json对象
//	         解析json
	            String json_result = TextTranslateRequest.toJsonString(resp);
	            System.out.println("返回的json对象的值是:"+ json_result );
//	           创建对象
	            JsonObject  jsonObj = (JsonObject)new JsonParser().parse(json_result);
	            String res = jsonObj.get("TargetText").toString();
	           result = res.replaceAll("\"", "");
	           System.out.println("中文翻译成英文的结果是:"+result);
	        } catch (TencentCloudSDKException e) {
     
	                System.out.println(e.toString());
	        }
	        return result;
	    }
//   这里是英文到中文
   public  String fanyi_tx_auto_to_zh(String str) {
     
   	String result = null;
       try{
     
           Credential cred = new Credential("您的APPID", "您的APPKEY");
           HttpProfile httpProfile = new HttpProfile();
           httpProfile.setEndpoint("tmt.tencentcloudapi.com");
           ClientProfile clientProfile = new ClientProfile();
           clientProfile.setHttpProfile(httpProfile);
           TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
           String params = "{\"SourceText\":\""+str+"\",\"Source\":\"auto\",\"Target\":\"zh\",\"ProjectId\":1183364}";
           TextTranslateRequest req = TextTranslateRequest.fromJsonString(params, TextTranslateRequest.class);
           TextTranslateResponse resp = client.TextTranslate(req);
//           创建一个json对象
//        解析json
           String json_result = TextTranslateRequest.toJsonString(resp);
//          创建对象
           JsonObject  jsonObj = (JsonObject)new JsonParser().parse(json_result);
           String res = jsonObj.get("TargetText").toString();
        result = res.replaceAll("\"", "");
       } catch (TencentCloudSDKException e) {
     
               System.out.println(e.toString());
       }
       return result;
   }
/**
* author fntp 
* 腾讯大大不支持互译,我自己写的判断
*/
 /**
  * isenglish判断
  * @param c
  * @return
  */
  public  boolean isEnglish(String charaString){
     
//	   ^[[A-Za-z]|\\s]+$
//     return charaString.matches("^[a-zA-Z]*");
	   return charaString.matches("^[[A-Za-z]|\\s]+$");
   }
//  是否是中文判断(正则表达式)
 public  boolean isChinese(String str){
     
     String regEx = "[\\u4e00-\\u9fa5]+";
     Pattern p = Pattern.compile(regEx);
     Matcher m = p.matcher(str);
    if(m.find())
      return true;
    else
      return false;
  }
//private String zh_to_en(String str) {
     
// String result = "";
// try{
     
//     Credential cred = new 
//     HttpProfile httpProfile = new HttpProfile();
//     httpProfile.setEndpoint("tmt.tencentcloudapi.com");
//     ClientProfile clientProfile = new ClientProfile();
//     clientProfile.setHttpProfile(httpProfile);
//     TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
//     String params = "{\"SourceText\":\""+str+"\",\"Source\":\"zh\",\"Target\":\"en\",\"ProjectId\":1183364}";
//     TextTranslateRequest req = TextTranslateRequest.fromJsonString(params, TextTranslateRequest.class);
//     TextTranslateResponse resp = client.TextTranslate(req);
//     String json_result = TextTranslateRequest.toJsonString(resp);
//     System.out.println("返回的json对象的值是:"+ json_result );
    创建对象
//     JsonObject  jsonObj = (JsonObject)new JsonParser().parse(json_result);
//     String res = jsonObj.get("TargetText").toString();
//    result = res.replaceAll("\"", "");
//    System.out.println("现在中文翻译成英文的结果是:"+result);
// } catch (TencentCloudSDKException e) {
     
//         System.out.println(e.toString());
// }
// return result;
//
//}
}

有道云代码:

1.有道云核心代码:

package com.sinsy.fanyi.youdaoyun;
//应用ID:61049bb82284c382
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class fanyi_youdaoyun {
     

    private static Logger logger = LoggerFactory.getLogger(fanyi_youdaoyun.class);

    private static final String YOUDAO_URL = "https://openapi.youdao.com/api";

    private static final String APP_KEY = "您的APPKEY";

    private static final String APP_SECRET = "您的APP密码";
    
    public static  String thefirst_str="";
//    public static void main(String[] args) {
     
//		try {
     
//			fanyi_youdaoyun("dream");
//		} catch (IOException e) {
     
//			// TODO Auto-generated catch block
//			System.out.println(e.toString());
//		}
//	}
    public   String  youdaoyun_fanyi(String  str) throws IOException {
     
    	String result="";
        Map<String,String> params = new HashMap<String,String>();
        String q = str;
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("from", "auto");
        params.put("to", "auto");
        params.put("signType", "v3");
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("curtime", curtime);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        params.put("appKey", APP_KEY);
        params.put("q", q);
        params.put("salt", salt);
        params.put("sign", sign);
        /** 处理结果 */
        System.out.println("打印结果");
        requestForHttp(YOUDAO_URL,params);
        pipei yu = new pipei();
        for (int i = 0; i < yu.Keysplit(thefirst_str).size(); i++) {
     
//        	System.out.println("第"+(i+1)+"条相关单词是:"+yu.Keysplit(a).get(i));
        	result+="第"+(i+1)+"条相关单词是:"+yu.Keysplit(thefirst_str).get(i)+"\n";
//        	System.out.println("第"+(i+1)+"条单词解释是:"+yu.valuesplit(a).get(i));
        	result+="第"+(i+1)+"条单词解释是:"+yu.valuesplit(thefirst_str).get(i)+"\n";
		}
//        System.out.println(result);s
		return result;
    }

    public static void requestForHttp(String url,Map<String,String> params) throws IOException {
     
    	String a="";
        /** 创建HttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /** httpPost */
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String,String>> it = params.entrySet().iterator();
        while(it.hasNext()){
     
            Map.Entry<String,String> en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            paramsList.add(new BasicNameValuePair(key,value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(paramsList,"UTF-8"));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try{
     
            Header[] contentType = httpResponse.getHeaders("Content-Type");
            logger.info("Content-Type:" + contentType[0].getValue());
            if("audio/mp3".equals(contentType[0].getValue())){
     
                //如果响应是wav
                HttpEntity httpEntity = httpResponse.getEntity();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpResponse.getEntity().writeTo(baos);
                byte[] result = baos.toByteArray();
                EntityUtils.consume(httpEntity);
                if(result != null){
     //合成成功
                    String file = "合成的音频存储路径"+System.currentTimeMillis() + ".mp3";
                    byte2File(result,file);
                }
            }else{
     
                /** 响应不是音频流,直接显示结果 */
                HttpEntity httpEntity = httpResponse.getEntity();
                String json = EntityUtils.toString(httpEntity,"UTF-8");
                EntityUtils.consume(httpEntity);
                logger.info(json);
//                System.out.println("json结果是:如下");
                String json_result = json;
//               创建一个json解析对象
                System.out.println("原返回的json值是:"+json);
                JsonObject  jsonObj = (JsonObject)new JsonParser().parse(json_result);
                String res = jsonObj.get("web").toString();
//                获取指定字段value
                System.out.println("第一次转换后结果是:"+res);
                int count=0;
              for (int i = 0; i < res.length(); i++) {
     
            	  if(res.charAt(i)!='{'&&res.charAt(i)!='['&&res.charAt(i)!='"'&&res.charAt(i)!=']'&&res.charAt(i)!='}') {
     
            		  		a=a+res.charAt(i);
            	  }  
            	  count++;
			}
              a=a+",";
               System.out.println("经过"+count+"次转换,最终结果为:"+a);
               thefirst_str=a;
//               KMP kmp = new KMP();
//               String value="";
//               String key="";
//               for (int i = 0; i <=a.length(); i++) {
     
//            	   	if(kmp.kmp_1(a,"value:")!=-1) {
     
//            	   		i=i+6;
//            	   	}
//            	   	value=value+a.charAt(i);
//            	 	if(kmp.kmp_1(a,"key:")!=-1) {
     
//            	   		i=i+4;
//            	   	}
//            	 	key=key+a.charAt(i);
//			}
//            	   System.out.println("value是:"+value);
//            	   System.out.println("key是:"+key);

            }
        }finally {
     
            try{
     
                if(httpResponse!=null){
     
                    httpResponse.close();
                }
            }catch(IOException e){
     
                logger.info("## release resouce error ##" + e);
            }
        }
    }

    /**
     * 生成加密字段
     */
    public static String getDigest(String string) {
     
        if (string == null) {
     
            return null;
        }
        char hexDigits[] = {
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
     
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
     
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
     
            return null;
        }
    }

    /**
    *
    * @param result 音频字节流
    * @param file 存储路径
    */
    private static void byte2File(byte[] result, String file) {
     
        File audioFile = new File(file);
        FileOutputStream fos = null;
        try{
     
            fos = new FileOutputStream(audioFile);
            fos.write(result);

        }catch (Exception e){
     
            logger.info(e.toString());
        }finally {
     
            if(fos != null){
     
                try {
     
                    fos.close();
                } catch (IOException e) {
     
                    e.printStackTrace();
                }
            }
        }

    }

  public static String truncate(String q) {
     
        if (q == null) {
     
            return null;
        }
        int len = q.length();
//        String result;
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}

2.KMP算法(可用可不用):

package com.sinsy.fanyi.youdaoyun;

public class KMP {
     
//	测试方法
//	public static void main(String[] args) {
     
//		String str="ANJCBLANXKLAJCBLSKN";
//		String sub = "CBLANXK";
//		System.out.println("子字符串的位置是从第"+(kmp_1(str,sub)+1)+"位开始的!");
//	}
	public  int kmp_1(String sources_str,String target_str) {
     
		if (sources_str == null || target_str == null || sources_str.length() == 0 || target_str.length() == 0) {
     	
			throw new IllegalArgumentException("str或者sub不能为空");
			} 	
		int j = 0;	
		int[] n = next(target_str);	
		for (int i = 0; i < sources_str.length(); i++) {
     
				while (j > 0 && sources_str.charAt(i) != target_str.charAt(j)) {
     	
				j = n[j - 1];			} 		
		if (sources_str.charAt(i) == target_str.charAt(j)) {
     			
		j++;			
	} 		
		if (target_str.length() == j) {
     	
				int index = i - j + 1;		
			return index;		
		}	
		} 	
		return -1;
	}
	public   int[] next(String target_str) {
     
//		首先声明一个数组,容量为目标字符串长度
		int[] n = new int[target_str.length()];
		int x = 0;
		for (int i = 1; i < target_str.length(); i++) {
     
			while (x > 0 && target_str.charAt(x) != target_str.charAt(x)) {
     
				x = n[x - 1];			
				} 			
			if (target_str.charAt(i) == target_str.charAt(x)) {
     
				x++;			
				} 			
			n[i] = x;	
			}
		return n;
		
	}
}

3.字符串匹配算法:

package com.sinsy.fanyi.youdaoyun;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class pipei {
     

	public  List<String> valuesplit(String str) {
     

		String regex = "value:(.*?)key:";

		List<String> list = new ArrayList<String>();

		List<String> extvounoLists = new ArrayList<String>();

		Pattern pattern = Pattern.compile(regex);

		Matcher m = pattern.matcher(str);

		while (m.find()) {
       

            int i = 1;  

            list.add(m.group(i));  

            i++;  

        } 
//		System.out.println(list.toString());
//		for (String str : list) {
     
//
//			System.out.println(str);
//
//			String[] strs = str.split("-");
//
//			String strss = strs[strs.length-1];
//
//			extvounoLists.add(strs[strs.length-1]);
//
//		}
//
//		
//
//		for (String string : extvounoLists) {
     
//
//			System.out.println(string);
//
//		}
//System.out.println(extvounoLists.toString());
		return list;
	}

	public  List<String> Keysplit(String str) {
     

		String regex = "key:(.*?),";

		List<String> list = new ArrayList<String>();

		List<String> extvounoLists = new ArrayList<String>();

		Pattern pattern = Pattern.compile(regex);

		Matcher m = pattern.matcher(str);

		while (m.find()) {
       

            int i = 1;  

            list.add(m.group(i));  

            i++;  

        } 
//		System.out.println(list.toString());
//		for (String str : list) {
     
//
//			System.out.println(str);
//
//			String[] strs = str.split("-");
//
//			String strss = strs[strs.length-1];
//
//			extvounoLists.add(strs[strs.length-1]);
//
//		}
//
//		
//
//		for (String string : extvounoLists) {
     
//
//			System.out.println(string);
//
//		}
//System.out.println(extvounoLists.toString());
		return list;
	}

//public static void main(String[] args) {
     
//	String str ="value:Hello,guten tag,How do you do,good afternoon,key:您好,value:FFWR,key:您好楼主,value:Model hello,Hello models,key:模特您好,";
//	String regex = "key:(.*?),";
//
//	List list = new ArrayList();
//
//	List extvounoLists = new ArrayList();
//
//	Pattern pattern = Pattern.compile(regex);
//
//	Matcher m = pattern.matcher(str);
//
//	while (m.find()) {  
//
//        int i = 1;  
//
//        list.add(m.group(i));  
//
//        i++;  
//
//    } 
//	System.out.println(list.toString());
	for (String str : list) {
     

		System.out.println(str);

		String[] strs = str.split("-");

		String strss = strs[strs.length-1];

		extvounoLists.add(strs[strs.length-1]);

	}

	

	for (String string : extvounoLists) {
     

		System.out.println(string);

	}
System.out.println(extvounoLists.toString());
//
//
//}

	public String ww(String str) {
     
		String regex = ",(.*?),";
		List<String> list = new ArrayList<String>();
		List<String> extvounoLists = new ArrayList<String>();
		Pattern pattern = Pattern.compile(regex);
		Matcher m = pattern.matcher(str);
		while (m.find()) {
       
            int i = 1;  
            list.add(m.group(i));  
            i++;  
        } 
		return list.toString();
	}
}

剪切板控制代码:

1.剪切板核心实现:

package com.sinsy.fntp;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class ClipboradUtils {
     
//	获取文本剪切板
	public Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
	public String getClipboardText() {
     
		String ret = "";
		// 获取剪切板中的内容
		Transferable clipTf = sysClip.getContents(null);
		if (clipTf != null) {
     
			// 检查内容是否是文本类型
			if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
     
				try {
     
					ret = (String) clipTf
							.getTransferData(DataFlavor.stringFlavor);
				} catch (Exception e) {
     
					e.printStackTrace();
				}
			}
		}
		return ret;
	}
	public boolean isChanged() {
     
		String firsttime = getClipboardText();
		String secondtime=null;
		// 获取剪切板中的内容
		Transferable clipTf = sysClip.getContents(null);
		if (clipTf != null) {
     
			// 检查内容是否是文本类型
			if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
     
				try {
     
					secondtime = (String) clipTf
							.getTransferData(DataFlavor.stringFlavor);
				} catch (Exception e) {
     
					e.printStackTrace();
				}
			}
		}
		if(firsttime==secondtime) {
     
			return false;
		}else {
     
		return true;
		}
	}
	public void setempty() {
       
        Transferable tText = new StringSelection("");  //覆盖系统剪切板
        sysClip.setContents(tText, null);  
	}
}


随机数算法:

package com.sinsy.fntp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Random;
public class Randomui {
     
	public static void main(String[] args) {
     
//		返回一个随机数
		System.out.println(suijishu().get(0));
	}
		static ArrayList<Integer> suijishu() {
     
			ArrayList<Integer> GD=new ArrayList<Integer>();
			 ArrayList<Integer> SCX=new ArrayList<Integer>();
	       for(int a=0;a<11;a++){
     
	           GD.add(a);
//	           System.out.print(a+"  ");
	       }
//	       System.out.println();
	       for(int b=0;b<4;b++){
     
	           Random r=new Random();
	             int a=r.nextInt(GD.size());
//	             [0,11)个伪随机数
//	             System.out.print(GD.get(a)+","); 
	             SCX.add(GD.get(a));
	             GD.remove(a);
	       }
//	       System.out.println();
	       return SCX;
		}
}


3.监听剪切板实现代码(保存至本地,可用可不用):

package com.sinsy.fntp;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class savaimage {
     
//	设置一个路径
//	String path="";
	public static String getpath (){
     
		 String Image_path=null;
		try {
     
			//获取粘贴板图片
			Image image = savaimage.getImageFromClipboard();
			Randomui randompath=new Randomui();
			
			File file= new File("D:\\"+randompath.suijishu().get(0)+randompath.suijishu().get(1)+randompath.suijishu().get(2)+randompath.suijishu().get(3)+".jpg");
			//转成jpg
			BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
			//转成png
//			BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, null, null);
			ImageIO.write((RenderedImage)bufferedImage, "jpg", file);
//			ImageIO.write((RenderedImage)bufferedImage, "png", file);
			Image_path=file.getPath();
 
		} catch (Exception e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Image_path;
	}
	
	
	/**
	 * 从剪切板获得文字。
	 */
	public static String getSysClipboardText() {
     
		String ret = "";
		Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
		// 获取剪切板中的内容
		Transferable clipTf = sysClip.getContents(null);
		
		if (clipTf != null) {
     
			// 检查内容是否是文本类型
			if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
     
				try {
     
					ret = (String) clipTf
							.getTransferData(DataFlavor.stringFlavor);
				} catch (Exception e) {
     
					e.printStackTrace();
				}
			}
		}
 
		return ret;
	}
 
	/**
	 * 将字符串复制到剪切板。
	 */
	public static void setSysClipboardText(String writeMe) {
     
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		clip.setContents(tText, null);
	}
 
	/**
	 * 从剪切板获得图片。
	 */
	public static Image getImageFromClipboard() throws Exception {
     
		Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable cc = sysc.getContents(null);
		if (cc == null)
			return null;
		else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
			return (Image) cc.getTransferData(DataFlavor.imageFlavor);
		return null;
	}
 
	/**
	 * 复制图片到剪切板。
	 */
	public static void setClipboardImage(final Image image) {
     
		Transferable trans = new Transferable() {
     
			public DataFlavor[] getTransferDataFlavors() {
     
				return new DataFlavor[] {
      DataFlavor.imageFlavor };
			}
 
			public boolean isDataFlavorSupported(DataFlavor flavor) {
     
				return DataFlavor.imageFlavor.equals(flavor);
			}
 
			public Object getTransferData(DataFlavor flavor)
					throws UnsupportedFlavorException, IOException {
     
				if (isDataFlavorSupported(flavor))
					return image;
				throw new UnsupportedFlavorException(flavor);
			}
 
		};
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
				null);
	}
}

腾讯云文本识别代码:

1.识别核心代码:

package com.sinsy.fntp.shibie;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sinsy.fntp.shibie.*;

public class aiscan {
     
	  //设置APPID/AK/SK
    public static final String APP_ID = "APPID";
    public static final String API_KEY = "APIKEY";
    public static final String SECRET_KEY = "KEY";
    public static String result = null;
    public  String ceshi() {
     
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选:设置log4j日志输出格式,若不设置,则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//    System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
//        设置一个连接地址(path)
    	savaimage image_path = new savaimage();
        String path = image_path.getpath();
        JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
//        保存读取结果:
       result = res.toString(2);
        System.out.println(res.toString(2));
        System.out.println(res.toString());
//       清除多余符号后
       System.out.println( split( getwords(res.toString())));
//       清除标记后:
       System.out.println(" 清除标记后:"+valuesplit(split( getwords(res.toString()))));
//       格式清除
       List<String> yu = valuesplit(split( getwords(res.toString())));
      String words="";
      for(int a=0;a<yu.size();a++) {
     
    	  words+=yu.get(a)+",";
      }
	return words;
      
    }
   public  String getwords(String json) {
     
//    	第一步:getwods
    	 JsonObject  jsonObj = (JsonObject)new JsonParser().parse(json);
    	 String words_res = jsonObj.get("words_result").toString();
    	 String number_res = jsonObj.get("words_result_num").toString();
    	  String re = words_res.replaceAll("\"", "");
    	  System.out.println(re);
    	  
		return re;
    	
    }
    public String split(String str) {
     
    	String i="";int count=0;
    	for(int a=0;a<str.length();a++) {
     
    		if(str.charAt(a)!='{'&&str.charAt(a)!='['&&str.charAt(a)!='"'&&str.charAt(a)!=']'&&str.charAt(a)!='}') {
     
		  		i=i+str.charAt(a);
	  }  
	  count++;
    	}
    	i+=",";
    	System.out.println("经过"+count+"次转换,最终结果为:"+i);
		return i;
    	
    }
    
	public   List<String> valuesplit(String str) {
     

		String regex = "words:(.*?),";

		List<String> list = new ArrayList<String>();

		List<String> extvounoLists = new ArrayList<String>();

		Pattern pattern = Pattern.compile(regex);

		Matcher m = pattern.matcher(str);

		while (m.find()) {
       

            int i = 1;  

            list.add(m.group(i));  

            i++;  

        } 
		return list;
	}

}

2.随机数生成算法

package com.sinsy.fntp.shibie;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Random;
public class Randomui {
     
	public static void main(String[] args) {
     
//		返回一个随机数
		System.out.println(suijishu().get(0));
	}
		static ArrayList<Integer> suijishu() {
     
			ArrayList<Integer> GD=new ArrayList<Integer>();
			 ArrayList<Integer> SCX=new ArrayList<Integer>();
	       for(int a=0;a<11;a++){
     
	           GD.add(a);
//	           System.out.print(a+"  ");
	       }
//	       System.out.println();
	       for(int b=0;b<4;b++){
     
	           Random r=new Random();
	             int a=r.nextInt(GD.size());
//	             [0,11)个伪随机数
//	             System.out.print(GD.get(a)+","); 
	             SCX.add(GD.get(a));
	             GD.remove(a);
	       }
//	       System.out.println();
	       return SCX;
		}
}


3.生成图片保存本地:(与上文一致)

package com.sinsy.fntp.shibie;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import com.sinsy.fntp.shibie.*;
public class savaimage {
     
//	设置一个路径
//	String path="";
	public static String getpath (){
     
		 String Image_path=null;
		try {
     
			//获取粘贴板图片
			Image image = savaimage.getImageFromClipboard();
			Randomui randompath=new Randomui();
			
			File file= new File("D:\\sinsy\\"+randompath.suijishu().get(0)+randompath.suijishu().get(1)+randompath.suijishu().get(2)+randompath.suijishu().get(3)+".jpg");
			//转成jpg
			BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
			//转成png
//			BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, null, null);
			ImageIO.write((RenderedImage)bufferedImage, "jpg", file);
//			ImageIO.write((RenderedImage)bufferedImage, "png", file);
			Image_path=file.getPath();
 
		} catch (Exception e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Image_path;
	}
	
	
	/**
	 * 从剪切板获得文字。
	 */
	public static String getSysClipboardText() {
     
		String ret = "";
		Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
		// 获取剪切板中的内容
		Transferable clipTf = sysClip.getContents(null);
		
		if (clipTf != null) {
     
			// 检查内容是否是文本类型
			if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
     
				try {
     
					ret = (String) clipTf
							.getTransferData(DataFlavor.stringFlavor);
				} catch (Exception e) {
     
					e.printStackTrace();
				}
			}
		}
 
		return ret;
	}
 
	/**
	 * 将字符串复制到剪切板。
	 */
	public static void setSysClipboardText(String writeMe) {
     
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		clip.setContents(tText, null);
	}
 
	/**
	 * 从剪切板获得图片。
	 */
	public static Image getImageFromClipboard() throws Exception {
     
		Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable cc = sysc.getContents(null);
		if (cc == null)
			return null;
		else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
			return (Image) cc.getTransferData(DataFlavor.imageFlavor);
		return null;
	}
 
	/**
	 * 复制图片到剪切板。
	 */
	public static void setClipboardImage(final Image image) {
     
		Transferable trans = new Transferable() {
     
			public DataFlavor[] getTransferDataFlavors() {
     
				return new DataFlavor[] {
      DataFlavor.imageFlavor };
			}
 
			public boolean isDataFlavorSupported(DataFlavor flavor) {
     
				return DataFlavor.imageFlavor.equals(flavor);
			}
 
			public Object getTransferData(DataFlavor flavor)
					throws UnsupportedFlavorException, IOException {
     
				if (isDataFlavorSupported(flavor))
					return image;
				throw new UnsupportedFlavorException(flavor);
			}
 
		};
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
				null);
	}
}

代码就放到这里吧,所有的资源包下载,我都放在一个压缩包里面,大家下载压缩包就可以导入eclipse直接运行使用了,注意需要Java-SWT的jar,没有的话,请在csdn搜索一下eclipse安装swt。

最后,如果您喜欢博主的文章,请您关注,点赞,评论三连走一波,感谢各位程序猿与程序媛的支持,小弟会继续努力。
翻译软件怎么实现的?我用Java教你实现私人自用翻译软件_第12张图片

你可能感兴趣的:(java程序开发,教程,Java,翻译,机器翻译)