先把工具类下载下来,直接拖进去:
/** * Base64 工具类 */ public class Base64Util { private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public Base64Util() { } public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); } }
import java.io.*; /** * 文件读取工具类 */ public class FileUtil { /** * 读取文件内容,作为字符串返回 */ public static String readFileAsString(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } if (file.length() > 1024 * 1024 * 1024) { throw new IOException("File is too large"); } StringBuilder sb = new StringBuilder((int) (file.length())); // 创建字节输入流 FileInputStream fis = new FileInputStream(filePath); // 创建一个长度为10240的Buffer byte[] bbuf = new byte[10240]; // 用于保存实际读取的字节数 int hasRead = 0; while ( (hasRead = fis.read(bbuf)) > 0 ) { sb.append(new String(bbuf, 0, hasRead)); } fis.close(); return sb.toString(); } /** * 根据文件路径读取byte[] 数组 */ public static byte[] readFileByBytes(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); short bufSize = 1024; byte[] buffer = new byte[bufSize]; int len1; while (-1 != (len1 = in.read(buffer, 0, bufSize))) { bos.write(buffer, 0, len1); } byte[] var7 = bos.toByteArray(); return var7; } finally { try { if (in != null) { in.close(); } } catch (IOException var14) { var14.printStackTrace(); } bos.close(); } } } }
/* * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. */ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import java.lang.reflect.Type; /** * Json工具类. */ public class GsonUtils { private static Gson gson = new GsonBuilder().create(); public static String toJson(Object value) { return gson.toJson(value); } public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException { return gson.fromJson(json, classOfT); } public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException { return (T) gson.fromJson(json, typeOfT); } }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * http 工具类 */ public class HttpUtil { public static String post(String requestUrl, String accessToken, String params) throws Exception { String contentType = "application/x-www-form-urlencoded"; return HttpUtil.post(requestUrl, accessToken, contentType, params); } public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception { String encoding = "UTF-8"; if (requestUrl.contains("nlp")) { encoding = "GBK"; } return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); } public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception { String url = requestUrl + "?access_token=" + accessToken; return HttpUtil.postGeneralUrl(url, contentType, params, encoding); } public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception { URL url = new URL(generalUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置通用的请求属性 connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); // 得到请求的输出流对象 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(params.getBytes(encoding)); out.flush(); out.close(); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> headers = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : headers.keySet()) { System.err.println(key + "--->" + headers.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = null; in = new BufferedReader( new InputStreamReader(connection.getInputStream(), encoding)); String result = ""; String getLine; while ((getLine = in.readLine()) != null) { result += getLine; } in.close(); System.err.println("result:" + result); return result; } }
然后是具体的实现:
import okhttp3.*; import org.json.JSONObject; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.io.IOException; public class TranslatorApp extends JFrame { public static final String API_KEY = "123456"; // 替换为你的 API_KEY public static final String SECRET_KEY = "123456"; // 替换为你的 SECRET_KEY static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); private JTextArea inputTextArea; private JTextArea resultTextArea; private JComboBox<String> languageComboBox; private JLabel statusLabel; public TranslatorApp() { setTitle("多语言翻译器"); setSize(600, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 设置整体背景色和边距 JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); mainPanel.setBackground(new Color(240, 240, 240)); mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20)); setContentPane(mainPanel); // 顶部面板 JPanel topPanel = new JPanel(new BorderLayout(10, 10)); topPanel.setOpaque(false); // 输入区域 JPanel inputPanel = new JPanel(new BorderLayout(5, 5)); inputPanel.setOpaque(false); JLabel inputLabel = new JLabel("输入文本:"); inputLabel.setFont(new Font("微软雅黑", Font.BOLD, 14)); inputTextArea = new JTextArea(5, 30); inputTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14)); inputTextArea.setLineWrap(true); inputTextArea.setWrapStyleWord(true); JScrollPane inputScrollPane = new JScrollPane(inputTextArea); inputScrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200))); inputPanel.add(inputLabel, BorderLayout.NORTH); inputPanel.add(inputScrollPane, BorderLayout.CENTER); // 语言选择和翻译按钮面板 JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5)); controlPanel.setOpaque(false); String[] languages = new String[]{ "中译英 (English)", "中译日 (日本語)", "中译俄 (Русский)", "中译法 (Français)", "英译中 (中文)" }; languageComboBox = new JComboBox<>(languages); languageComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12)); languageComboBox.setPreferredSize(new Dimension(150, 30)); JButton translateButton = createStyledButton("开始翻译"); controlPanel.add(new JLabel("目标语言:")); controlPanel.add(languageComboBox); controlPanel.add(translateButton); // 结果显示区域 JPanel resultPanel = new JPanel(new BorderLayout(5, 5)); resultPanel.setOpaque(false); JLabel resultLabel = new JLabel("翻译结果:"); resultLabel.setFont(new Font("微软雅黑", Font.BOLD, 14)); resultTextArea = new JTextArea(5, 30); resultTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14)); resultTextArea.setLineWrap(true); resultTextArea.setWrapStyleWord(true); resultTextArea.setEditable(false); resultTextArea.setBackground(new Color(250, 250, 250)); JScrollPane resultScrollPane = new JScrollPane(resultTextArea); resultScrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200))); resultPanel.add(resultLabel, BorderLayout.NORTH); resultPanel.add(resultScrollPane, BorderLayout.CENTER); // 状态栏 statusLabel = new JLabel("就绪"); statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12)); statusLabel.setForeground(Color.GRAY); // 组装界面 topPanel.add(inputPanel, BorderLayout.CENTER); topPanel.add(controlPanel, BorderLayout.SOUTH); mainPanel.add(topPanel, BorderLayout.NORTH); mainPanel.add(resultPanel, BorderLayout.CENTER); mainPanel.add(statusLabel, BorderLayout.SOUTH); // 设置翻译按钮事件 translateButton.addActionListener(e -> performTranslation()); } private JButton createStyledButton(String text) { JButton button = new JButton(text); button.setFont(new Font("微软雅黑", Font.PLAIN, 12)); button.setPreferredSize(new Dimension(100, 30)); button.setBackground(new Color(66, 139, 202)); button.setForeground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); return button; } private void performTranslation() { String textToTranslate = inputTextArea.getText().trim(); if (textToTranslate.isEmpty()) { showError("请输入要翻译的文本"); return; } // 设置语言代码 String[] languagePair = getLanguagePair(); String fromLanguage = languagePair[0]; String toLanguage = languagePair[1]; // 开始翻译 statusLabel.setText("正在翻译..."); resultTextArea.setText(""); // 使用SwingWorker在后台执行翻译 new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { return translateText(fromLanguage, toLanguage, textToTranslate); } @Override protected void done() { try { String result = get(); resultTextArea.setText(result); statusLabel.setText("翻译完成"); } catch (Exception e) { showError("翻译失败: " + e.getMessage()); } } }.execute(); } private String[] getLanguagePair() { String selection = (String) languageComboBox.getSelectedItem(); switch (selection) { case "中译英 (English)": return new String[]{"zh", "en"}; case "中译日 (日本語)": return new String[]{"zh", "jp"}; case "中译俄 (Русский)": return new String[]{"zh", "ru"}; case "中译法 (Français)": return new String[]{"zh", "fra"}; case "英译中 (中文)": return new String[]{"en", "zh"}; default: return new String[]{"zh", "en"}; } } private void showError(String message) { statusLabel.setText("错误: " + message); JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE); } // 翻译方法保持不变,但增加错误处理 public static String translateText(String from, String to, String q) throws IOException { try { MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, new JSONObject().put("from", from).put("to", to).put("q", q).toString()); Request request = new Request.Builder() .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken()) .post(body) .addHeader("Content-Type", "application/json") .addHeader("Accept", "application/json") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); if (response.isSuccessful()) { String responseBody = response.body().string(); JSONObject jsonResponse = new JSONObject(responseBody); return jsonResponse.getJSONObject("result").getJSONArray("trans_result").getJSONObject(0).getString("dst"); } else { throw new IOException("翻译请求失败,状态码:" + response.code()); } } catch (Exception e) { throw new IOException("翻译过程中发生错误: " + e.getMessage()); } } // getAccessToken方法保持不变 static String getAccessToken() throws IOException { MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY); Request request = new Request.Builder() .url("https://aip.baidubce.com/oauth/2.0/token") .post(body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); if (response.isSuccessful()) { String responseBody = response.body().string(); return new JSONObject(responseBody).getString("access_token"); } else { throw new IOException("获取Access Token失败,状态码:" + response.code()); } } public static void main(String[] args) { try { // 设置界面风格为系统默认外观 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(() -> { TranslatorApp app = new TranslatorApp(); app.setVisible(true); }); } }
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>SoftWareConstruction</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>22</maven.compiler.source> <maven.compiler.target>22</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.12.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.1</version> </dependency> </dependencies> </project>
把pom也给一下吧
标签:return,String,多种语言,接口,char,static,new,public,百度 From: https://www.cnblogs.com/muzhaodi/p/18541814