import cn.zhangsan.tools.enums.Algorithm;import com.google.common.collect.Maps;import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.bouncycastle.util.encoders.Hex;import java.net.MalformedURLException;import java.net.URL;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.Security;import java.util.Base64;import java.util.Map;/** * @ClassName HashGeneratorUtils * @Description TODO * @Author ZhangSan_Plus * @Date 2024/7/29 20:04 * @Version 1.0 **/public class HashGeneratorUtils { static Map<Object, String> map = Maps.newLinkedHashMap(); static { Security.addProvider(new BouncyCastleProvider()); } public static void main(String[] args) { String input = "张三"; try { Map<Object, String> hashText = getHashText(input, 4); hashText.forEach((k, v) -> System.out.println(k + ":" + v)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String extractDomain(String urlString) { try { URL url = new URL(urlString); return url.getHost(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } } private static Map<Object, String> getHashText(String text, int digest) throws NoSuchAlgorithmException { map.put(Algorithm.MD5, encryption(md5(text), digest)); map.put(Algorithm.SHA1, encryption(sha1(text), digest)); map.put(Algorithm.SHA256, encryption(sha224(text), digest)); map.put(Algorithm.SHA224, encryption(sha256(text), digest)); map.put(Algorithm.SHA512, encryption(sha384(text), digest)); map.put(Algorithm.SHA384, encryption(sha512(text), digest)); map.put(Algorithm.SHA3, encryption(sha3_256(text), digest)); map.put(Algorithm.RIPEMD160, encryption(ripemd160(text), digest)); return map; } private static byte[] md5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); return digest.digest(input.getBytes()); } private static byte[] sha1(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); return digest.digest(input.getBytes()); } private static byte[] sha224(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-224"); return digest.digest(input.getBytes()); } private static byte[] sha256(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); return digest.digest(input.getBytes()); } private static byte[] sha384(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-384"); return digest.digest(input.getBytes()); } private static byte[] sha512(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-512"); return digest.digest(input.getBytes()); } private static byte[] sha3_256(String input) throws NoSuchAlgorithmException { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA3-256", "BC"); } catch (NoSuchProviderException e) { throw new RuntimeException(e); } return digest.digest(input.getBytes()); } private static byte[] ripemd160(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("RIPEMD160"); return digest.digest(input.getBytes()); } private static String toHexString(byte[] bytes) { return Hex.toHexString(bytes); } private static String toBase64(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } private static String toBase64Url(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } private static String toBinary(byte[] bytes) { StringBuilder binaryString = new StringBuilder(); for (byte b : bytes) { for (int i = 7; i >= 0; i--) { binaryString.append(((b >> i) & 1) == 1 ? '1' : '0'); } binaryString.append(""); } return binaryString.toString().trim(); } private static String encryption(byte[] bytes, int encoding) { switch (encoding) { case 1: return toHexString(bytes); case 2: return toBinary(bytes); case 3: return toBase64(bytes); case 4: return toBase64Url(bytes); default: return ""; } }}

时间: 2025-03-30 21:06:17 AIGC 浏览: 45
### Java 实现多种哈希算法及编码方式 #### 1. 使用 `MessageDigest` 类生成哈希值 Java 提供了标准库类 `java.security.MessageDigest` 来计算哈希值。以下是针对 MD5、SHA-1 和 SHA-256 的实现。 ```java import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; public class HashExample { public static String getHash(String input, String algorithm) throws Exception { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8)); return bytesToHex(hashBytes); } private static String bytesToHex(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte b : bytes) { result.append(String.format("%02x", b)); } return result.toString(); } public static void main(String[] args) throws Exception { String text = "HelloWorld"; // 计算 MD5 哈希值 System.out.println("MD5: " + getHash(text, "MD5")); // 计算 SHA-1 哈希值 System.out.println("SHA-1: " + getHash(text, "SHA-1")); // 计算 SHA-256 哈希值 System.out.println("SHA-256: " + getHash(text, "SHA-256")); } } ``` 上述代码通过调用 `MessageDigest.getInstance()` 方法指定了具体的哈希算法[^1],并将其应用于输入字符串上。最终返回的结果是以十六进制格式表示的哈希值。 --- #### 2. 将哈希值转换为其他编码方式 ##### a. 转换为 Base64 编码 可以利用 `java.util.Base64` 工具类将字节数组转换为 Base64 字符串: ```java public static String toBase64(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } // 示例:在主函数中添加如下代码 System.out.println("MD5 Base64: " + toBase64(digest.digest())); ``` 此处展示了如何将原始字节数据转化为 Base64 表示形式[^5]。 ##### b. 转换为二进制字符串 可以通过逐位解析的方式将字节数组转为二进制字符串: ```java private static String bytesToBinary(byte[] bytes) { StringBuilder binaryString = new StringBuilder(); for (byte b : bytes) { binaryString.append(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0')); } return binaryString.toString(); } // 示例:在主函数中添加如下代码 System.out.println("MD5 Binary: " + bytesToBinary(md5.digest())); ``` 此部分实现了从字节数组到纯二进制字符串的映射过程。 --- #### 3. 图片文件的哈希处理 对于图片或其他类型的文件,可以直接读取其字节流并传递给 `MessageDigest` 进行处理。以下是一个基于图片路径生成 MD5 值的例子: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ImageHashExample { public static void main(String[] args) throws IOException, Exception { byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.jpg")); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] hashBytes = md5.digest(imageBytes); System.out.println("Image MD5 Hex: " + bytesToHex(hashBytes)); // 十六进制输出 System.out.println("Image MD5 Base64: " + Base64.getEncoder().encodeToString(hashBytes)); // Base64 输出 } } ``` 该片段说明了如何加载外部资源(如图像)并通过指定算法对其进行摘要运算[^2]。 --- ### 总结 以上介绍了如何使用 Java 标准库完成多样的哈希算法与编码操作。无论是简单的文本还是复杂的多媒体文件,都可以借助内置工具轻松达成目标。
阅读全文

相关推荐

package controller; import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import pojo.UserForm; @Controller @RequestMapping("/user") public class UserControllerOrigin { //得到一个用来记录日志的对象,这样在打印信息时能够标记打印的是哪个类的信息 private static final Log logger = LogFactory.getLog(UserControllerOrigin.class); /** * 处理登录 * 使用UserForm 对象(实体 Bean)user接收登录页面提交的请求参数 */ @PostMapping("/login") public String login(UserForm user, HttpSession session, Model model) { if ("zhangsan".equals(user.getUname()) && "123456".equals(user.getUpass())) { session.setAttribute("u", user); logger.info("成功"); return "main"; } else { logger.info("失败"); //登录失败,跳转到login.jsp model.addAttribute("messageError", "用户名或密码错误"); return "login"; } } /** * 处理注册 * 使用UserForm对象(实体Bean)user接收注册页面提交的请求参数 */ @PostMapping("/register") public String register(UserForm user, Model model) { if (user.getUname() != null && !user.getUname().isEmpty() && user.getUpass() != null && !user.getUpass().isEmpty()) { logger.info("成功"); return "login"; } else { //注册失败,跳转到 register.jsp logger.info("失败"); //在register.jsp页面上可以使用EL表达式取出model的uname值 model.addAttribute("uname", user.getUname()); return "register";//返回 register.jsp } } }C:\Users\xx\Desktop\demo\src\main\java\controller\UserControllerOrigin.java:25:35 java: 找不到符号 符号: 方法 getUname() 位置: 类型为pojo.UserForm的变量 user

package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; @WebServlet("/SearchServlet") public class SearchServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 连接数据库查询数据 //模拟了数据库查询出来的数据,两行数据(两个对象) User user1 = new User("1","zhangsan","18","M"); User user2 = new User("2","lisi","19","F"); List<User> userList = new ArrayList<User>(); userList.add(user1); userList.add(user2); // 将查询结果转为JSON格式 JSONArray jsonArray = new JSONArray(); for (int i = 0; i < userList.size(); i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", userList.get(i).getId()); jsonObject.put("name", userList.get(i).getName()); jsonObject.put("age", userList.get(i).getAge()); jsonObject.put("gender", userList.get(i).getGender()); jsonArray.put(jsonObject); } // 返回JSON格式数据 response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print(jsonArray.toString()); out.flush(); out.close(); } }package servlet; import java.util.Collection; public class User { public User(String Id, String Name, String Age, String Gender) { // TODO Auto-generated constructor stub } public Collection<?> getId() { // TODO Auto-generated method stub return null; } public Collection<?> getName() { // TODO Auto-generated method stub return null; } public Collection<?> getAge() { // TODO Auto-generated method stub return null; } public Collection<?> getGender() { // TODO Auto-generated method stub return null; } }package servlet; import java.util.Collection; public class User { public User(String Id, String Name, String Age, String Gender) { // TODO Auto-generated constructor stub } public Collection<?> getId() { // TODO Auto-generated method stub return null; } public Collection<?> getName() { // TODO Auto-generated method stub return null; } public Collection<?> getAge() { // TODO Auto-generated method stub return null; } public Collection<?> getGender() { // TODO Auto-generated method stub return null; } }package servlet; import java.util.Collection; public class User { public User(String Id, String Name, String Age, String Gender) { // TODO Auto-generated constructor stub } public Collection<?> getId() { // TODO Auto-generated method stub return null; } public Collection<?> getName() { // TODO Auto-generated method stub return null; } public Collection<?> getAge() { // TODO Auto-generated method stub return null; } public Collection<?> getGender() { // TODO Auto-generated method stub return null; } }

实验四的界面是图书查询界面Ss.java类代码: import static com.example.myapplication.R.id.tt_hg; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Ss extends AppCompatActivity { private EditText editId; private EditText editName; private EditText editAuthor; private static final int item1 = Menu.FIRST; private static final int item2 = Menu.FIRST + 1; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); EditText syqt = findViewById(R.id.edit_id); syqt.setTextSize(Integer.valueOf(size)); EditText cxqt = findViewById(R.id.edit_name); cxqt.setTextSize(Integer.valueOf(size)); EditText szqt = findViewById(R.id.edit_author); szqt.setTextSize(Integer.valueOf(size)); RadioButton dfqt = findViewById(tt_hg); dfqt.setTextSize(Integer.valueOf(size)); RadioButton dft = findViewById(R.id.tt_hu); dft.setTextSize(Integer.valueOf(size)); Button dfttd = findViewById(R.id.btn_ff); dfttd.setTextSize(Integer.valueOf(size)); Button dftqq = findViewById(R.id.btn_clar); dftqq.setTextSize(Integer.valueOf(size)); Button dftww = findViewById(R.id.btn_back); dftww.setTextSize(Integer.valueOf(size)); Button dftwwl = findViewById(R.id.ff_id1); dftwwl.setTextSize(Integer.valueOf(size)); Button dftwws = findViewById(R.id.ff_id2); dftwws.setTextSize(Integer.valueOf(size)); Button dftwwt = findViewById(R.id.ff_id3); dftwwt.setTextSize(Integer.valueOf(size)); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToEditText(editId, size, color); applyStyleToEditText(editName, size, color); applyStyleToEditText(editAuthor, size, color); } private void applyStyleToEditText(EditText btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ss); // 初始化 EditText editId = findViewById(R.id.edit_id); editName = findViewById(R.id.edit_name); editAuthor = findViewById(R.id.edit_author);//通过ID绑定视图对象 RadioButton ttHg = findViewById(R.id.tt_hg); RadioButton ttHu = findViewById(R.id.tt_hu); Button btnFf = findViewById(R.id.btn_ff); LinearLayout ll = findViewById(R.id.table_layout); registerForContextMenu(ll); btnFf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在此处编写查询逻辑(示例:Toast提示) // Toast.makeText(Ss.this, "查询按钮被点击,执行查询操作", Toast.LENGTH_SHORT).show(); } }); // 1清空 - 属性事件响应(XML 按钮需添加 android:onClick="clearByAttribute") // 2清空 - 内部匿名类事件响应 findViewById(R.id.ff_id1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearFields(); } }); // 3清空 - 监听器接口实现类事件响应 findViewById(R.id.ff_id2).setOnClickListener(new MyClickListener()); // 4清空 - 外部监听器接口实现类事件响应 findViewById(R.id.ff_id3).setOnClickListener(new ExternalClickListener(this)); Button btnBack = findViewById(R.id.btn_back); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Ss.this, Sy.class); startActivity(intent); finish(); } }); } // 1清空对应的属性事件响应方法 public void clearByAttribute(View view) { clearFields(); }//当用户点击按钮就会被执行 // 清空文本框的公共方法 public void clearFields() { if (editId != null) editId.setText(""); if (editName != null) editName.setText(""); if (editAuthor != null) editAuthor.setText(""); } // 内部监听器接口实现类(3清空) private class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { clearFields(); } } // 外部监听器接口实现类(4清空) @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) { menu.add(0, 1, 0, "删除"); menu.add(0, 2, 0, "修改"); super.onCreateContextMenu(menu, view, info); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == 1) { Toast.makeText(this, "您点击了删除", Toast.LENGTH_LONG).show(); } else if (item.getItemId() == 2) { Toast.makeText(this, "您点击了修改", Toast.LENGTH_LONG).show(); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, item1, 0, "关于"); menu.add(0, item2, 0, "退出"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case item1: Toast.makeText(Ss.this, "姓名:骆树涛。学号:2404224132", Toast.LENGTH_SHORT).show(); break; case item2: this.finish(); break; } return true; } } 图书查询界面的ss.XML布局文件代码: <?xml version="1.0" encoding="utf-8"?> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书编号" android:textSize="20dp"/> <EditText android:id="@+id/edit_id" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书名称" android:textSize="20dp"/> <EditText android:id="@+id/edit_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书作者" android:textSize="20dp"/> <EditText android:id="@+id/edit_author" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="中文" android:textSize="20dp"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="外文" android:textSize="20dp"/> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询" android:textSize="20dp"/> <Button android:id="@+id/btn_clar" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="清空" android:textSize="20dp" android:onClick="clearByAttribute"/> <Button android:id="@+id/btn_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回" android:textSize="20dp"/> <Button android:id="@+id/ff_id1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清空" android:textSize="20dp"/> <Button android:id="@+id/ff_id2" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="清空" android:textSize="20dp" /> <Button android:id="@+id/ff_id3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清空" android:textSize="20dp"/> <TextView android:text="图书编号" android:textSize="15dp"/> <TextView android:text="图书名称" android:textSize="15dp"/> <TextView android:text="图书作者" android:textSize="15dp"/> <TextView android:text="馆藏地点" android:textSize="15dp"/> <TextView android:text="1001" android:textSize="15dp"/> <TextView android:text="Android" android:textSize="15dp"/> <TextView android:text="张三" android:textSize="15dp"/> <TextView android:text="5-423" android:textSize="15dp"/> <TextView android:text="查询结果1条" android:textSize="15dp" android:layout_span="4" android:layout_gravity="center"/> 实验六的代码如下 新增Xz.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Xz extends AppCompatActivity { private EditText editBookId; private EditText editBookName; private EditText editBookAuthor; private EditText editBookLocation; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); EditText syq = findViewById(R.id.edit_book_id); syq.setTextSize(Integer.valueOf(size)); EditText cxq = findViewById(R.id.edit_book_name); cxq.setTextSize(Integer.valueOf(size)); EditText szq = findViewById(R.id.edit_book_author); szq.setTextSize(Integer.valueOf(size)); EditText dfq = findViewById(R.id.edit_book_location); dfq.setTextSize(Integer.valueOf(size)); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToEditText(editBookId, size, color); applyStyleToEditText(editBookName, size, color); applyStyleToEditText(editBookAuthor, size, color); applyStyleToEditText(editBookLocation, size, color); } private void applyStyleToEditText(EditText btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.xz); editBookId = findViewById(R.id.edit_book_id); editBookName = findViewById(R.id.edit_book_name); editBookAuthor = findViewById(R.id.edit_book_author); editBookLocation = findViewById(R.id.edit_book_location); Button btnAddBook = findViewById(R.id.btn_add_book); btnAddBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String bookId = editBookId.getText().toString(); String bookName = editBookName.getText().toString(); String bookAuthor = editBookAuthor.getText().toString(); String bookLocation = editBookLocation.getText().toString(); Intent intent = new Intent(Xz.this, Xq.class); intent.putExtra("bookId", bookId); intent.putExtra("bookName", bookName); intent.putExtra("bookAuthor", bookAuthor); intent.putExtra("bookLocation", bookLocation); startActivity(intent); } }); } } 新增的xz.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书编号" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_id" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书名称" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书作者" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_author" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="馆藏地点" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_location" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_add_book" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增" android:textSize="20dp" android:layout_gravity="center"/> 详情Xq.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Xq extends AppCompatActivity { private static final int ITEM_HOME = Menu.FIRST; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); TextView syqw = findViewById(R.id.tv_book_id); syqw.setTextSize(Integer.valueOf(size)); TextView cxqw = findViewById(R.id.tv_book_name); cxqw.setTextSize(Integer.valueOf(size)); TextView szqw = findViewById(R.id.tv_book_author); szqw.setTextSize(Integer.valueOf(size)); TextView dfqw = findViewById(R.id.tv_book_location); dfqw.setTextSize(Integer.valueOf(size)); super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.xq); TextView tvBookId = findViewById(R.id.tv_book_id); TextView tvBookName = findViewById(R.id.tv_book_name); TextView tvBookAuthor = findViewById(R.id.tv_book_author); TextView tvBookLocation = findViewById(R.id.tv_book_location); Intent intent = getIntent(); String bookId = intent.getStringExtra("bookId"); String bookName = intent.getStringExtra("bookName"); String bookAuthor = intent.getStringExtra("bookAuthor"); String bookLocation = intent.getStringExtra("bookLocation"); tvBookId.setText("图书编号:" + bookId); tvBookName.setText("图书名称:" + bookName); tvBookAuthor.setText("图书作者:" + bookAuthor); tvBookLocation.setText("馆藏地点:" + bookLocation); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, ITEM_HOME, 0, "首页"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case ITEM_HOME: Intent intent = new Intent(Xq.this, Sy.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } } 详情的xq.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <TextView android:id="@+id/tv_book_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_author" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> 首页Sy.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Sy extends AppCompatActivity { private Button btnAdd; private Button btnSearch; private Button btnSetting; private static final int item1 = Menu.FIRST; private static final int item2 = Menu.FIRST + 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sy); btnAdd = findViewById(R.id.btn_add); btnSearch = findViewById(R.id.btn_search); btnSetting = findViewById(R.id.btn_setting); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, SettingsActivity.class); startActivity(intent); } }); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, Xz.class); startActivity(intent); } }); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, Ss.class); startActivity(intent); } }); } public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); Button sy = findViewById(R.id.btn_add); sy.setTextSize(Integer.valueOf(size)); Button cx = findViewById(R.id.btn_search); cx.setTextSize(Integer.valueOf(size)); Button sz = findViewById(R.id.btn_setting); sz.setTextSize(Integer.valueOf(size)); String bg = sp.getString("bg","c"); int pic_id = this.getResources().getIdentifier(bg,"drawable","com.example.myapplication"); LinearLayout bg_b = findViewById(R.id.bg_d); bg_b.setBackgroundResource(pic_id); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToButton(btnAdd, size, color); applyStyleToButton(btnSearch, size, color); applyStyleToButton(btnSetting, size, color); } private void applyStyleToButton(Button btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, item1, 0, "关于"); menu.add(0, item2, 0, "退出"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case item1: Toast.makeText(Sy.this, "姓名:骆树涛。学号:2404224132", Toast.LENGTH_SHORT).show(); break; case item2: finishAffinity(); break; } return true; } } 首页的sy.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <Button android:id="@+id/btn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增" android:textSize="15dp"/> <Button android:id="@+id/btn_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询" android:textSize="15dp"/> <Button android:id="@+id/btn_setting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设置" android:textSize="15dp"/> SettingsActivity.Java设置类代码: import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceFragmentCompat; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.se); // 加载容器布局 // 加载PreferenceFragment到Activity中 getSupportFragmentManager() .beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } // 静态内部类:管理设置项的Fragment public static class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { // 从XML文件加载设置项(需创建res/xml/settings.xml) setPreferencesFromResource(R.xml.settings, rootKey); } } } Se.XML布局文件代码: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/content" android:layout_width="match_parent" android:layout_height="match_parent"/> arry.XML的valuse代码: <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="color_entries"> <item>黑色</item> <item>红色</item> <item>黄色</item> <item>蓝色</item> </string-array> <string-array name="color_values"> <item>#FF000000</item> <item>#FFFF0000</item> <item>#FFFFFF00</item> <item>#FF0000FF</item> </string-array> <string-array name="bg"> <item>科技</item> <item>书籍</item> </string-array> <string-array name="bg_hhg"> <item>a</item> <item>b</item> <item>c</item> </string-array> </resources> sring.XML的xml代码: <?xml version="1.0" encoding="utf-8"?> <EditTextPreference android:key="font_size" android:title="字号设置" android:summary="输入文字大小" android:defaultValue="15" android:inputType="number"/> AndroidManifest.xml代码 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.MyApplication" tools:targetApi="31"> <meta-data android:name="com.google.android.actions" android:resource="@layout/sy" /> <activity android:name=".Sy" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Xz" /> <activity android:name=".Xq" /> <activity android:name=".Ss" /> <activity android:name=".Cada" /> <activity android:name=".SettingsActivity" android:label="设置" android:theme="@style/Theme.AppCompat.Light.DarkActionBar" /> </application> </manifest> 内部存储(Internal Storage)的Context中提供了相应的函数对文件进行操作, 实验7:基于文件存储的数据读写 在实验6的基础上,实现基于Android系统文件存储的数据存储功能,具体要求如下: (1)增加一个励志标题添加功能。在首页增加“设置标题”按钮,点击后进入励志标题编辑界面,励志标题文字保存在内部存储的文件中,文件名以开发者自己的姓名拼音命名,例如“zhangsan.txt”。用户打开软件后,标题栏的标题文字从内部文件中读取并显示。 (2)修改图书新增功能。点击“新增”按钮后,用户输入的图书数据存储在外部文件中,文件名以开发者自己的姓名拼音命名,例如“zhangsan.txt”。数据新增完毕后,自动跳到图书查询页面。 (3) 修改图书查询页面。打开图书查询界面后,界面中的那条图书信息从外部文件中读取,并显示在相应的位置。 以上内容的全部代码

import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FolderStructureGenerator { public static void main(String[] args) { // 1. 创建主文件夹 (替换YourName为实际拼音) String mainFolder = "D:\\ZhangSan"; // 示例:张三的拼音 File mainDir = new File(mainFolder); if (!mainDir.exists() && mainDir.mkdir()) { System.out.println("主文件夹创建成功: " + mainFolder); } // 2. 创建子文件夹 String subFolder = mainFolder + "\\myfile"; File subDir = new File(subFolder); if (!subDir.exists() && subDir.mkdir()) { System.out.println("子文件夹创建成功: " + subFolder); } // 3. 创建各种类型文件 String[] fileNames = { "document1.docx", "document2.docx", "Program1.java", "Program2.java", "notes1.txt", "notes2.txt" }; // 文件示例内容 String javaContent = "public class Program {\n public static void main(String[] args) {\n System.out.println(\"Hello World!\");\n }\n}"; String txtContent = "这是一个示例文本文件\n包含多行内容\n-- 第1行\n-- 第2行"; for (String fileName : fileNames) { try { File file = new File(subDir, fileName); if (file.createNewFile()) { // 写入内容到文本文件 if (fileName.endsWith(".java")) { try (FileWriter writer = new FileWriter(file)) { writer.write(javaContent); } } else if (fileName.endsWith(".txt")) { try (FileWriter writer = new FileWriter(file)) { writer.write(txtContent); } } System.out.println("文件创建成功: " + file.getPath()); } } catch (IOException e) { System.err.println("文件创建失败: " + e.getMessage()); } } // 4. 输出完整文件夹结构 System.out.println("\n===== 文件夹结构 ====="); printFolderStructure(mainDir, 0); } // 递归打印文件夹结构 private static void printFolderStructure(File folder, int indent) { // 生成缩进字符串 StringBuilder indentStr = new StringBuilder(); for (int i = 0; i < indent; i++) { indentStr.append(" "); } // 打印当前文件夹 System.out.println(indentStr.toString() + "📁 " + folder.getName()); File[] files = folder.listFiles(); if (files == null) return; for (File file : files) { if (file.isDirectory()) { printFolderStructure(file, indent + 1); } else { // 生成文件缩进(比文件夹多一级) StringBuilder fileIndent = new StringBuilder(indentStr.toString()); fileIndent.append(" "); // 打印文件信息 System.out.println(fileIndent.toString() + "📄 " + file.getName()); // 输出文本文件内容 if (file.getName().endsWith(".txt") || file.getName().endsWith(".java")) { try { StringBuilder contentIndent = new StringBuilder(fileIndent.toString()); contentIndent.append(" "); System.out.println(contentIndent.toString() + "---- 文件内容 ----"); for (String line : Files.readAllLines(Paths.get(file.getAbsolutePath()))) { System.out.println(contentIndent.toString() + line); } System.out.println(contentIndent.toString() + "-----------------"); } catch (IOException e) { System.err.println("读取文件失败: " + e.getMessage()); } } } } } }修改 可被替换为 'String.repeat()',不必要的 'toString()' 调用,拼写错误: 在单词 'myfile' 中

1、MySQL数据库操作 (1) 根据上面给出的Student表,在 MySQL数据库中完成如下操作。 1、在MySQL中创建Student表,并录入数据。 SQL语句: 1)create table Student ( name varchar(30) not null, English tinyint unsigned not null, Math tinyint unsigned not null, Computer tinyint unsigned not null ); 2)insert into Student values (“zhangsan”,69,86,77); 3)insert into Student values ("lisi",55,100,88); 图1、创建Student表 2、用SQL语句输出Student表中的所有记录。 SQL语句: select * from Student; 图2、查询Student表 3、查询zhangsan的Computer成绩。 SQL语句: select name , Computer from Student where name ="zhangsan"; 图3、查询zhangsan的Computer成绩 4、修改lisi的 Math成绩,改为95。 SQL语句: update Student set Math=95 where name = "lisi"; select name , Math from Student where name ="lisi"; 图4、修改lisi的 Math成绩,改为95 (2)根据上面已经设计出的 Student表,使用MySQL的Java客户端编程实现以下操作。 1、向Student表中添加如下所示的一条记录: 2、获取scofield的 English成绩信息。 java代码: 图5、MySQL添加记录(java) 图6、MySQL查询记录(java) 2、HBase数据库操作 (1)根据上面给出的Student表的信息,执行如下操作。 1)用HBase Shell命令创建学生表Student。 2)用scan指令浏览Student表的相关信息。 Shell命令以及运行结果如图: 图7、HBase建Student表 3)查询zhangsan的Computer成绩。 4)修改lisi的Math成绩,改为95。 Shell命令: get 'Student','1','score:Computer' put 'Student','2','score:Math',95 get 'Student','2' 图8、HBase查询修改记录 (2)根据上面已经设计出的Student表,用HBase API编程实现以下操作。 1)添加数据:English为45 ;Math为89;Computer 为 100。 2)获取scofield的English成绩信息。 java代码:   图9、HBase查询修改记录(java) 3、Redis数据库操作 (1)根据上面给出的键值对,完成如下操作。 1)用Redis的哈希结构设计出学生表Student(键值可以用student.zhangsan和student.lisi来表示两个键值属于同一个表)。 2)用hgetall命令分别输出zhangsan和 lisi的成绩信息。 Shell命令: hset Student.zhangsan English 69 hset Student.zhangsan Math 86 hset Student.zhangsan Computer 77 hset Student.lisi English 55 hset Student.lisi Math 100 hset Student.lisi Computer 88 hgetall Student.zhangsan hgetall Student.lisi 图10、Redis添加与查询记录 3)用hget命令查询zhangsan的 Computer成绩。 4)修改lisi的Math成绩,改为95。 Shell命令: hget Student.zhangsan Computer hset Student.lisi Math 95 图11、Redis查询与修改记录 (2)根据上面已经设计出的学生表Student,用Redis的Java客户端编程(jedis),实现如下操作。 1)添加数据:English:45 Math:89 Computer:100 2)获取 scofield 的 English 成绩信息 图12、Redis添加和查询记录(java) 4、MongoDB数据库操作 (1)根据上面给出的文档,完成如下操作。 1)用MongoDB Shell设计出student集合。 2)用find()方法输出两个学生的信息。 Shell命令: 1.use Student   2.var stus=[{"name":"zhangsan","scores":{"English":69,"Math":86,"Computer":77}},{"name":"lisi","scores":{ "English":55,"Math":100,"Computer":88}}]   3.db.Student.insert(stus)   4.db.Student.find().pretty()  图13、MongoDB添加和查询记录 3)用find函数查询zhangsan的所有成绩(只显示 score列)。 4)修改lisi的Math 成绩,改为95。 Shell命令: db.Student.find({"name":"zhangsan"},{"_id":0,"name":0}) db.Student.update({"name":"lisi"},{"$set":{"scores.Math":95}}) 图14、MongoDB查询和修改记录 (2)根据上面已经设计出的Student集合,用MongoDB的Java客户端编程,实现如下操作: 1)添加数据:English:45 Math:89 Computer:100 2)获取scofield的所有成绩成绩信息(只显示score列) 图15、MongoDB添加和查询记录(java) 实验问题与解决

java图片显示不了package cn.game.ui; import javax.swing.*; import javax.swing.border.BevelBorder; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Random; import java.util.ArrayList; import java.awt.event.ActionEvent; public class LoginJFrame extends JFrame { static Random rand = new Random(); //准备账号的储存 static ArrayList<database> list = new ArrayList<database>(); static{ list.add(new database("zhangsan","1234","123456789112345678","12345678912")); } //验证码 static String CAPTCHA = getcaptcha(); //获取输入的信息 String USERNAME; String PASSWORD; String IDCARDNUMBER; //游戏登陆界面 public LoginJFrame() { this.setSize(603,630); //设置界面的标题 this.setTitle("登陆"); //设置界面置顶 this.setAlwaysOnTop(true); //设置界面居中 this.setLocationRelativeTo(null); this.setVisible(true); //设置关闭模式,即关闭游戏程序结束 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //取消默认居中放置,取消了才可以按XY轴方式放置组件 this.setLayout(null); //加载基本信息,用户名密码验证码 JLabel username = new JLabel("用户名"); JLabel password = new JLabel("密码"); JLabel captcha= new JLabel("验证码"); username.setBounds(160,250,100,30); username.setFont(new Font("用户名", Font.PLAIN, 24)); // 调整字体大小 this.getContentPane().add(username); password.setBounds(160,300,100,30); password.setFont(new Font("<UNK>", Font.PLAIN, 24)); this.getContentPane().add(password); captcha.setBounds(160,350,100,30); captcha.setFont(new Font("<UNK>", Font.PLAIN, 24)); this.getContentPane().add(captcha); //测试数据 // database data = new database(); // data.setUsername("123456789"); // data.setPassword("12342"); // // JLabel testlabel = new JLabel(CAPTCHA); // testlabel.setBounds(160,200,100,30); // this.getContentPane().add(testlabel); //加载白框为了输入 JTextField usernametext = new JTextField(); usernametext.setBounds(250,252,180,30); this.getContentPane().add(usernametext); JPasswordField passwordtext = new JPasswordField(); passwordtext.setBounds(250,302,180,30); this.getContentPane().add(passwordtext); JTextField captchatext = new JTextField(); captchatext.setBounds(250,352,130,30); this.getContentPane().add(captchatext); //生成验证码 JLabel captchalabel = new JLabel(getcaptcha()); captchalabel.setBounds(390,350,180,30); captchalabel.setFont(new Font(getcaptcha(), Font.PLAIN, 24)); this.getContentPane().add(captchalabel); //添加登陆和注册按钮 // JButton login = new JButton(); // login.setIcon(new ImageIcon("D:\\java\\IDEA\\code\\game\\login\\login.png")); // login.setBorderPainted(false); // login.setContentAreaFilled(false); // login.setBounds(250,400,100,30); // this.getContentPane().add(login); //加载背景图 JLabel label = new JLabel(new ImageIcon("D:\\java\\IDEA\\code\\game\\animal1\\background.png")); label.setBounds(40,10,503,560); this.getContentPane().add(label); //添加登陆和注册按钮 JButton login = new JButton(); login.setIcon(new ImageIcon("D:\\java\\IDEA\\code\\game\\animal1\\login.png")); login.setBorderPainted(false); login.setContentAreaFilled(false); login.setBounds(250,400,130,50); this.getContentPane().add(login); //获取白框的输入值 // String USERNAME = usernametext.getText(); // String PASSWORD = passwordtext.getText(); // String CAPTCHA = captchalabel.getText(); } //生产验证码 public static String getcaptcha() { String captcha = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; String number= "0123456789"; StringBuilder sb = new StringBuilder(5); for(int i = 0;i < 4;i++) { int num = rand.nextInt(captcha.length()); sb.append(captcha.charAt(num)); } int num = rand.nextInt(number.length()); int index = rand.nextInt(4); sb.insert(index,number.charAt(num)); return sb.toString(); } //判断账号是否可用 public static boolean isusername(String username) { if(username.length()<3 || username.length() > 17) { return false; } for(int i = 0;i < username.length();i++) { if(!Character.isDigit(username.charAt(i))) { return false; } } return true; } //判断身份证是否可用 public static boolean isidcardnumber(String idcardnumber) { if(idcardnumber.length()!= 18) { return false; } for(int i = 0;i < idcardnumber.length();i++) { if(!Character.isDigit(idcardnumber.charAt(i))) { return false; } } return Character.isDigit(idcardnumber.charAt(17)) && idcardnumber.charAt(17) !='x' && idcardnumber.charAt(17) != 'X'; } //判断手机号是否可用 public static boolean isphonenumber(String phonenumber) { if(phonenumber.length()!= 11) { return false; } for(int i = 0;i < phonenumber.length();i++) { if(!Character.isDigit(phonenumber.charAt(i))) { return false; } } return true; } //判断账号是否正确 public static boolean istrueusername(String username) { for(int i = 0;i < list.size();i++) { if(username.equals(list.get(i).getUsername())) { return true; } } return false; } //判断密码是否正确 public static boolean istruepassword(String password) { for(int i = 0 ;i < list.size();i++) { if(password.equals(list.get(i).getPassword())) { return true; } } return false; } //判断身份证是否正确 public static boolean istrueidcardnumber(String idcardnumber) { for(int i = 0;i < list.size();i++) { if(idcardnumber.equals(list.get(i).getIdcardnumber())) { return true; } } return false; } //判断验证码是否正确 public static boolean istruecaptcha(String captcha) { if(captcha.equals(CAPTCHA)) { return true; } return false; } //判断手机号是否正确 public static boolean istruephonenum(String phonenumber) { for(int i = 0;i < list.size();i++) { if(phonenumber.equals(list.get(i).getPhonenumber())) { return true; } } return false; } //判断是可以登陆 public static boolean islogin(String username, String password, String captcha) { if(istrueusername(username) && istruepassword(password) && istruecaptcha(captcha)) { return true; } return false; } //展示弹框 public static void showJDialog(String content) { JDialog jdialog = new JDialog(); jdialog.setSize(200,200); jdialog.setAlwaysOnTop(true); jdialog.setLocationRelativeTo(null); jdialog.setModal(true); JLabel label = new JLabel(); label.setBounds(0,0,200,150); jdialog.getContentPane().add(label); jdialog.setVisible(true); } } 为啥我的背景图和按钮不会显示出来

from pgpy import PGPKey, PGPMessage, PGPUID from pgpy.constants import ( PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm ) import warnings from cryptography.utils import CryptographyDeprecationWarning warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) # 1. 生成主密钥(签名用) master_key = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096) uid = PGPUID.new('张三', email='[email protected]') # 添加主密钥用途(认证和签名) master_key.add_uid( uid, usage={KeyFlags.Sign, KeyFlags.Certify}, hashes=[HashAlgorithm.SHA512], ciphers=[SymmetricKeyAlgorithm.AES256], compression=[CompressionAlgorithm.ZLIB] ) # 2. 生成加密子密钥 subkey = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096) # 添加子密钥到主密钥(用于加密) master_key.add_subkey( subkey, usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, expires=365*24*3600 # 1年有效期 ) # 3. 导出密钥 pubkey = master_key.pubkey private_key = master_key # 保存密钥到文件(实际操作需要密码保护) with open("master_private.asc", "w") as f: f.write(str(private_key)) with open("public_key.asc", "w") as f: f.write(str(pubkey)) # # 加密示例 # message = PGPMessage.new("机密消息", encryption_algorithm=SymmetricKeyAlgorithm.AES256) # encrypted_message = pubkey.encrypt(message) # print(f"加密后的消息:\n{encrypted_message}") # # # 解密示例(使用私钥) # decrypted_message = private_key.decrypt(encrypted_message).message # print(f"解密后的消息: {decrypted_message}") # 签名示例 signature = private_key.sign("需要签名的消息") print(f"消息签名:\n{signature}") # 验证签名 verification = pubkey.verify("需要签名的消息", signature) print(f"签名验证结果: {'有效' if verification else '无效'}") 设置一个保存密钥为testyz, 请改写程序

参考一下代码 结合以上数据 给我一个完整的运行代码import org.apache.spark.sql.{Row, SparkSession} import org.apache.spark.sql.types._ import scala.collection.mutable import java.text.SimpleDateFormat object sparkSQL01 { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .master("local") .appName("test") .config("spark.sql.shuffle.partitions", "5") .getOrCreate() /** ************************ student表结构*****************************/ val studentRDD = spark.sparkContext.textFile("data/student.txt") //创建表结构(学号,学生姓名,学生性别,学生出生年月,学生所在班级) //转换为DataFrame //生成临时表 /** ************************ teacher表结构*****************************/ val teacherRDD = spark.sparkContext.textFile("data/teacher.txt") //创建表结构(教工编号(主键),教工姓名,教工性别,教工出生年份,职称,教工所在部门) //转换为DataFrame //生成临时表 /** ************************ course表结构*****************************/ val courseRDD = spark.sparkContext.textFile("data/course.txt") //创建表结构(课程号,课程名称,教工编号) //转换为DataFrame //生成临时表 /** ************************ score表结构*****************************/ val scoreRDD = spark.sparkContext.textFile("data/score.txt") //创建表结构(学号(外键),课程号(外键),成绩) //转换为DataFrame //生成临时表 /** ************************对各表的处理*****************************/ //按照班级排序显示所有学生信息 //查询“计算机系”与“电子工程系“不同职称的教师的Tname和Prof。 //显示性别为nv的教师信息 //显示不重复的教师部门信息 //显示最高成绩 //按照班级排序显示每个班级的平均成绩 } }

最新推荐

recommend-type

Odoo与WooCommerce双向数据同步解决方案

在探讨Odoo与WooCommerce连接器模块之前,需要先了解几个关键的IT概念,比如Odoo,WooCommerce,ERP系统,以及如何将它们通过一个名为“connector-woocommerce”的Python模块整合在一起。 ### Odoo与WooCommerce的连接 **Odoo** 是一个全面的企业资源规划(ERP)软件包,用于管理企业中的所有业务流程。它包含了一系列的模块,覆盖了从会计、库存管理到电子商务和客户关系管理的各个方面。Odoo强大的模块化系统使其可以高度定制化,以适应不同企业的特定需求。 **WooCommerce** 是一个开源的电子商务解决方案,主要设计用于集成WordPress,是目前使用最广泛的电子商务平台之一。它能够提供完整的在线商店功能,并且可以通过众多插件进行扩展,以满足不同的业务需求。 ### ERP系统与电子商务的整合 在现代商务环境中,ERP系统和电子商务平台需要紧密集成。ERP系统负责内部业务流程的管理,而电子商务平台则负责与客户的直接交互,包括产品展示、订单处理、支付处理等。当两者被整合在一起时,它们可以提供无缝的工作流,例如实时库存同步、自动更新订单状态、以及统一的客户数据管理。 ### WooCommerceERPconnect **WooCommerceERPconnect**,也即“connector-woocommerce”,是一款专为连接Odoo ERP系统与WooCommerce电子商务平台设计的双向连接器。这个模块能够使得Odoo中的产品信息、订单信息、库存信息以及客户信息能够实时地同步到WooCommerce中。同样,从WooCommerce平台接收到的订单也可以实时地传输并反映到Odoo系统内。这样一来,企业可以确保他们的ERP系统和在线商店始终保持信息的一致性,极大地提高了业务效率和客户满意度。 ### 连接器的兼容性和实现方式 提到该连接器与**OpenERP 8.0** 和 **WooCommerce 2.4.x** 100% 兼容,说明开发团队在设计时考虑了特定版本间的兼容性问题,确保了连接器能够在这些版本上正常工作。考虑到Odoo是由OpenERP发展而来,它强调了此连接器是为最新版本的Odoo所设计,以确保能利用Odoo提供的最新功能。 **Python** 在这里扮演了重要的角色,因为Python是Odoo的开发语言,并且在连接器模块中也广泛使用。Python的易用性、灵活性以及丰富的库支持,使得开发者能够快速开发出功能强大的模块。该连接器模块很可能使用了Python进行后端逻辑处理,借助Odoo提供的API与WooCommerce进行数据交互。 ### 文件压缩包内容 关于提供的**connector-woocommerce-8.0** 压缩包,这显然是一个专为Odoo版本8.0设计的WooCommerce连接器。文件包内可能包括了所有必要的安装文件、配置脚本、以及可能的文档说明。安装这样的模块通常需要对Odoo有一定的了解,包括如何部署新模块,以及如何配置模块以确保其能够正确与WooCommerce通信。 ### 实施电子商务与ERP整合的考虑因素 企业实施ERP与电子商务整合时,需考虑以下因素: - **数据同步**:确保产品数据、库存数据、价格、订单信息等在Odoo和WooCommerce之间实时准确地同步。 - **安全性和稳定性**:在数据传输和处理过程中保障数据安全,并确保整合后的系统稳定运行。 - **扩展性**:随着业务的扩展,连接器需要能够适应更多的用户、更多的产品和更复杂的数据交互。 - **维护和更新**:连接器需要定期维护和更新,以适应Odoo和WooCommerce的版本迭代。 在进行整合时,可能需要进行定制开发以适应特定的业务逻辑和工作流程。这往往涉及到对Odoo或WooCommerce API的深入了解,并可能需要调整连接器的源代码以满足特殊需求。 ### 总结 通过Odoo连接器WooCommerce模块的使用,企业可以有效地整合其ERP系统与电子商务平台,实现数据的一体化管理,提高工作效率,优化客户体验。而这一切的实现,都离不开对Odoo、WooCommerce以及连接器背后的技术栈(如Python)的深入理解。
recommend-type

Linux系统运维知识大揭秘

### Linux 系统运维知识大揭秘 #### 1. 标准输入、输出与错误 在 Linux 系统中,标准输入(STDIN)、标准输出(STDOUT)和标准错误(STDERR)是非常基础且重要的概念。 |名称|默认目标|重定向使用|文件描述符编号| | ---- | ---- | ---- | ---- | |STDIN|计算机键盘|< (等同于 0<)|0| |STDOUT|计算机显示器|> (等同于 1>)|1| |STDERR|计算机显示器|2>|2| 常见的 Bash 重定向器如下: |重定向器|解释| | ---- | ---- | |> (等同于 1>)|重定向 STDOUT。
recommend-type

int arr1[4] = {1,2,3,4}; int arr2[4] = { 1,2 }; int arr[4] = {0];//所有元素为0 static int arr3[3]; int arr4[4]; cout << "arr1:"<<arr1[0] << arr1[1] << arr1[2] << arr1[3] << endl; cout << "arr2:" << arr2[0] << arr2[1] << arr2[2] << arr2[3] << endl; cout << "arr3:" << arr3[0] << arr3[1] << arr3[2] << arr3[3] << endl; cout << "arr4:" << arr4[0] << arr4[1] << arr4[2] << arr4[3] << endl;

### C++ 中数组的初始化与未初始化元素的默认值行为 在 C++ 中,数组的初始化行为取决于其类型(如内置数组、`std::array` 或 `std::vector`)以及使用的初始化语法。以下是对不同情况的详细分析。 #### 内置数组的初始化与默认值 对于内置数组(如 `int arr[10];`),如果未显式初始化,则其元素的值是未定义的。这意味着这些元素可能包含任意的垃圾值,具体取决于编译器和运行环境。例如: ```cpp int arr[10]; // 未初始化,元素值未定义 ``` 如果希望所有元素初始化为零,可以使用值初始化语法: ```cpp int arr[
recommend-type

基于Lerna和Module Federation的Micro前端架构

### 知识点一:微前端架构(microfrontend) 微前端是一种架构设计风格,它将一个大型前端应用拆分成多个较小的独立前端应用,每个独立的前端应用可以被单独开发、部署和扩展。微前端架构有助于团队的独立工作,降低了大规模项目的技术债务,提高了系统的可维护性和可扩展性。 #### 关键概念: 1. **独立自治:** 每个微前端都可以独立于整体应用进行开发、测试和部署。 2. **技术多样性:** 不同的微前端可以使用不同的前端技术栈。 3. **共享基础设施:** 为了保持一致性,微前端之间可以共享工具、框架和库。 4. **通信机制:** 微前端之间需要有通信机制来协调它们的行为。 ### 知识点二:Lerna Lerna 是一个优化了多包管理的 JavaScript 库,专用于维护具有多个包的大型JavaScript项目。Lerna 可以帮助开发者在一个仓库中管理多个包,减少重复的构建步骤,并且在包之间共享依赖。 #### 核心功能: 1. **作用域包管理:** Lerna 可以帮助开发者创建和管理仓库中的本地作用域包。 2. **自动链接:** 自动链接内部依赖,减少开发中的配置复杂性。 3. **版本管理:** 方便地处理多包项目的版本发布和变更。 4. **并行构建:** 加速构建过程,因为可以并行地构建多个包。 ### 知识点三:Module Federation Module Federation 是 Webpack 5 引入的一个实验性功能,它允许运行时从多个构建中动态加载代码。这使得在不同的前端应用之间共享模块成为可能,这是实现微前端架构的关键技术。 #### 关键特性: 1. **远程和本地模块共享:** 它不仅可以在应用程序之间共享模块,还可以在应用程序内部进行模块共享。 2. **代码分割:** 可以实现更好的代码分割和懒加载。 3. **独立部署:** 允许独立部署,由于模块是动态加载的,对应用程序的更改不需要重新部署整个应用。 4. **热模块替换:** 可以在不刷新页面的情况下替换模块。 ### 知识点四:Yarn 和 npm 包管理器 Yarn 和 npm 是 JavaScript 社区中最流行的两个包管理器,它们用于安装、更新和管理项目依赖。 #### Yarn: 1. **速度:** Yarn 在安装依赖时具有更快的速度。 2. **确定性:** 通过使用 lock 文件确保依赖安装的一致性。 3. **离线缓存:** Yarn 缓存了安装的每个包,以便在离线模式下工作。 #### npm: 1. **广泛性:** npm 是 JavaScript 社区中最广泛使用的包管理器。 2. **生态系统:** npm 拥有一个庞大且活跃的生态系统,提供了大量可用的包。 ### 知识点五:monorepo Monorepo 是一种源代码管理策略,其中所有项目代码都位于同一个仓库中。与多仓库(每个项目一个仓库)相反,monorepo 管理方式可以在整个项目的上下文中共享和管理代码。 #### monorepo 的优势: 1. **代码共享:** 项目之间可以共享代码库,便于代码复用。 2. **集中管理:** 统一的依赖管理和版本控制。 3. **项目间依赖清晰:** 项目间依赖关系透明,便于维护和开发。 ### 知识点六:工作区(Workspaces) 工作区是 monorepo 的一个重要组成部分,它允许一个仓库中包含多个包或项目。每个工作区可以有自己的 `package.json` 和依赖项,并且可以互相引用,简化了复杂项目的依赖管理。 #### 工作区特点: 1. **依赖管理:** 允许工作区依赖于仓库中的其他包。 2. **扁平化依赖:** 可以确保依赖项只被安装一次,节省了空间并减少了重复。 3. **开发流程简化:** 工作区设置简化了开发流程,允许同时工作在多个项目或包上。 ### 实际操作指令解读 1. **初始化项目:** - `yarn install` 或 `npm install`:安装依赖,根据仓库设置的不同可能包括 Lerna 或其他依赖。 2. **开发模式:** - `yarn develop` 或 `npm run develop`:启动开发服务器,对于带有预览的情况,可以使用 `WITH_PREVIEWS=1 yarn develop`。 3. **构建和启动单个远程生产版本:** - `yarn clean` 清除之前的构建。 - `yarn single:build` 单独构建生产版本。 - `yarn single:start` 启动生产服务器。 4. **构建和启动多个远程生产版本:** - `yarn multi:build` 构建多个生产版本。 - `yarn multi:start` 启动多版本生产服务器。 5. **构建镜像:** - `yarn docker:build` 使用 Yarn 构建 Docker 镜像。 以上操作指令展示了如何在使用 Lerna 和 Module Federation 的微前端 monorepo 环境下进行项目的初始化、开发、构建和部署,使用 Yarn 和 npm 工作区来优化多项目依赖管理与构建流程。
recommend-type

RHCSA实践考试及相关知识汇总

# RHCSA 实践考试及相关知识汇总 ## 一、实践考试说明 ### (一)通用注意事项 为确保考试在干净的环境中开始,需遵循以下提示: - 无需任何外部服务器或资源。 - 不要注册或连接任何外部存储库。 - 根据每个实践考试的说明安装新的虚拟机。 - 这些实践考试不提供示例解决方案,在实际考试中,你需要能够自行验证解决方案。 - 应能在两小时内完成每个考试。 ### (二)实践考试 C 内容 1. **安装虚拟机**:安装一个 RHEL 8 或 CentOS 8 虚拟机,要求如下: - 2GB 内存。 - 使用默认分区,20GB 磁盘空间。 - 一个额外的 20
recommend-type

'EOF' 现在,告诉我,eof左右俩边的标点

在 Bash 脚本或 Shell 编程中,`EOF` 通常用于 here document 语法结构中,表示一段多行文本的结束标记。在该结构中,`EOF` 左右两边的标点符号具有特定的语法意义。 ### `EOF` 左边的标点符号 `EOF` 左边通常使用 `<<` 这一组合符号作为重定向操作符,表示开始一个 here document。这一操作符紧接在命令之后,用于指示 Shell 接下来的输入将被视为输入流,直到遇到指定的结束标记(如 `EOF`)为止。例如: ```bash cat << EOF This is a test. EOF ``` 在上述示例中,`<<` 出现在 `E
recommend-type

构建智能银行聊天机器人:Watson Assistant与情绪分析

### 知识点 #### 概述 在给定的文件信息中,我们关注的是通过使用IBM Watson服务,如何构建一个银行行业的聊天机器人。该机器人整合了Watson Assistant、自然语言理解(NLU)、Tone Analyzer以及Watson Discovery服务,目的是提高客户互动体验,并能够应对常见问题解答和情绪检测等复杂场景。 #### 标题中的知识点 1. **Watson Assistant** Watson Assistant是IBM提供的一个以AI为基础的对话式客户服务工具,它允许开发者构建能够与用户进行自然语言交互的聊天机器人。Watson Assistant的核心优势在于其能够理解和预测用户的意图,并且可以学习并适应用户与之对话的方式。 2. **自然语言理解(NLU)** 自然语言理解是人工智能的一个分支,它专注于使计算机能够理解和处理人类语言。在这个项目中,NLU被用来识别和分析用户输入中的位置实体,这样机器人能够更精确地提供相关的服务或信息。 3. **Tone Analyzer服务** Tone Analyzer是IBM Watson的另一项服务,它运用情绪分析技术来检测文本中的情绪色彩。在聊天机器人应用中,通过Tone Analyzer可以判断用户的情绪状态,比如是否感到愤怒或沮丧,从而使得聊天机器人能够做出相应的反馈。 4. **聊天机器人** 聊天机器人是一种软件应用,旨在模拟人类对话,可以通过文本或语音识别,对用户的输入进行处理,并作出响应。在这里,聊天机器人应用于银行业务,以实现快速响应客户的查询和问题。 #### 描述中的知识点 1. **Node.js** Node.js是一个基于Chrome V8引擎的JavaScript运行时环境,它使得JavaScript能够用于服务器端开发。在构建聊天机器人时,Node.js可以用来创建Web UI界面,通过它可以实现用户与聊天机器人的互动。 2. **常见问题发现** 在聊天机器人的上下文中,常见问题发现指的是系统识别并回答客户经常提出的问题。这通常是通过预先设定的问题-答案对来实现的。 3. **愤怒检测** 愤怒检测是聊天机器人使用Tone Analyzer服务的一项功能,用于分析用户输入的语气,判断其是否含有负面情绪。这样机器人可以采取适当的行动,例如将对话转接给人工客服。 4. **FAQ文档中的段落检索** 在聊天机器人中,当客户的问题不能通过预设的答案解决时,需要从文档集合中检索相关信息。段落检索是一种高级搜索技术,用于从大量文档中快速找到最符合用户查询的部分。 #### 标签中的知识点 1. **IBM Cloud** IBM Cloud,先前称为Bluemix,是IBM提供的一套云计算服务,支持包括Watson服务在内的各种应用和服务的部署和运行。 2. **IBM Developer Technology** 这指的是IBM为开发者提供的技术和资源集合,其中包括IBM Watson服务和开发者可以利用的工具包。 3. **IBM Code** IBM Code是IBM倡导的开源项目和代码分享平台,旨在推动开发者社区通过共享代码实现创新。 4. **JavaScript** JavaScript是一种广泛用于网页开发的编程语言,也是Node.js的开发语言,它在构建聊天机器人时起到了前端逻辑处理的关键作用。 #### 压缩包子文件的文件名称列表中的知识点 1. **watson-banking-chatbot-master** 文件名称表明这是一个主项目文件夹,包含构建银行聊天机器人的所有源代码、资源文件及配置。"master"一词暗示这是项目的主分支或主版本。 综合以上信息,开发者将学习到如何利用IBM Watson平台提供的不同AI服务,结合Node.js来创建一个功能完善的银行服务聊天机器人。通过这个过程,开发者会掌握在IBM Cloud上部署和运行聊天机器人所需的知识和技能,同时了解到如何利用NLU服务进行实体识别,如何使用Tone Analyzer服务进行情绪分析,以及如何通过Watson Discovery服务检索FAQ相关的信息。
recommend-type

Linux技术术语全面解析

# Linux技术术语全面解析 ## 1. 基础概念 ### 1.1 变量与路径 - **$PATH**:一个变量,包含了用户输入命令时系统搜索可执行文件的目录列表。 - **.(当前目录)**:可使用`pwd`命令获取其值。 ### 1.2 文件与目录 - **绝对文件名**:完整的文件名,以根目录名开头,包含直至当前文件或目录的所有目录。 - **目录(Directory)**:文件系统中用于有组织地存储文件的文件夹。 ### 1.3 权限与访问控制 - **访问控制列表(ACL)**:在Linux权限管理中,该系统允许为多个用户和多个组授予权限,管理员还能为特定目录设置默认权限。
recommend-type

生成一组原始数据

为了生成一组适用于 LSTM 模型训练的原始时间序列数据,通常会构造一个具有周期性和随机噪声的合成数据集。例如,可以使用正弦波作为基础信号,并添加高斯噪声以模拟真实世界数据的不确定性。这种数据形式可以有效用于时间序列预测任务,尤其是在 LSTM 模型训练中。 ### 数据生成 以下是一个基于 Python 的数据生成示例,使用 NumPy 构造正弦波并添加噪声。该数据可以用于训练 LSTM 模型,以学习时间序列中的周期性模式和非线性关系[^1]。 ```python import numpy as np import matplotlib.pyplot as plt # 参数设置 se
recommend-type

现代React技术栈:热备份机箱的React Redux RxJS实践

从给定文件中可以看出,这是一个现代Web开发的实践仓库,其中涉及到了许多最新的开发工具和技术,下面我将详细解读其中的知识点。 ### 标题解析 标题 "hot-redux-chassis:现代ReactReduxRxJS应用程序使用了社区中所有最新和最伟大的东西:fire:" 暗示了该仓库是一个集成多种现代Web开发技术和工具的项目,重点强调了React, Redux, RxJS这三个主要技术点。 - **React**:一个用于构建用户界面的JavaScript库,由Facebook开发和维护。它是用于构建动态Web界面的一层视图(View),以声明式的方式实现高效的数据更新和渲染。 - **Redux**:一个用于管理Web应用状态的库,通常与React一起使用来构建单页面应用程序。Redux应用拥有一个单一的、可预测的状态容器,并且这个状态只能通过纯函数来修改,这些函数被称为“reducer”。 - **RxJS**:一个使用可观察序列进行异步编程的库。RxJS利用了可观察对象(Observables)的概念来组织异步代码,处理事件流和回调地狱等常见问题。 - **社区最新和最伟大的东西**:这里的“社区”指的是开源社区,涵盖了上述技术以及可能包括的其他新兴技术或工具。"最新"和"最伟大"指的可能是社区中认可的、新的、以及在实践中被验证为有效和强大的工具。 ### 描述解析 描述中提供了更多具体的技术信息和项目特点: - **热备份机箱**:这里可能是指项目的备份机制,确保有随时可用的生产版本。 - **Swift变化**:意味着项目正在快速且灵活地吸纳社区中流行的软件包和新想法。 - **生态系统**:表示该项目不仅仅是单一技术的运用,而是形成了一个技术生态,包含多种工具和库的结合。 - **代码粘合**:可能是指将各种技术栈结合在一起,形成一个无缝工作的整体。 - **实时生产版本**:通过特定的账户信息(admin:admin),可以访问实时部署的版本。 - **特征**:提供了项目的具体技术特征,如使用最新版本的React,下一代JavaScript(可能指的是ES6/ES2015及以上版本),模块捆绑工具(如Webpack或Rollup),无痛测试(可能指Jest测试框架),静态类型检查(TypeScript),以及代码的格式化工具。 - **RxJS**:再次强调了RxJS库在管理异步操作和副作用中的应用。 - **CSS模块**:表示项目使用了CSS模块化技术,有助于管理大型的CSS文件,并保持样式的封装和复用。 - **GitHub动作**:指出了项目已经建立了持续集成和持续部署(CI/CD)的管道,并通过GitHub Actions自动化了流程。 ### 标签解析 - **React**:标签确认了该项目使用React构建前端。 - **Redux**:标签再次确认了Redux的状态管理。 - **Flow**:Flow是一个JavaScript静态类型检查器,它允许开发者声明变量和函数的类型,进而提供代码健壮性。 - **Redux-Observable**:这是Redux中间件,它基于RxJS,用于管理复杂的异步逻辑。 - **React-Router**:用于在React应用中进行路由管理。 - **CSS-Modules**:表示该项目使用CSS模块化技术。 - **TypeScript**:一种编程语言,是JavaScript的超集,增加了静态类型检查等功能。 ### 压缩包子文件的文件名称列表 - **hot-redux-chassis-master**:这是仓库中包含的文件名称列表,表明了仓库的主要代码存储在以“hot-redux-chassis”命名的主分支(master)中。 ### 总结 这个项目是一个现代的Web开发实践示例,重点在于如何将React、Redux、RxJS以及TypeScript等技术结合在一起,形成一个功能全面且能够快速响应社区变化的Web应用。它展现了当前Web开发的某些最佳实践,例如模块化、自动化测试、静态类型检查和持续集成。此外,该项目还可以作为新项目的模板或起点,帮助开发者迅速搭建和理解这些前沿技术的结合使用。