关于Java的Byte和Integer的equals及==对比方式的问题

Byte a = 1;
Byte b = new Byte("1");
Byte c = 0x1;
System.out.println(a.equals(1));
System.out.println(a==1);
System.out.println(a.equals(b));
System.out.println(a==b);
System.out.println(c.equals(1));
System.out.println(c==1);
System.out.println("======================");
Integer i = 1;
System.out.println(i.equals(1));
System.out.println(i==1);


图片说明

如上面的代码,为什么Byte的equals不能直接跟1比?比较结果为false;而Integer却可以?

4个回答

Byte.equals方法结果为true的前提是比较双方均为Byte类型。
a.equals(1)返回值为false的原因就是不满足这个要求。

1 这个常量默认是int类型,关于这点,官方文档有说明:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

下面是这部分文字的截图:
图片说明

如果对您有帮助,请采纳答案好吗,谢谢!

/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

       * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

       /**
 * Compares this object to the specified object.  The result is
 * {@code true} if and only if the argument is not
 * {@code null} and is a {@code Byte} object that
 * contains the same {@code byte} value as this object.
 *
 * @param obj       the object to compare with
 * @return          {@code true} if the objects are the same;
 *                  {@code false} otherwise.
 */
public boolean equals(Object obj) {
    if (obj instanceof Byte) {
        return value == ((Byte)obj).byteValue();
    }
    return false;
}

    Integer的equals方法是转为int类型 ,Byte的equals是byte类型  ,1是int类型

这个问题我觉得就是说,equals()方法传入的参数是一个Object,是一个对下象,1这样的int基本类型涉及到对象层次的操作时会自动包装成Integer,
Integer和Byte两个不同的引用类型相比较肯定时返回false的,Integer可以比较的原因也在这里。

Object类中的equals方法和“==”是一样的,没有区别,而String类,Integer类等等一些类,是重写了equals方法,才使得equals和“==不同”
总之;
“==”比较的是值【变量(栈)内存中存放的对象的(堆)内存地址】
equal用于比较两个对象的值是否相同【不是比地址】但是似乎,每个被类重写的equals方法,在比较的时候,先看看是不是同一类型;
还要注意,Integer -128-127,是共享的。按Ctrl看看源码。。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
新登录的用户名怎么判断是否和已登录的用户名重名?
用户1、用户2、用户3、用户4依次登录,再登录用户2怎么判断是否重名 ![图片说明](https://img-ask.csdn.net/upload/202002/13/1581566962_929174.png) ![图片说明](https://img-ask.csdn.net/upload/202002/13/1581566977_484440.png) ``` package Pack; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; public class Test { private JFrame jf = null; private JTextField CastIPTxtFiled = new JTextField("228.9.6.8");// 组播IP地址文本框 private JTextField portTxtFiled = new JTextField("8000");// 端口地址文本框 private JTextField nameField = new JTextField("用户");// 用户名文本框 private JTextArea receiveMesArea = new JTextArea();// 接收消息文本域 private JTextArea sendMesArea = new JTextArea();// 发送消息文本域 private JButton startChatBtn = new JButton("开始聊天");// 按钮 private JButton stopChatBtn = new JButton("断开聊天"); private JButton quitBtn = new JButton("退出"); private JButton saveBtn = new JButton("保存"); private JButton cleaBtn = new JButton("清空"); private JButton sendBtn = new JButton("发送"); private JRadioButton groupchatBtn = new JRadioButton("群聊");// 单选按钮 private JRadioButton privatechatBtn = new JRadioButton("私聊"); private ButtonGroup btg = new ButtonGroup(); private JList<String> jlist = new JList<String>();// 列表框 private DefaultListModel<String> dlm = new DefaultListModel<String>();// 用dlm向jlist动态增删用户 private JScrollPane jScrollPane1 = new JScrollPane(receiveMesArea);// 滚动窗口 private JScrollPane jScrollPane2 = new JScrollPane(sendMesArea); private JScrollPane jScrollPane3 = new JScrollPane(jlist); private BroadCast broadCast = null; boolean broadCastIsDisable = true; boolean chitchat = true;// 判断是群聊还是私聊 public void InitFrame() { jf = new JFrame("组播聊天室"); jf.setLayout(null); jf.setSize(650, 530); jf.setLocationRelativeTo(null);// 在屏幕中居中显示 jf.setResizable(false);// 不可调整窗口大小 jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// 标题栏关闭按钮失效 JLabel nameJLabel = new JLabel("用户名"); nameJLabel.setBounds(30, 80, 60, 20); jf.add(nameJLabel); nameField.setBounds(80, 80, 100, 20); jf.add(nameField); JLabel portTxtJLabel = new JLabel("端口地址"); portTxtJLabel.setBounds(300, 20, 60, 20); jf.add(portTxtJLabel); portTxtFiled.setBounds(360, 20, 100, 20); jf.add(portTxtFiled); JLabel CastIPTxtJLabel = new JLabel("组播IP地址"); CastIPTxtJLabel.setBounds(10, 20, 90, 20); jf.add(CastIPTxtJLabel); CastIPTxtFiled.setBounds(80, 20, 100, 20); jf.add(CastIPTxtFiled); startChatBtn.setBounds(220, 80, 100, 20); stopChatBtn.setBounds(360, 80, 100, 20); jf.add(startChatBtn); jf.add(stopChatBtn); JLabel receiveJLabel = new JLabel("接收消息"); receiveJLabel.setBounds(20, 140, 100, 20); jScrollPane1.setBounds(20, 160, 460, 130); jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane1); jf.add(receiveJLabel); JLabel sendJLabel = new JLabel("发送消息"); sendJLabel.setBounds(20, 300, 100, 20); jScrollPane2.setBounds(20, 320, 460, 100); jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane2); jf.add(sendJLabel); jlist.setModel(dlm); jScrollPane3.setBorder(BorderFactory.createTitledBorder("在线用户列表")); jScrollPane3.setBounds(500, 20, 120, 430); jScrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane3); quitBtn.setBounds(20, 460, 100, 20); // 退出 jf.add(quitBtn); saveBtn.setBounds(140, 460, 100, 20); // 保存 jf.add(saveBtn); cleaBtn.setBounds(260, 460, 100, 20);// 清空 jf.add(cleaBtn); sendBtn.setBounds(380, 460, 100, 20); // 发送 jf.add(sendBtn); groupchatBtn.setBounds(120, 120, 100, 20); jf.add(groupchatBtn); privatechatBtn.setBounds(320, 120, 100, 20); jf.add(privatechatBtn); btg.add(groupchatBtn); btg.add(privatechatBtn); groupchatBtn.setSelected(true); jf.setVisible(true); // 显示窗口 BtnFalse(); Object1(); receiveMesArea.setEditable(false);// 接收消息文本域不能被编辑 sendBtn.setMnemonic(KeyEvent.VK_ENTER); // 给sendBtn设置快捷键(Alt+Enter) broadCast = new BroadCast(Integer.parseInt(portTxtFiled.getText()), CastIPTxtFiled.getText(), nameField.getText()); startChatBtn.addActionListener(new ButtonAction()); stopChatBtn.addActionListener(new ButtonAction()); groupchatBtn.addActionListener(new ButtonAction()); privatechatBtn.addActionListener(new ButtonAction()); quitBtn.addActionListener(new ButtonAction()); saveBtn.addActionListener(new ButtonAction()); cleaBtn.addActionListener(new ButtonAction()); sendBtn.addActionListener(new ButtonAction()); jlist.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { Object2(); } }); } public class ButtonAction implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource().equals(startChatBtn)) { jf.setTitle("当前用户:" + nameField.getText()); startChatBtn.setEnabled(false); BtnTrue(); Object2(); broadCastIsDisable = false; StartChat(); } else if (e.getSource().equals(stopChatBtn)) { jf.setTitle("组播聊天室"); startChatBtn.setEnabled(true); BtnFalse(); Object1(); broadCastIsDisable = true; broadCast.StopChat(); // 用户下线 } else if (e.getSource().equals(groupchatBtn)) { chitchat = true; Object2(); } else if (e.getSource().equals(privatechatBtn)) { chitchat = false; Object2(); } else if (e.getSource().equals(quitBtn)) { if (broadCastIsDisable == false) { broadCast.StopChat(); } System.exit(0); } else if (e.getSource().equals(saveBtn)) { try { SaveScreen(); Object2(); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource().equals(cleaBtn)) { ClearScreen(); Object2(); } else if (e.getSource().equals(sendBtn)) { if (sendMesArea.getText().equals("")) { JOptionPane.showMessageDialog(jf, "请输入需要发送的消息", "提示!!!", JOptionPane.ERROR_MESSAGE); } else { SendMessage(); sendMesArea.setText(null);// 按发送按钮,立即将发送消息文本域内容清空 } Object2(); } } } public void Object1() { nameField.requestFocusInWindow();// 将nameField设置为焦点 nameField.selectAll(); startChatBtn.getRootPane().setDefaultButton(startChatBtn);// 将startChatBtn设置为焦点,按回车相当于鼠标单击 } public void Object2() { sendMesArea.requestFocusInWindow(); } public void BtnTrue() {// 按钮可点击 stopChatBtn.setEnabled(true); sendBtn.setEnabled(true); groupchatBtn.setEnabled(true); privatechatBtn.setEnabled(true); } public void BtnFalse() {// 按钮不可点击 stopChatBtn.setEnabled(false); sendBtn.setEnabled(false); groupchatBtn.setEnabled(false); privatechatBtn.setEnabled(false); } public void StartChat() { // 用户上线开始聊天 String port = portTxtFiled.getText(); String castIp = portTxtFiled.getText(); if (!castIp.equals("") && !port.equals("")) { broadCast = new BroadCast(Integer.parseInt(portTxtFiled.getText()), CastIPTxtFiled.getText(), nameField.getText()); broadCast.start(); // 启动线程 } } public void SendMessage() { if (chitchat == true) { broadCast.SendMessage(sendMesArea.getText().toString()); } else { broadCast.SendMessage("@" + jlist.getSelectedValue() + "#" + sendMesArea.getText().toString()); } } public void SaveScreen() throws IOException { broadCast.SaveScreen(); } public void ClearScreen() { broadCast.ClearScreen(); } public static void main(String[] args) { Test client = new Test(); client.InitFrame(); } public class BroadCast extends Thread { public int port = 0; // 端口地址 String Ip = ""; // 组播IP地址 String name = ""; // 用户名 MulticastSocket multicastSocket = null; boolean StopThread = false; static final char FLAG_CHAT = '#'; static final char FLAG_PM_USER = '@'; static final char FLAG_PM_TEXT = '#'; static final char FLAG_ONLINE = '$'; static final char FLAG_OFFLINE = '&'; static final char FLAG_REQ_ONLINE = '*'; static final char FLAG_ALREADY_ONLINE = '+'; public BroadCast(int port, String Ip, String name) { this.port = port; this.Ip = Ip; this.name = name; } public void SocketSend(String data) // 发送组播消息 { try { byte[] buf = data.getBytes(); DatagramPacket datagramPacket1 = new DatagramPacket(buf, buf.length); InetAddress address = InetAddress.getByName(Ip); datagramPacket1.setAddress(address); datagramPacket1.setPort(port); multicastSocket.send(datagramPacket1); } catch (IOException e) { e.printStackTrace(); } } public void SendMessage(String message) // 发送组播消息 { SocketSend(FLAG_CHAT + this.name + ":" + message); // '#' + this.name + ":" + message } public void SendUserOnline() // 发送用户上线消息 { SocketSend(FLAG_ONLINE + this.name); // '$' + this.name } public void SendUserOffline() // 发送用户下线消息 { SocketSend(FLAG_OFFLINE + this.name); // '&' + this.name } public void ReqOnlineUser() // 请求在线用户 { SocketSend(String.valueOf(FLAG_REQ_ONLINE)); // '*' 请求在线用户 } public void SendAlreadyOnline() // 当前在线用户 { SocketSend(FLAG_ALREADY_ONLINE + this.name); // '+' + this.name } public void StopChat() { SendUserOffline(); // 发送用户下线消息 StopThread = true; // 用户下线 while (StopThread == true) { dlm.removeAllElements(); } } public void PrintMessageWT(String message) // 带时间的消息 { receiveMesArea.append("[" + GetSystemTime() + "] "); receiveMesArea.append(message); receiveMesArea.append("\n"); receiveMesArea.setCaretPosition(receiveMesArea.getText().length()); } public void SaveScreen() throws IOException { // 保存聊天记录 String msg = receiveMesArea.getText(); FileOutputStream Note = new FileOutputStream(this.name + "的聊天记录.txt"); PrintMessageWT("聊天记录保存地址:" + System.getProperty("user.dir") + "\\" + this.name + "的聊天记录.txt"); Note.write(msg.getBytes()); Note.close(); } public void ClearScreen() { receiveMesArea.setText(""); // 清空接收消息文本域内容 } public String GetSystemTime() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // 获取当前时间(格式yyyy-MM-dd HH:mm:ss) return sdf.format(new Date()); // 返回当前时间 } public void run() { // 启动线程 try { InetAddress address = InetAddress.getByName(Ip); multicastSocket = new MulticastSocket(this.port); multicastSocket.joinGroup(address); SendUserOnline(); // 发送用户上线消息 ReqOnlineUser(); // 请求在线用户 while (!StopThread) { byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); if (multicastSocket.isClosed() == false) { multicastSocket.receive(datagramPacket); String string_MS = new String(datagramPacket.getData(), 0, datagramPacket.getLength()); switch (string_MS.charAt(0)) { case (FLAG_ONLINE): // '$' string_MS = string_MS.substring(1, string_MS.length()); // 去掉第一个字符,获取用户名 // dlm.addElement(string_MS); PrintMessageWT("系统提示:" + string_MS + " 上线!"); break; case (FLAG_OFFLINE): // '&' string_MS = string_MS.substring(1, string_MS.length()); dlm.removeElement(string_MS); PrintMessageWT("系统提示:" + string_MS + " 下线!"); break; case (FLAG_REQ_ONLINE): // '*' SendAlreadyOnline(); break; case (FLAG_ALREADY_ONLINE): // '+' string_MS = string_MS.substring(1, string_MS.length()); boolean notfound = true; for (int i = 0; i < dlm.size(); i++) { if (dlm.get(i).equals(string_MS)) { notfound = false; break; } } if (notfound == true) { if (nameField.getText().equals(string_MS)) { JOptionPane.showMessageDialog(jf, "欢迎加入组播聊天室!!!", "提示!!!", JOptionPane.INFORMATION_MESSAGE); } dlm.addElement(string_MS); // receiveMesArea.append("新加入用户:" + string_MS + "\n"); // receiveMesArea.append("目前总人數:" + String.valueOf(dlm.size()) + "\n"); } } int max = dlm.size(), min = 0; int ran = (int) (Math.random() * (max - min) + min); jlist.setSelectedIndex(ran); boolean IsPM1 = false, IsPM2 = false;// 判断是否为私聊,默认不是 int num1 = 0, num2 = 0; if (string_MS.charAt(0) == FLAG_CHAT) {// '#' 判断第一个字符是否相等 string_MS = string_MS.substring(1, string_MS.length());// 去掉第一个字符 for (int i = 0; i < string_MS.length(); i++) {// 私聊,判断@和#在哪个位置,获取姓名 if (string_MS.charAt(i) == FLAG_PM_USER) { // '@' num1 = i + 1; IsPM1 = true;// 是私聊 } if (string_MS.charAt(i) == FLAG_PM_TEXT) { // '#' num2 = i; } } String Chat_UserName = string_MS.substring(num1, num2++);// 获取私聊对象的姓名 if (IsPM1 == true) {// 是私聊 String PM_SenderName = string_MS.substring(0, num1 - 2);// 获取私聊对象的姓名 if (this.name.equals(Chat_UserName)) {// 是和我私聊 PrintMessageWT("私聊消息--> " + PM_SenderName + "@我:" + string_MS.substring(num2, string_MS.length())); } else if (this.name.equals(PM_SenderName)) {// 自己发私聊消息 PrintMessageWT("私聊消息--> " + "我@" + Chat_UserName + ":" + string_MS.substring(num2, string_MS.length())); } else {// 不是和我私聊 IsPM2 = true; } } if (IsPM1 == false && IsPM2 == false) { // 不是私聊 PrintMessageWT(string_MS); } } } } } catch (Exception e) { e.printStackTrace(); } try { multicastSocket.close(); } catch (Exception e) { e.printStackTrace(); } StopThread = false; } } } ```
Socket请求第三方接口返回值有很多NUL
请求的代码 ``` public static synchronized String socketPost(String clientIp, String clientPort, String xml, String filePath) throws Exception { String rs = ""; System.out.println(xml); if (clientIp == null || "".equals(clientIp) || clientPort == null || "".equals(clientPort)) { throw new Exception("数据同步地址信息有误,请联系管理员!"); } int clientPortInt = Integer.parseInt(clientPort); logger.info("clientIp:" + clientIp + " clientPort:" + clientPort); Socket s = null; OutputStream out = null; InputStream in = null; try { s = new Socket(clientIp, clientPortInt); s.setSendBufferSize(8192); s.setReceiveBufferSize(8192); s.setTcpNoDelay(true); s.setSoTimeout(30000); s.setKeepAlive(true); out = s.getOutputStream(); in = s.getInputStream(); out.write(xml.getBytes("GBK")); out.flush(); if (in.available() > 0) { Thread.sleep(100); } //前8字节报文长度 byte[] byte8 = new byte[8]; in.read(byte8); logger.info("===========================前8字节报文长度" + new String(byte8)); Integer int8 = Integer.parseInt(new String(byte8, "GBK")); logger.info("===========================" + int8); //报文正文 byte[] byteXml = new byte[int8]; in.read(byteXml); rs = new String(byteXml, "GBK"); logger.info("===========================报文正文" + rs); //后续报文标记3位 byte[] byteEnd = new byte[3]; in.read(byteEnd); String strEnd = new String(byteEnd, "GBK"); logger.info("===========================后续报文标记3位" + strEnd); if(strEnd.equals("FIL")){ //30位文件名 byte[] byte30 = new byte[30]; in.read(byte30); String fileName = new String(byte30, "GBK").trim(); if(StringUtils.isBlank(fileName)){ fileName = UUID.randomUUID().toString()+".jpg"; } logger.info("==========================="+fileName); //前8字节文件长度 byte8 = new byte[8]; in.read(byte8); int8 = Integer.parseInt(new String(byte8,"GBK")); logger.info("==========================="+int8); //文件 byte[] byteFile = readStream(in,int8); //本地文件 File fileDir = new File(filePath); if(!fileDir.exists()||!fileDir.isDirectory()) { fileDir.mkdirs(); } File file = new File(filePath + File.separatorChar + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(byteFile); fos.flush(); fos.close(); } ``` 返回值开始的一部分数据是正常的剩下的就全是NUL ![图片说明](https://img-ask.csdn.net/upload/201912/28/1577495910_273518.jpg)
这是一个MD5加密工具类,登陆始终是失败的,我用相同的密码123456多次注册发现加密后的密码字符串都是不同的,是不是工具类有错误的原因?
``` package com.easy.demo.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; /*这是一个非常好用的使用MD5+salt加密的工具类。使用这个工具类,非常简单, 从前台拿到密码password,直接HexUtil.getEncryptedPwd(password)就可以返回一个长度为56的字符串, 可以用来保存到数据库中,相反,登录的时候,因为MD5加密是不可逆的运算,只能拿用户输入的密码走一遍MD5+salt加密之后, 跟数据库中的password比较,看是否一致,一致时密码相同,登录成功,通过调用HexUtil.validpassword(String password,String dbpassword)方法, 就可以了,不用再做其他事。*/ public class MD5Util { private final static String HEX_NUMS_STR = "0123456789ABCDEF"; private final static Integer SALT_LENGTH = 12; /** * 将16进制字符串转换成数组 * * @return byte[] * @author jacob * */ public static byte[] hexStringToByte(String hex) { /* len为什么是hex.length() / 2 ? * 首先,hex是一个字符串,里面的内容是像16进制那样的char数组 * 用2个16进制数字可以表示1个byte,所以要求得这些char[]可以转化成什么样的byte[],首先可以确定的就是长度为这个char[]的一半 */ int len = (hex.length() / 2); byte[] result = new byte[len]; char[] hexChars = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR .indexOf(hexChars[pos + 1])); } return result; } /** * 将数组转换成16进制字符串 * * @return String * @author jacob * * */ public static String byteToHexString(byte[] salt){ StringBuffer hexString = new StringBuffer(); for (int i = 0; i < salt.length; i++) { String hex = Integer.toHexString(salt[i] & 0xFF); if(hex.length() == 1){ hex = '0' + hex; } hexString.append(hex.toUpperCase()); } return hexString.toString(); } /** * 密码验证 * @param password 用户输入密码 * @param dbpassword 数据库保存的密码 * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static boolean validpassword(String password, String dbpassword) throws NoSuchAlgorithmException, UnsupportedEncodingException{ byte[] pwIndb = hexStringToByte(dbpassword); //定义salt byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwIndb, 0, salt, 0, SALT_LENGTH); //创建消息摘要对象 MessageDigest md = MessageDigest.getInstance("MD5"); //将盐数据传入消息摘要对象 md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); //声明一个对象接收数据库中的口令消息摘要 byte[] digestIndb = new byte[pwIndb.length - SALT_LENGTH]; //获得数据库中口令的摘要 System.arraycopy(pwIndb, SALT_LENGTH, digestIndb, 0,digestIndb.length); //比较根据输入口令生成的消息摘要和数据库中的口令摘要是否相同 if(Arrays.equals(digest, digestIndb)){ //口令匹配相同 return true; }else{ return false; } } /** * 获得md5之后的16进制字符 * @param password 用户输入密码字符 * @return String md5加密后密码字符 * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{ //拿到一个随机数组,作为盐 byte[] pwd = null; SecureRandom sc= new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; sc.nextBytes(salt); //声明摘要对象,并生成 MessageDigest md = MessageDigest.getInstance("MD5"); //计算MD5函数 md.update(salt); //password.getBytes("UTF-8")将输入密码变成byte数组,即将某个数装换成一个16进制数 md.update(password.getBytes("UTF-8")); //计算后获得字节数组,这就是那128位了即16个元素 byte[] digest = md.digest(); pwd = new byte[salt.length + digest.length]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); } } //controller层实现登陆的代码 @RequestMapping(value={"/login"}, method=RequestMethod.GET) public boolean login(HttpServletRequest request, @Param(value = "number")String number, @Param(value = "password")String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { password = HexUtil.getEncryptedPwd(password); User user = userMapper.loginUser(number,password); if(user != null){ return true; }else{ return false; } } ``` 密码输入多遍始终登陆失败,尝试注册相同密码发现,每次注册123456加密后的密码都不一样,是不是MD5工具类有错误?
我有md5加密工具类了,但是不会去调用,要在哪个层去调用?
![图片说明](https://img-ask.csdn.net/upload/201909/18/1568792334_186753.png) ``` package com.easy.demo.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; /*这是一个非常好用的使用MD5+salt加密的工具类。使用这个工具类,非常简单, 从前台拿到密码password,直接HexUtil.getEncryptedPwd(password)就可以返回一个长度为56的字符串, 可以用来保存到数据库中,相反,登录的时候,因为MD5加密是不可逆的运算,只能拿用户输入的密码走一遍MD5+salt加密之后, 跟数据库中的password比较,看是否一致,一致时密码相同,登录成功,通过调用HexUtil.validpassword(String password,String dbpassword)方法, 就可以了,不用再做其他事。*/ public class MD5Util { private final static String HEX_NUMS_STR = "0123456789ABCDEF"; private final static Integer SALT_LENGTH = 12; /** * 将16进制字符串转换成数组 * * @return byte[] * @author jacob * */ public static byte[] hexStringToByte(String hex) { /* len为什么是hex.length() / 2 ? * 首先,hex是一个字符串,里面的内容是像16进制那样的char数组 * 用2个16进制数字可以表示1个byte,所以要求得这些char[]可以转化成什么样的byte[],首先可以确定的就是长度为这个char[]的一半 */ int len = (hex.length() / 2); byte[] result = new byte[len]; char[] hexChars = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR .indexOf(hexChars[pos + 1])); } return result; } /** * 将数组转换成16进制字符串 * * @return String * @author jacob * * */ public static String byteToHexString(byte[] salt){ StringBuffer hexString = new StringBuffer(); for (int i = 0; i < salt.length; i++) { String hex = Integer.toHexString(salt[i] & 0xFF); if(hex.length() == 1){ hex = '0' + hex; } hexString.append(hex.toUpperCase()); } return hexString.toString(); } /** * 密码验证 * @param password 用户输入密码 * @param dbpassword 数据库保存的密码 * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static boolean validpassword(String password, String dbpassword) throws NoSuchAlgorithmException, UnsupportedEncodingException{ byte[] pwIndb = hexStringToByte(dbpassword); //定义salt byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwIndb, 0, salt, 0, SALT_LENGTH); //创建消息摘要对象 MessageDigest md = MessageDigest.getInstance("MD5"); //将盐数据传入消息摘要对象 md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); //声明一个对象接收数据库中的口令消息摘要 byte[] digestIndb = new byte[pwIndb.length - SALT_LENGTH]; //获得数据库中口令的摘要 System.arraycopy(pwIndb, SALT_LENGTH, digestIndb, 0,digestIndb.length); //比较根据输入口令生成的消息摘要和数据库中的口令摘要是否相同 if(Arrays.equals(digest, digestIndb)){ //口令匹配相同 return true; }else{ return false; } } /** * 获得md5之后的16进制字符 * @param password 用户输入密码字符 * @return String md5加密后密码字符 * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{ //拿到一个随机数组,作为盐 byte[] pwd = null; SecureRandom sc= new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; sc.nextBytes(salt); //声明摘要对象,并生成 MessageDigest md = MessageDigest.getInstance("MD5"); //计算MD5函数 md.update(salt); //password.getBytes("UTF-8")将输入密码变成byte数组,即将某个数装换成一个16进制数 md.update(password.getBytes("UTF-8")); //计算后获得字节数组,这就是那128位了即16个元素 byte[] digest = md.digest(); pwd = new byte[salt.length + digest.length]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); } } ```
nodejs 通过盐值密码校验 的java实现方式,只有这么多豆了
![图片说明](https://img-ask.csdn.net/upload/201702/22/1487757435_80246.png) 通过java来通过盐值和密码来计算校验密码,是不对的,求教错在哪里,哪位做过请指点下 nodejs的代码如下: ``` //无密码的属于第三方登陆不能拿昵称登陆 authenticate: function (plainText) { return this.password&&this.salt&&this.encryptPassword(plainText, this.salt) === this.password; }, encryptPassword: function (password, salt) { if (!password || !salt) { return ''; } salt = new Buffer(salt, 'base64'); return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64'); }, ``` 我试验的java的代码如下 ``` package com.xxshow.util; import org.apache.commons.codec.binary.Base64; import sun.misc.BASE64Decoder; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; public class PasswordEncryption { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; // public static final String PBKDF2_ALGORITHM = "SHA1"; /** * 盐的长度 */ public static final int SALT_BYTE_SIZE = 32 / 2; // public static final int SALT_BYTE_SIZE = 16 / 2; //public static final int SALT_BYTE_SIZE = 16; /** * 生成密文的长度 */ public static final int HASH_BIT_SIZE = 128 * 4; /** * 迭代次数 */ public static final int PBKDF2_ITERATIONS = 1000; /** * 对输入的密码进行验证 * * @param attemptedPassword * 待验证的密码 * @param encryptedPassword * 密文 * @param salt * 盐值 * @return 是否验证成功 * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static boolean authenticate(String attemptedPassword, String encryptedPassword, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // 用相同的盐值对用户输入的密码进行加密 String encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt); System.out.println("加密后:"+encryptedAttemptedPassword); System.out.println("base64位加密后:"); System.out.println(Base64.encodeBase64String(fromHex(encryptedAttemptedPassword))); encryptedAttemptedPassword = Base64.encodeBase64String(fromHex(encryptedAttemptedPassword)); // 把加密后的密文和原密文进行比较,相同则验证成功,否则失败 return encryptedAttemptedPassword.equals(encryptedPassword); } /** * 生成密文 * * @param password * 明文密码 * @param salt * 盐值 * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { System.out.println(new String(toHex(fromHex(salt)))); KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE); SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return toHex(f.generateSecret(spec).getEncoded()); } /** * 通过提供加密的强随机数生成器 生成盐 * * @return * @throws NoSuchAlgorithmException */ public static String generateSalt() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[SALT_BYTE_SIZE]; random.nextBytes(salt); return toHex(salt); } /** * 十六进制字符串转二进制字符串 * * @param hex the hex string * @return the hex string decoded into a byte array */ private static byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for (int i = 0; i < binary.length; i++) { binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return binary; } /** * 二进制字符串转十六进制字符串 * * @param array the byte array to convert * @return a length*2 character string encoding the byte array */ private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; } /* makeSalt: function () { return crypto.randomBytes(16).toString('base64'); }, //无密码的属于第三方登陆不能拿昵称登陆 authenticate: function (plainText) { return this.password&&this.salt&&this.encryptPassword(plainText, this.salt) === this.password; }, encryptPassword: function (password, salt) { if (!password || !salt) { return ''; } salt = new Buffer(salt, 'base64'); return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64'); * */ public static void main(String[] args) { String password = "a123"; String salt = toHex(Base64.decodeBase64("XL9yrupj+X6Z70oFNu5Iog==")); System.out.println(salt); String ciphertext = "YuhDM3R8tOIsOejI5/1beoic7Ykh633i30Grb43f5mjO8lYI6XGrWF2fcwfOH/da0f3m6JNM3JZXe+9Wtn2+Fw=="; System.out.println(ciphertext); try { boolean result = PasswordEncryption.authenticate(password, ciphertext, salt); if (result) { System.out.println("succeed"); } else { System.out.println("failed"); } } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException"); } catch (InvalidKeySpecException e) { System.out.println("InvalidKeySpecException"); } } } ```
java这个简单的服务器我要如何读取客户端的输入信息?
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Set; public class EchoServer { public static int DEFAULT_PORT = 7; public static String text=""; public static ServerSocketChannel server; public static SocketChannel client ; public static ByteBuffer output ; public static void main(String[] args){ int port; try{ port = Integer.parseInt(args[0]); }catch(RuntimeException ex){ port = DEFAULT_PORT; } System.out.println("Listening for connertions on port "+port); ServerSocketChannel serverChannel; Selector selector; try{ serverChannel = ServerSocketChannel.open(); ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); ss.bind(address); serverChannel.configureBlocking(false); selector =Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); }catch(IOException ex){ ex.printStackTrace(); return; } while(true){ try{ selector.select(); }catch(IOException ex){ ex.printStackTrace(); break; } Set<SelectionKey> readyKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = readyKeys.iterator(); while(iterator.hasNext()){ SelectionKey key = iterator.next(); iterator.remove(); try{ if(key.isAcceptable()){ ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); System.out.println("Accepted connection from "+client); client.configureBlocking(false); SelectionKey clientKey = client.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ); ByteBuffer buffer = ByteBuffer.allocate(100); clientKey.attach(buffer); } if(key.isReadable()){ client =(SocketChannel)key.channel(); output = (ByteBuffer)key.attachment(); client.read(output); output.flip(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = null; charBuffer = decoder.decode(output); text=charBuffer.toString(); //if(text.equals("time")) //{ //System.out.println("2"); Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time=format.format(date); byte b[] = time.getBytes(); //将十六进制字符串转换成十进制整数 //int i=Integer.decode(time); //创建一个大小为1的字节缓冲区因为只放一个byte值 ByteBuffer bb=ByteBuffer.allocate(1); //将十进制整数转换成二进制byte值然后存进ByteBuffer //bb.put(b); //打印ByteBuffer中的byte值 //byte []b1=bb.array(); client.write(output); // output.compact(); //} // text=output.toString(); //System.out.println(text); //output.compact(); } if(key.isWritable()){ client = (SocketChannel) key.channel(); output = (ByteBuffer)key.attachment(); //output.flip(); client.write(output); //output.compact(); } }catch(IOException ex){ key.cancel(); try{ key.channel().close(); }catch(IOException cex){} } } } } } 这是我写的,中间有点乱,因为客户在cmd访问我的服务器如果他输入time,我要给他返回时间。。。大神求助!!
java.lang.NumberFormatException: Invalid int: ""
07-08 10:18:40.743: W/System.err(32269): java.lang.NumberFormatException: Invalid int: "" 07-08 10:18:40.763: W/System.err(32269): at java.lang.Integer.invalidInt(Integer.java:138) 07-08 10:18:40.763: W/System.err(32269): at java.lang.Integer.parseInt(Integer.java:359) 07-08 10:18:40.763: W/System.err(32269): at java.lang.Integer.parseInt(Integer.java:332) 07-08 10:18:40.763: W/System.err(32269): at java.util.Calendar.getHwFirstDayOfWeek(Calendar.java:807) 07-08 10:18:40.763: W/System.err(32269): at java.util.Calendar.<init>(Calendar.java:745) 07-08 10:18:40.763: W/System.err(32269): at java.util.GregorianCalendar.<init>(GregorianCalendar.java:338) 07-08 10:18:40.763: W/System.err(32269): at java.util.GregorianCalendar.<init>(GregorianCalendar.java:314) 07-08 10:18:40.763: W/System.err(32269): at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:378) 07-08 10:18:40.763: W/System.err(32269): at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:368) 07-08 10:18:40.763: W/System.err(32269): at libcore.net.http.HttpDate$1.initialValue(HttpDate.java:38) 07-08 10:18:40.763: W/System.err(32269): at libcore.net.http.HttpDate$1.initialValue(HttpDate.java:36) 07-08 10:18:40.763: W/System.err(32269): at java.lang.ThreadLocal$Values.getAfterMiss(ThreadLocal.java:430) 07-08 10:18:40.763: W/System.err(32269): at java.lang.ThreadLocal.get(ThreadLocal.java:65) 07-08 10:18:40.763: W/System.err(32269): at libcore.net.http.HttpDate.parse(HttpDate.java:73) 07-08 10:18:40.773: W/System.err(32269): at libcore.net.http.ResponseHeaders.<init>(ResponseHeaders.java:142) 07-08 10:18:40.773: W/System.err(32269): at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:547) 07-08 10:18:40.773: W/System.err(32269): at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:784) 07-08 10:18:40.773: W/System.err(32269): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:274) 07-08 10:18:40.773: W/System.err(32269): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479) 07-08 10:18:40.773: W/System.err(32269): at com.example.uploadtest.UploadARMThread.post(UploadARMThread.java:132) 07-08 10:18:40.773: W/System.err(32269): at com.example.uploadtest.UploadARMThread.run(UploadARMThread.java:34) 以上错误发生在 int code = urlConn.getResponseCode();这一句 HttpURLConnection urlConn = null; BufferedReader br = null; try { //新建url对象 URL url = new URL(actionUrl); //通过HttpURLConnection对象,向网络地址发送请求 urlConn = (HttpURLConnection)url.openConnection(); //设置该连接允许读取 urlConn.setDoOutput(true); //设置该连接允许写入 urlConn.setDoInput(true); //设置不能适用缓存 urlConn.setUseCaches(false); //设置连接超时时间 urlConn.setConnectTimeout(3000); //设置连接超时时间 //设置读取时间 urlConn.setReadTimeout(4000); //读取超时 //设置连接方法post urlConn.setRequestMethod("POST"); //设置维持长连接 urlConn.setRequestProperty("connection", "Keep-Alive"); //设置文件字符集 urlConn.setRequestProperty("Charset", CHARSET); //设置文件类型 urlConn.setRequestProperty("Content-Type", MUTIPART_FORMDATA+";boundary="+BOUNDARY); /********************************************************************/ DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); //构建表单数据 //String entryText = bulidFormText(params); //dos.write(entryText.getBytes()); int index = 1; StringBuffer sb = new StringBuffer(""); sb.append(PREFIX+BOUNDARY+LINEND) .append("Content-Disposition: form-data;" + " name=\""+"123456"+"\";" + " filename=\""+"2222222"+"\""+LINEND) .append("Content-Type:"+CONTENTTYPE+";" + "charset="+CHARSET+LINEND) .append(LINEND); dos.write(sb.toString().getBytes()); FileInputStream fis = new FileInputStream(files); byte[] buffer = new byte[10000]; int len = 0; while ((len = fis.read(buffer)) != -1) { dos.write(buffer, 0, len); } dos.write(LINEND.getBytes()); fis.close(); //请求的结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); dos.write(end_data); dos.flush(); dos.close(); // 发送请求数据结束 //接收返回信息 int code = urlConn.getResponseCode(); if(code!=200){ urlConn.disconnect(); return code; }else{ br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String result = ""; String line = null; while((line = br.readLine())!=null){ result += line; } Log.i(Constant.TAG, result); if("true".equals(result)){ return 200; }else{ return 500; } } } catch (Exception e) { e.printStackTrace(); Log.e(Constant.TAG, e.getMessage()); return -1; }finally{ try { if(br!=null){ br.close(); } if(urlConn!=null){ urlConn.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } 这段代码在一个Thread的Run()中执行, 不在主进程
求助,java在上传文档的时候出现NullPointerException
org.hibernate.PropertyAccessException: NullPointerException occurred while calling setter of com.model.Job.hwfile org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:78) org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValue(AbstractEntityTuplizer.java:720) org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValue(AbstractEntityPersister.java:4948) com.base.dao.impl.BaseDaoImpl.updates(BaseDaoImpl.java:101) com.service.impl.BaseServiceImpl.updates(BaseServiceImpl.java:36) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:497) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) com.sun.proxy.$Proxy30.updates(Unknown Source) com.action.JobAction.updateDoc(JobAction.java:236) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:497) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:325) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) com.filter.MyStrutsFilter.doFilter(MyStrutsFilter.java:25) com.filter.SystemContextFilter.doFilter(SystemContextFilter.java:40) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) 原代码: Action类 public String updateDoc() throws IOException { if (file != null) { ActionContext ac = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); String root = request.getRealPath("/upload"); InputStream is = new FileInputStream(file); String f = fileFileName; f = UUIDUtils.create() + fileFileName; OutputStream os = new FileOutputStream(new File(root, f)); byte[] buffer = new byte[500]; int length = 0; while (-1 != (length = is.read(buffer, 0, buffer.length))) { os.write(buffer); } os.close(); is.close(); job.setHwfile("\\upload\\" + f); } jobService.updates(job);//显示这一行出错 ActionContext.getContext().put("url", "job_dataList.do"); return "redirect"; } BaseDaoImpl.java public T updates(T bean) { // 取得元数据 ClassMetadata cm = sessionFactory.getClassMetadata(getClz()); // 取得主键名称 String identifierName = cm.getIdentifierPropertyName(); // 反射取得主键值 Integer id = (Integer) getSimpleProperty(bean, identifierName); // 取得数据库中的对象 T po = findById(id); // 取得所有属性 String[] propNames = cm.getPropertyNames(); // 定义存储新值 Object newValue; for (String propName : propNames) { // 如果是主键就跳过 if (propName.equals(identifierName)) { continue; } // 反射取得新值 newValue = getSimpleProperty(bean, propName); if (newValue != null) { // 设置新值 cm.setPropertyValue(po, propName, newValue);//显示这一行出错 } } return po; } BaseServiceImpl.java: public void updates(T entity) { dao.updates(entity);//显示这一行出错 } Job实体类: private String hwfile; public String getHwfile() { return hwfile; } public void setHwfile(String hwfile) { this.hwfile = hwfile; }
java错误:Connection refused:connect
这是我主界面,我想在这点开文件,然后可以发送给连接的人,目前的测试就是自己给自己发。 package com.fastSendFile; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; public class SendWindow { // private static final SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss"); // private static Object lock1 = new Object(); private Object[] columnNames = { "用户名", "工作组","主机名","优先级", "IP地址", "port","" }; private String myName = ""; private UDP udpService; private static SendWindow sendWindow; int add =0; int count=0,flag=0; JFrame frame; File f; File file; JButton reFresh; JButton send; JButton file_btn; JButton open_file; JLabel userOnline; JLabel userCount; JCheckBox packaging; JCheckBox lock; JTable table; JTextArea inputArea; JScrollPane scrollPaneTable; JScrollPane scrollPaneFile; JSplitPane jSplitPane; JPanel panelSouth; JPanel panelSouthNorth; JPanel panelSouthSouth; JPanel panelNorth; JPanel panelNorthEast; private JFileChooser filechooser; private AddFileWindow addFileWindow; String filename = "",filePath = "",filepath=""; long fileSize = 0; int d = 0,port; public Vector fileVector = new Vector(); private void createWindow() { //分割容器 jSplitPane=new JSplitPane();//创建一个分割容器类 jSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);//设置分割线方向 jSplitPane.setDividerSize(5); jSplitPane.setDividerLocation(50);//设置分割线位于中央 //上半部分整体布局 panelNorth = new JPanel(new BorderLayout()); panelNorthEast = new JPanel(new BorderLayout()); panelNorth.add(panelNorthEast,BorderLayout.EAST); jSplitPane.setTopComponent(panelNorth); //下半部分整体布局 panelSouth = new JPanel(new BorderLayout()); panelSouthNorth = new JPanel(); panelSouthSouth = new JPanel(); inputArea = new JTextArea(); scrollPaneFile = new JScrollPane(inputArea); scrollPaneFile.setPreferredSize(new Dimension(500, 150)); scrollPaneFile.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); file_btn = new JButton(); // panelSouthNorth.add(fileName); file_btn.setVisible(false); FlowLayout flowLayout2 = new FlowLayout(FlowLayout.CENTER , 10 , 10); panelSouthSouth.setLayout(flowLayout2); panelSouth.add(file_btn,BorderLayout.NORTH); panelSouth.add(scrollPaneFile,BorderLayout.CENTER); panelSouth.add(panelSouthSouth,BorderLayout.SOUTH); jSplitPane.setBottomComponent(panelSouth); DefaultTableModel tableModel = new DefaultTableModel(null, columnNames); table = new JTable(tableModel){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; scrollPaneTable = new JScrollPane(); scrollPaneTable.setPreferredSize(new Dimension(500, 150)); //scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize()); scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //scrollPane.setBounds(new Rectangle(76, 35, 257, 193)); //table.setFillsViewportHeight(true); //panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START); panelNorth.add(scrollPaneTable,BorderLayout.WEST); // JScrollPane tableScroll = new JScrollPane(); JTableHeader header = table.getTableHeader(); header.setBounds(0, 0, 400, 20); table.setBounds(0, 20, 400, 180); DefaultTableColumnModel columnModel = (DefaultTableColumnModel) table.getColumnModel(); columnModel.removeColumn(columnModel.getColumn(6)); scrollPaneTable.setViewportView(header); scrollPaneTable.setViewportView(table); scrollPaneTable.setBounds(0, 0, 400, 200); scrollPaneTable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //scrollPaneTable = new JScrollPane(table); //scrollPaneTable.setPreferredSize(new Dimension(500, 150)); //scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize()); //scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //scrollPane.setBounds(new Rectangle(76, 35, 257, 193)); //table.setFillsViewportHeight(true); //panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START); panelNorth.add(scrollPaneTable,BorderLayout.WEST); //上半部分标签和按钮 userOnline = new JLabel("在线用户",JLabel.CENTER); userCount = new JLabel("0",JLabel.CENTER); reFresh = new JButton("刷新(R)"); panelNorthEast.add(userOnline,BorderLayout.NORTH); panelNorthEast.add(userCount,BorderLayout.CENTER); panelNorthEast.add(reFresh,BorderLayout.SOUTH); //下半部分拖拽 DropTargetAdapter kgd=new DropTargetAdapter() { @Override public void drop(DropTargetDropEvent dtde) { try { Transferable tf=dtde.getTransferable(); if(tf.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); List lt=(List)tf.getTransferData(DataFlavor.javaFileListFlavor); Iterator itor=lt.iterator(); while(itor.hasNext()) { f=(File)itor.next(); filename = f.getName(); fileSize = f.length(); filePath = f.getPath(); file_btn.setText(f.getName()); // fileName.setText(f.getPath()); //fileName.setText(f.getPath().substring(filePath.lastIndexOf("\\") + 1)); file_btn.setVisible(true); fileVector.add(f); add = 0; // flag+=1; //frame.removeAll(); // frame.repaint(); if(fileSize>0) { open_file.setEnabled(false); } } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch(Exception e) { e.printStackTrace(); } } }; new DropTarget(inputArea,DnDConstants.ACTION_COPY_OR_MOVE,kgd); file_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addFileWindow = AddFileWindow.createWindow(getInstance()); addFileWindow.frame.setVisible(true); System.out.println("file_btn:"+f.getName()+f.length()+f.getPath()); addFileWindow.showFile(f.getName(),f.length(),f.getPath()); } }); //下半部分按钮和复选按钮 open_file = new JButton("添加文件"); send = new JButton("发送(S)"); packaging = new JCheckBox("封装(E)"); packaging.setSelected(true); lock = new JCheckBox("上锁(K)"); panelSouthSouth.add(open_file); panelSouthSouth.add(send); panelSouthSouth.add(packaging); panelSouthSouth.add(lock); open_file.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { filechooser = new JFileChooser(); filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = filechooser.showDialog(null, "选择文件"); if (option == 0) { file = filechooser.getSelectedFile(); filePath = file.getPath(); file_btn.setText(file.getName()); file_btn.setVisible(true); add = 0; } } }); packaging.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(packaging.isSelected()==false) { lock.setSelected(false); lock.setEnabled(false); } } }); //整个布局 frame = new JFrame("FastSend"); frame.setSize(595, 420); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(true); frame.setContentPane(jSplitPane); jSplitPane.setDividerLocation(0.5); //frame.pack(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { try { udpService.broadcast("offline#"); } catch (IOException e) { e.printStackTrace(); } } }); reFresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.repaint(); } }); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String msg = inputArea.getText(); if(add==1) { filepath = ""; } else { filepath = filePath; } System.out.println("1111filepath:"+filepath); if ((msg != null && msg.length() > 0) || (filepath != null && filepath.length() > 0)) { List<Map<String, String>> selected = getSelected(); if (selected == null) { JOptionPane.showMessageDialog(null, "请选择发送对象!", "注意", JOptionPane.INFORMATION_MESSAGE); return; } for (Map<String, String> map : selected) { String addr = map.get("addr"); int port = Integer.parseInt(map.get("port")); try { StringBuffer sb = new StringBuffer("msg#"); sb.append(myName); msg = (msg != null && msg.length() > 0) ? msg : "null"; sb.append("#" + msg.replaceAll("#", "*")); filepath = (filepath != null && filepath.length() > 0) ? filepath : "null"; sb.append("#" + filepath); //if(addFileWindow.) udpService.send(addr, port, sb.toString()); Vector sendList = new Vector( ); sendList.add(fileVector); int[] selectRows = table.getSelectedRows(); InetAddress sendAddress; DefaultTableModel model = (DefaultTableModel) table.getModel(); // for (int i = 0; i < selectRows.length; i++) { // String addr = model.getValueAt(selectRows[i], 3).toString(); sendAddress=InetAddress.getByName( ( String ) model.getValueAt (selectRows[0] ,3 ) ); Thread clientThread=new Thread(new Client( sendList ,sendAddress)); clientThread.setPriority(6); clientThread.start(); // } } catch (IOException e1) { e1.printStackTrace(); } } inputArea.setText(null); file_btn.setVisible(false); file_btn.setText(""); sendWindow.setVisible(false); //filepath = ""; filename = ""; fileSize = 0; filePath = ""; d= 1; System.out.println("哈哈"+filepath); } else { System.out.println("wode.."); JOptionPane.showMessageDialog(null, "请输入内容或选择文件!", "注意", JOptionPane.INFORMATION_MESSAGE); } } }); } private void addRow(String userName,String hostGroup,String hostName,String Priority,String hostAddr, int hostPort) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[] { userName,hostGroup,hostName, Priority,hostAddr, hostPort }); } private void rmRow(String addr) { DefaultTableModel model = (DefaultTableModel) table.getModel(); for (int i = 0, j = table.getRowCount(); i < j; i++) { String taddr = model.getValueAt(i, 2).toString(); if (taddr.equals(addr)) { model.removeRow(i); break; } } } private List<Map<String, String>> getSelected() { int[] selectRows = table.getSelectedRows(); if (selectRows.length == 0) { return null; } List<Map<String, String>> selected = new ArrayList<Map<String, String>>(); DefaultTableModel model = (DefaultTableModel) table.getModel(); for (int i = 0; i < selectRows.length; i++) { String addr = model.getValueAt(selectRows[i], 3).toString(); port = Integer.parseInt(model.getValueAt(selectRows[i], 5).toString()); Map<String, String> map = new HashMap<String, String>(); map.put("addr", addr); map.put("port", port + ""); selected.add(map); } return selected; } public void setInpuArea(String str) { this.inputArea.setText(str); } public void setVisible(boolean b) { frame.setVisible(b); } private SendWindow() throws IOException { this.createWindow(); myName = System.getProperty("user.name"); udpService = new UDP(); ReceiveThread thread = new ReceiveThread(); thread.start(); udpService.broadcast("online#" + myName); count++; userCount.setText(count+""); frame.repaint(); // TCP.init(); } public static SendWindow getInstance() { // synchronized (lock1) { if (sendWindow == null) { try { sendWindow = new SendWindow(); } catch (IOException e) { e.printStackTrace(); } } return sendWindow; // } } class ReceiveThread extends Thread { @Override public void run() { try { while (true) { Map<String, String> recMap = udpService.receive(); if (recMap != null && recMap.size() > 0) { handlData(recMap); } } } catch (IOException e) { e.printStackTrace(); } } void handlData(Map<String, String> recMap) throws IOException { String data = recMap.get("data").trim(); String hostName = recMap.get("hostName"); String hostGroup = ""; String hostAddr = recMap.get("hostAddr"); String Priority = ""; int hostPort = Integer.parseInt(recMap.get("hostPort")); String[] dataArr = data.split("#"); if (dataArr[0].equals("online")) {// 收到上线消息后回复发消息给我的人 String userName = dataArr[1]; addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort); udpService.send(hostAddr, hostPort, "reply#" + dataArr[1]); return; } if (dataArr[0].equals("reply")) {// 更新在线table if(!hostAddr.equals(InetAddress.getLocalHost().getHostAddress())){ String userName = dataArr[1]; addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort); count++; userCount.setText(count+""); frame.repaint(); } return; } if (dataArr[0].equals("offline")) {// 下线消息,更新table rmRow(hostAddr); count--; userCount.setText(count+""); frame.repaint(); return; } if (dataArr[0].equals("msg")) {// 接收文本消息 ReceiveWindow receiveWindow = ReceiveWindow.createWindow(getInstance()); String msg = dataArr[2].equals("null") ? "":dataArr[2]; String file = dataArr[3].equals("null") ? "":dataArr[3]; System.out.println("hhfilename"+file); receiveWindow.showMsg(dataArr[1] + "/" + hostName, msg, file, hostAddr); //addFileWindow.showFile( filename,fileSize,filePath); return; } } } public static void main(String[] args) throws IOException { SendWindow sendWindow = SendWindow.getInstance(); } } 这是接收客户端,是端口选择的问题吗,我要怎么改呢T T package com.fastSendFile; import java.awt.GridLayout; import java.util.*; import java.net.*; import java.io.*; import javax.swing.*; public class Client implements Runnable { private Vector Vname=new Vector(); private InetAddress address; private Vector sendDir = new Vector(); private Vector fileVector = new Vector(); private long totalSize; private long fileSize; private String fileName; private long receivedSize; private long skipSize; SendWindow sendWindow; Client( Vector file , InetAddress address) { fileVector.addAll ( file ) ; this.address = address; } public void getFiles(File file,String lastDir ,String localPath) { if(file.isFile()) { totalSize += file.length(); sendDir.add (localPath); Vname.add(new String(lastDir + "/"+file.getName())); } else if(file.isDirectory()) { lastDir = lastDir + "/" + file.getName(); String strs[] = file.list(); for(int i = 0 ;i < strs.length; i ++) { File newfile = new File( file.getAbsolutePath() + "/" + strs[i] ); getFiles( newfile , lastDir , localPath ); } } } public void run() { totalSize = 0; String send = ""; try { byte[] buffer = new byte[1024]; Socket sendSocket = new Socket(address, 20); DataInputStream in = new DataInputStream(sendSocket.getInputStream()); BufferedOutputStream outb = new BufferedOutputStream(sendSocket.getOutputStream(),512); DataOutputStream out = new DataOutputStream(outb); ObjectOutputStream oout = new ObjectOutputStream (out); oout.writeObject ( fileVector ); oout.flush (); ObjectInputStream oin = new ObjectInputStream ( in ); Vector accVector = (Vector) oin.readObject (); if ( sendWindow.d ==1) JOptionPane.showMessageDialog(null, "消息已发送","提示",JOptionPane.DEFAULT_OPTION); for (int i = 0 ; i < accVector .size (); i ++) { File temp = (File) accVector.get ( i ); send += " " + temp.getName (); getFiles( temp ,"",temp.getParent ()); } //receive file out.writeLong(totalSize); out.flush(); int rSize; File tempFile; String tempString; long count ; JFrame frame = new JFrame(); frame.setTitle("正在发送文件"); JLabel lable1 = new JLabel(); JLabel lable2 = new JLabel(); JLabel lable3 = new JLabel(); frame.add( lable1,"North" ); frame.add( lable3,"South" ); receivedSize = 0; JProgressBar bar = new JProgressBar ( 0 , (int)(totalSize/1024)); JProgressBar bar1 = new JProgressBar (); bar.setForeground(new java.awt.Color(102, 255, 102)); bar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "\u603b\u8fdb\u5ea6", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255))); bar.setDoubleBuffered(true); bar.setStringPainted ( true ) ; bar1.setSize (320,20); bar.setSize (320,20); bar1.setForeground(new java.awt.Color(102, 255, 102)); bar1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "当前进度", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255))); bar1.setDoubleBuffered(true); bar1.setStringPainted ( true ); JPanel jp = new JPanel(); jp.setLayout ( new GridLayout( 3 , 1 )); // jp.add ( new JLabel ("总进度: ")); jp.add ( bar ); // jp.add ( new JLabel( "当前进度: " )); jp.add ( bar1 ); jp.add ( lable2 ); frame.add ( jp ); String Lmessage1 = "总共要发送: "+String.valueOf( totalSize / 1024) + " KB"; String Lmessage2 = "速度: 0"; lable1.setText( Lmessage1 ); lable2.setText( Lmessage2 ); lable3.setText ( "共" + Vname.size () + "个文件,已完成" + 0 + "个"); RandomAccessFile inFile; frame.setBounds( 250 , 200 , 400 , 200); frame.setResizable ( false ); frame.setVisible(true); long baseTime = new Date().getTime(); for(int i = 0;i < Vname.size();i++) { count = 0; lable3.setText ( "共" + Vname.size () + "个文件,已完成" + i + "个"); bar1.setMinimum ( 0 ); tempString = ( String ) Vname.get(i); tempFile = new File( sendDir.get(i) + tempString); fileSize = tempFile.length(); jp.setToolTipText ( "正发送:" + tempString.substring ( 1 ) ); out.writeLong(fileSize); int locate = new Random().nextInt ( 1000 ); byte [] fileRandom = new byte [10]; if ( tempFile.length () < 1024 ) locate = -1 ; else fileRandom = getFile( locate,tempFile ); out.writeInt ( locate ); out.write ( fileRandom ); frame.setTitle ( "正发送文件:" + tempString.substring ( 1 ) ); bar1.setMaximum ( ( int )fileSize / 1024 ); bar1.setValue ( 0 ); byte data2[] = tempString.getBytes( "UTF-8" ); out.write(data2); out.flush(); skipSize = in.readLong(); rSize = in.read(buffer); String reBack = new String(buffer,0,rSize,"UTF-8"); if("S".equals(reBack)) { receivedSize += fileSize; count = fileSize; bar.setValue ( (int) receivedSize / 1024); bar1.setValue ((int) count / 1024); continue; } else { if("C".equals(reBack)) { receivedSize += skipSize; count = skipSize; bar.setValue ( ( int )receivedSize / 1024 ); bar1.setValue ( ( int )count /1024 ); inFile = new RandomAccessFile(tempFile, "r"); inFile.seek( skipSize ); } else { inFile=new RandomAccessFile(tempFile, "r"); } while((rSize = inFile.read(buffer)) != -1) { receivedSize += rSize; count += rSize; bar.setValue ( ( int )receivedSize / 1024 ); bar1.setValue ( ( int )count / 1024 ); lable2.setText("速度: "+ String.valueOf(receivedSize * 1000 / (new Date().getTime() - baseTime + 1) / 1024 )+" KB/s"); outb.write( buffer, 0 ,rSize ); } outb.flush(); inFile.close(); } } fileSize = -1; out.writeLong(fileSize); out.writeInt ( -1 ); out.write( new byte [10]); byte data3[] = "#发送完毕#".getBytes("UTF-8"); out.write(data3); out.flush(); frame.setVisible(false); JOptionPane.showMessageDialog(null, "发送完成!","提示", JOptionPane.DEFAULT_OPTION); in.close(); out.close(); sendSocket.close(); } catch(Exception e) { JOptionPane.showMessageDialog(null, "发送文件出错l:"+e,"错误", JOptionPane.ERROR_MESSAGE); } } public static byte [] getFile( int n , File file) { byte [] b = new byte [10]; try { RandomAccessFile rf = new RandomAccessFile(file,"r"); rf.seek ( n ); rf.read ( b, 0 ,b.length); rf.close (); } catch (Exception e) { } return b; } }
在java web工程中·,利用ireport生成的jasper文件,导出pdf文件
我已经用ireport工具生成了jasper文件,并且利用ireport已经可以成功预览并生成pdf文件,但是现在需要在java web工程中,利用jasper文件生成相应的pdf文件,自己测视了好久,在网上也搜了好久,没有找到解决办法,现在把相应代码及错误贴出来,希望会做的朋友帮忙改正一下! 主要的servlet文件,在web.xml中都已将其配置好了 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import util.JDBCConnection; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.JasperRunManager; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.util.JRLoader; public class JRHTMLServlet extends HttpServlet { private Connection conn = JDBCConnection.getConnection(); //这个是连接mysql数据库 public JRHTMLServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); try { ServletContext servletContext = this.getServletContext(); File reportFile = new File(servletContext.getRealPath("/")+"/WEB-INF/report/Untitled_report_1.jasper"); Map parameters = new HashMap(); if("pdf".equals(type)){ byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, conn); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=report.pdf"); response.setContentLength(bytes.length); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(bytes, 0, bytes.length); ouputStream.flush(); ouputStream.close(); } else if ("excel".equals(type)){ JRXlsExporter exporter = new JRXlsExporter(); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); JasperPrint jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), parameters, conn); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream); exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); exporter.exportReport(); byte[] bytes = oStream.toByteArray(); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=report.xls"); response.setContentLength(bytes.length); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(bytes, 0, bytes.length); ouputStream.flush(); ouputStream.close(); } else { JRHtmlExporter exporter = new JRHtmlExporter(); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); JasperPrint jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), parameters, conn); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "utf-8"); exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, oStream); exporter.exportReport(); byte[] bytes = oStream.toByteArray(); response.setContentType("text/html"); response.setContentLength(bytes.length); response.setCharacterEncoding("utf-8"); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(bytes, 0, bytes.length); ouputStream.flush(); ouputStream.close(); } } catch (JRException jre) { System.out.println("JRException:" + jre.getMessage()); } catch (Exception e) { System.out.println("Exception:" + e.getMessage()); } finally{ try { conn.close(); } catch (SQLException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } 在jsp文件中的主要代码: <a href="JRHTMLServlet?type=pdf">Servlet中生成pdf</a> <a href="JRHTMLServlet?type=excel">Servlet中生成excel</a> <a href="JRHTMLServlet?type=html">Servlet中生成html</a> 然后编译都没有问题,在执行时,如果点击了“Servlet中生成pdf”超链接,就会提示错误: JRException:Error evaluating expression : Source text : new java.lang.Integer(1) 若点击“Servlet中生成excel”超链接,就会提示错误: 严重: Servlet.service() for servlet JRHTMLServlet threw exception java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Sheet 若点击“Servlet中生成html”超链接,就会提示错误: JRException:Error preparing statement for executing the report query : SELECT customer.`ID` AS customer_ID, customer.`USERNAME` AS customer_USERNAME, customer.`PASSWORD` AS customer_PASSWORD, customer.`REALNAME` AS customer_REALNAME, customer.`ADDRESS` AS customer_ADDRESS, customer.`MOBILE` AS customer_MOBILE, customer.`IDCARD_ID` AS customer_IDCARD_ID FROM `customer` customer 以上三种都试了,执行时,页面都可以跳转,但是跳转之后,都没有显示,直接出错了,我尝试了好久好久,确实不知道是什么问题,还请各位帮忙看看啊,在这里先谢谢你们啦 附:数据库的连接: String url = "jdbc:mysql://localhost/test"; String userName = "root"; String password = "123456"; Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, userName,password); 数据库表里面有中文,应该没有影响,现在只要求可以在web工程中导出pdf就可以了
java的rxtx串口通信怎么接收16进制数据
package Cilent; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Timer; import java.util.TimerTask; import java.util.TooManyListenersException; import javax.print.attribute.standard.PrinterMessageFromOperator; public class SendTest implements SerialPortEventListener{ protected static CommPortIdentifier portid = null; //通讯端口标识符 protected static SerialPort comPort = null; //串行端口 protected int BAUD = 9600; //波特率 protected int DATABITS = SerialPort.DATABITS_8;; //数据位 protected int STOPBITS = SerialPort.STOPBITS_1; //停止位 protected int PARITY = SerialPort.PARITY_NONE; //奇偶检验 private static OutputStream outputStream; //输出流 private static InputStream inputStream; //输入流 private static byte[] readBuffer = new byte[1024]; // 4k的buffer空间,缓存串口读入的数据 StringBuilder buf = new StringBuilder(128); public static void main(String[] args) { SendTest my = new SendTest(); my.setSerialPortNumber(); sendMsg(); } //读取所有串口 private void listPortChoices() { CommPortIdentifier portId; Enumeration en = CommPortIdentifier.getPortIdentifiers(); // iterate through the ports. while (en.hasMoreElements()) { portId = (CommPortIdentifier) en.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { System.out.println(portId.getName()); } } } //设置串口号 private void setSerialPortNumber() { String osName = null; String osname = System.getProperty("os.name", "").toLowerCase(); if (osname.startsWith("windows")) { // windows osName = "COM1"; } System.out.println(osName); try { portid = CommPortIdentifier.getPortIdentifier(osName); // portid = CommPortIdentifier.getPortIdentifier(Port); if(portid.isCurrentlyOwned()){ System.out.println("端口在使用"); }else{ comPort = (SerialPort) portid.open(this.getClass().getName(), 1000); } } catch (PortInUseException e) { System.out.println("端口被占用"); e.printStackTrace(); } catch (NoSuchPortException e) { System.out.println("端口不存在"); e.printStackTrace(); } try { inputStream = comPort.getInputStream(); //从COM1获取数据 outputStream = comPort.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } try { comPort.addEventListener(this); //给当前串口增加一个监听器 comPort.notifyOnDataAvailable(true); //当有数据是通知 } catch (TooManyListenersException e) { e.printStackTrace(); } try { //设置串口参数依次为(波特率,数据位,停止位,奇偶检验) comPort.setSerialPortParams(this.BAUD, this.DATABITS, this.STOPBITS, this.PARITY); } catch (UnsupportedCommOperationException e) { System.out.println("端口操作命令不支持"); e.printStackTrace(); } } //将输入的16进制string转成字节 public static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.equals("")) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } //向串口发送信息方法 public static void sendMsg(){ String msg="71340001";//要发送的命令msg try { outputStream.write(hexStringToBytes(msg)); } catch (IOException e) { e.printStackTrace(); } } //字节转换成十六进制字符串 public static String bytesToHexString(byte[] src){ StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } @Override public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.BI://Break interrupt,通讯中断 case SerialPortEvent.OE://Overrun error,溢位错误 case SerialPortEvent.FE://Framing error,传帧错误 case SerialPortEvent.PE://Parity error,校验错误 case SerialPortEvent.CD://Carrier detect,载波检测 case SerialPortEvent.CTS://Clear to send,清除发送 case SerialPortEvent.DSR://Data set ready,数据设备就绪 case SerialPortEvent.RI://Ring indicator,响铃指示 case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据 try { // 多次读取,将所有数据读入 while (inputStream.available() > 0) { System.out.println("接收数据:"+((byte) inputStream.read())); } } catch ( IOException e ) { e.printStackTrace(); } break; } } } 各位大神,现在做的项目是往cpld发送指令控制,发送16进制的指令需要接收cpld返回的16进制数据判断指令是否正确执行,这是按照网上的例子写的,现在解决了发送指令,但是接收部分不知道如何接收16进制的返回数据,用串口调试助手往com1发送16进制数据只能显示2位的10进制,请问如何将接收的16进制数据正确显示出来,新手实在没办法了
Android 蓝牙通信问题
安卓开发萌新。在做一个蓝牙通信的APP,现在打开蓝牙可以搜索到周围一开启蓝牙的设备,点击连接后,也会出现配对的窗口,但软件会出现闪退,不知是何问题。以下是源代码,希望各路大佬可以帮我解决一下这个问题,是否是线程未开启呢。是否是因为我已经设置与单片机通信的UUID的问题。 ``` package com.windfire; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class WindFireDemoActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ /*建立蓝牙适配器,搜索可连接设备,进行配对,*/ public static final int RECV_VIEW = 0; private BluetoothAdapter mBluetoothAdapter;//蓝牙适配器 private ArrayAdapter<String> deviceAdapter;//设备显示列表适配器 private ConnectThread connectthread; private List<String> listDevices; private ListView text;//显示需要配对设备 private Button parameterinput;//参数录入 private Button teststart;//开始测试 private Button search;//寻找设备按钮 private Button send;//发送按钮 private TextView datatest; private boolean sendflag = false; private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//蓝牙串口服务 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(android.R.style.Theme_Black_NoTitleBar); setContentView(R.layout.main); initview();//实例化 initBroadcast();//初始化广播 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//获取本地蓝牙适配器,初始化蓝牙 //是否支持蓝牙功能 if(mBluetoothAdapter == null) { Toast.makeText(WindFireDemoActivity.this, "所持设备不支持蓝牙", Toast.LENGTH_SHORT).show(); } } /************************定义广播接收,查找设备,检查配对信息,添加到listDevices中*************************/ private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction();//服务发现远程设备时 String str = ""; if(BluetoothDevice.ACTION_FOUND.equals(action))//每扫描到一个设备,系统都会发送此广播 { //从Intent中获取device信息 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取搜索到的设备信息 str = device.getName()+ ":" + device.getAddress() + "\n"; //当发现的新设备不存在于设备配对列表中时,将设备的名字和地址添加到ArrayAdapter中 if(listDevices.indexOf(str) == -1)//防止重复添加 { listDevices.add(str);//添加搜索到的设备信息 deviceAdapter.notifyDataSetChanged(); } } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(WindFireDemoActivity.this, "Discovery finished", Toast.LENGTH_SHORT).show(); } } }; /**************************************UI实例化*************************************************/ public void initview() { parameterinput =(Button)findViewById(R.id.input); teststart =(Button)findViewById(R.id.start); search =(Button)findViewById(R.id.button); send =(Button)findViewById(R.id.send); text = (ListView)findViewById(R.id.listView1); datatest = (TextView)findViewById(R.id.datatest); parameterinput.setOnClickListener(this); teststart.setOnClickListener(this); search.setOnClickListener(this); send.setOnClickListener(this); listDevices = new ArrayList<String>(); deviceAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listDevices);//列表显示listDevices的设备名称及mac text.setAdapter(deviceAdapter); text.setOnItemClickListener( new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> adapterview, View view, int position,long id) { // TODO Auto-generated method stub //绑定所选择的蓝牙MAC地址设备 String str = deviceAdapter.getItem(position); if(null == str) { Toast.makeText(getApplicationContext(), "未选中设备", Toast.LENGTH_SHORT).show(); } String mac = str.substring(str.indexOf(":")+1).trim(); BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac);//以mac去创建一个device connectthread = new ConnectThread(device); connectthread.start(); Toast.makeText(getApplicationContext(), "连接到所选设备", Toast.LENGTH_SHORT).show(); } }); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.input: Intent intent1 = new Intent(WindFireDemoActivity.this,parametershow.class); startActivity(intent1); break; case R.id.start: Intent intent2 = new Intent(WindFireDemoActivity.this,datashow.class); startActivity(intent2); break; case R.id.button: if(!mBluetoothAdapter.isEnabled()) { Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(enabler);//开启蓝牙 if (mBluetoothAdapter.isEnabled())//设置可见 { if (mBluetoothAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200); startActivity(discoverableIntent); } } } if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); Toast.makeText(getApplicationContext(), "Exit Discovery", Toast.LENGTH_SHORT).show(); } else//搜索未开始 { mBluetoothAdapter.startDiscovery();//开始搜索 Toast.makeText(getApplicationContext(), "Start Discovery", Toast.LENGTH_SHORT).show(); } break; case R.id.send: if(connectthread != null)//连接建立完成,准备发送指令开始通信 { try { sendflag = true; String str = "0x33"; connectthread.write(getHexBytes(str)); datatest.setText("send success"); } catch(Exception e) { e.printStackTrace(); } } else { Toast.makeText(WindFireDemoActivity.this, "未连接蓝牙设备", Toast.LENGTH_SHORT).show(); } break; } } /**************************************Broadcast初始化*************************************************/ public void initBroadcast(){ IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver,filter); } /**************************************连接线程*************************************************/ public class ConnectThread extends Thread { private BluetoothSocket btSocket; private InputStream in; private OutputStream out; //private BluetoothDevice btDev; public ConnectThread (BluetoothDevice device) { try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch(IOException e) { e.printStackTrace(); } } public void run() { //发现服务会减慢连接建立速度,因此关闭掉 if(mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); }//退出搜索 try { //请求连接,该操作会阻塞线程 btSocket.connect(); Toast.makeText(WindFireDemoActivity.this, "连接建立", Toast.LENGTH_SHORT).show(); in = btSocket.getInputStream(); out = btSocket.getOutputStream(); if(sendflag) { new Thread(new Runnable(){ @Override public void run(){ byte[] buffer = new byte[1024]; int bytes; try{ while((bytes = in.read(buffer)) != -1) { String str = new String(buffer,"UTF-8"); str = str.substring(0, bytes); if(str.endsWith(" ")) { datatest.append(str); continue; } Bundle bundle = new Bundle(); Message message = new Message(); bundle.putString("recv", datatest.toString()); message.what = RECV_VIEW; message.setData(bundle); handler.sendMessage(message); } } catch(IOException e) { e.printStackTrace(); } } }).start(); } } catch(IOException e){ try{ btSocket.close(); } catch(IOException e1){ e1.printStackTrace(); } e.printStackTrace(); } } public void write(byte[] bytes) { try { out.write(bytes); } catch(IOException e) { e.printStackTrace(); } } public void cancel() { try { btSocket.close(); } catch (IOException e) { } } } /******************************************Handler处理message*************************************/ private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bundle bundle = null; switch(msg.what) { case RECV_VIEW: bundle = msg.getData(); String recv = bundle.getString("recv"); datatest.append(recv+"\n"); break; default: Toast.makeText(getApplicationContext(), "接受信息失败", Toast.LENGTH_SHORT).show(); /*case NOTICE_VIEW: bundle = msg.getData(); String notice = bundle.getString("notice"); datatest.append(notice);*/ break; } } }; public byte[] getHexBytes(String message) { int len = message.length() / 2; char[] chars = message.toCharArray(); String[] hexStr = new String[len]; byte[] bytes = new byte[len]; for (int i = 0, j = 0; j < len; i += 2, j++) { hexStr[j] = "" + chars[i] + chars[i + 1]; bytes[j] = (byte) Integer.parseInt(hexStr[j], 16); } return bytes; } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } } ``` 希望尽快解答
FutureTask异常捕获问题
如题,我用用FutureTask来监视一个限时任务,但是捕获不到异常,哪位帮忙分析一下。顺便说一下我的功能:我要实现一个流媒体分发的功能,例如同一路视频要分发给不同的用户,流是通过HTTP方式发给客户端,同一路流的所有请求者放在一个LIST里面,如果不限时,当其中一个用户的网路很差的时候就会将列表中其他的用户也堵住,不符合实时流分发的要求,所以要用FutureTask来控制发送时间,如果有哪位兄弟做过类似的东西也可以给我一些意见 1.这是异常 [code="java"] java.lang.InterruptedException at java.lang.Object.wait(Native Method) at org.mortbay.io.nio.SelectChannelEndPoint.blockWritable(SelectChannelE ndPoint.java:279) at org.mortbay.jetty.AbstractGenerator$Output.blockForOutput(AbstractGen erator.java:544) at org.mortbay.jetty.AbstractGenerator$Output.flush(AbstractGenerator.ja va:571) at org.mortbay.jetty.HttpConnection$Output.flush(HttpConnection.java:101 0) at com.hisome.web.httpplayer.thread.RealCallable.call(RealCallable.java: 22) at com.hisome.web.httpplayer.thread.RealCallable.call(RealCallable.java: 13) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor. java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor .java:603) at java.lang.Thread.run(Thread.java:729) 2012-09-21 13:40:14,858 INFO httpplayer.thread.RealCallable -RealCallable write byte IOException [/code] 2.这个是RealCallable的类 [code="java"] public Integer call() throws Exception { try { if (res != null && res.getOutputStream() != null) { res.getOutputStream().write(buffer.array()); res.getOutputStream().flush(); res.flushBuffer(); } } catch (IOException e) { if (e instanceof EOFException) { log.info("RealCallable write byte IOException"); return 1; } } return 0; } [/code] 3.这个是我获取Future的结果的方法体 [code="java"] private void checkTaskResult() { int res = 0; String streamId = null; FutureTask<Integer> future = null; taskIter = taskMap.entrySet().iterator(); while (taskIter.hasNext()) { Entry<String, FutureTask<Integer>> ele = taskIter.next(); streamId = ele.getKey(); future = ele.getValue(); try { res = future.get(10, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { res = 0; } catch (ExecutionException e) { res = 0; } catch (TimeoutException e) { future.cancel(true); res = 0; } catch (CancellationException e) { res = 0; } if (res == 1) { for (StreamInviter inviter : inviters) { if (inviter.getStreamId().equals(streamId)) { inviter.setStatus(false); } } } } } [/code]
JAVA UDP协议对接C#服务器 编码方式为unicode
![图片说明](https://img-ask.csdn.net/upload/201805/27/1527390334_516365.png) ![图片说明](https://img-ask.csdn.net/upload/201805/27/1527390372_218048.png) 上面图片使用测试工具实现效果。 JAVA代码无法实现,之前可以传输来着。一觉醒了居然不行了,捣鼓一晚上。 ``` package zyb.org.UDP; import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPClient { private static final int TIMEOUT = 5000; //设置接收数据的超时时间 private static final int MAXNUM = 5; //设置重发数据的最多次数 public static void main(String args[])throws IOException{ String str_send = "Cmd=Close,Para=1|Left,EndPoint=192.168.8.102:11001"; String unicode_Str = gbEncoding(str_send); byte[] buf = new byte[1024]; //客户端在9000端口监听接收到的数据 DatagramSocket ds = new DatagramSocket(11001); InetAddress loc = InetAddress.getLocalHost(); //定义用来发送数据的DatagramPacket实例 DatagramPacket dp_send= new DatagramPacket(unicode_Str.getBytes(),unicode_Str.length(),loc,11003); //定义用来接收数据的DatagramPacket实例 DatagramPacket dp_receive = new DatagramPacket(buf, 1024); //数据发向本地3000端口 ds.setSoTimeout(TIMEOUT); //设置接收数据时阻塞的最长时间 int tries = 0; //重发数据的次数 boolean receivedResponse = false; //是否接收到数据的标志位 //直到接收到数据,或者重发次数达到预定值,则退出循环 while(!receivedResponse && tries<MAXNUM){ //发送数据 ds.send(dp_send); try{ //接收从服务端发送回来的数据 ds.receive(dp_receive); //如果接收到的数据不是来自目标地址,则抛出异常 if(!dp_receive.getAddress().equals(loc)){ throw new IOException("Received packet from an umknown source"); } //如果接收到数据。则将receivedResponse标志位改为true,从而退出循环 receivedResponse = true; }catch(InterruptedIOException e){ //如果接收数据时阻塞超时,重发并减少一次重发的次数 tries += 1; System.out.println("Time out," + (MAXNUM - tries) + " more tries..." ); } } if(receivedResponse){ //如果收到数据,则打印出来 System.out.println("client received data from server:"); String str_receive = new String(dp_receive.getData(),0,dp_receive.getLength()) + " from " + dp_receive.getAddress().getHostAddress() + ":" + dp_receive.getPort(); System.out.println(str_receive); //由于dp_receive在接收了数据之后,其内部消息长度值会变为实际接收的消息的字节数, //所以这里要将dp_receive的内部消息长度重新置为1024 dp_receive.setLength(1024); }else{ //如果重发MAXNUM次数据后,仍未获得服务器发送回来的数据,则打印如下信息 System.out.println("No response -- give up."); } ds.close(); } /* * 中文转unicode编码 */ public static String gbEncoding(final String gbString) { char[] utfBytes = gbString.toCharArray(); String unicodeBytes = ""; for (int i = 0; i < utfBytes.length; i++) { String hexB = Integer.toHexString(utfBytes[i]); if (hexB.length() <= 2) { hexB = "00" + hexB; } unicodeBytes = unicodeBytes + "\\u" + hexB; } return unicodeBytes; } /* * unicode编码转中文 */ public static String decodeUnicode(final String dataStr) { int start = 0; int end = 0; final StringBuffer buffer = new StringBuffer(); while (start > -1) { end = dataStr.indexOf("\\u", start + 2); String charStr = ""; if (end == -1) { charStr = dataStr.substring(start + 2, dataStr.length()); } else { charStr = dataStr.substring(start + 2, end); } char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。 buffer.append(new Character(letter).toString()); start = end; } return buffer.toString(); } } ```
java做易宝支付,所有银行支付通道关闭!
![图片说明](https://img-ask.csdn.net/upload/201906/04/1559649020_753493.jpg) ``` (PaymentUtil工具类) public class PaymentUtil { private static String encodingCharset = "UTF-8"; /** * 生成hmac方法 * * @param p0_Cmd 业务类型 * @param p1_MerId 商户编号 * @param p2_Order 商户订单号 * @param p3_Amt 支付金额 * @param p4_Cur 交易币种 * @param p5_Pid 商品名称 * @param p6_Pcat 商品种类 * @param p7_Pdesc 商品描述 * @param p8_Url 商户接收支付成功数据的地址 * @param p9_SAF 送货地址 * @param pa_MP 商户扩展信息 * @param pd_FrpId 银行编码 * @param pr_NeedResponse 应答机制 * @param keyValue 商户密钥(公司密钥) * @return */ //此方法把原文参数全部放入StringBuilder封装数据 public static String buildHmac(String p0_Cmd,String p1_MerId, String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat, String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId, String pr_NeedResponse,String keyValue) { StringBuilder sValue = new StringBuilder(); // 业务类型 sValue.append(p0_Cmd); // 商户编号 sValue.append(p1_MerId); // 商户订单号 sValue.append(p2_Order); // 支付金额 sValue.append(p3_Amt); // 交易币种 sValue.append(p4_Cur); // 商品名称 sValue.append(p5_Pid); // 商品种类 sValue.append(p6_Pcat); // 商品描述 sValue.append(p7_Pdesc); // 商户接收支付成功数据的地址 sValue.append(p8_Url); // 送货地址 sValue.append(p9_SAF); // 商户扩展信息 sValue.append(pa_MP); // 银行编码 sValue.append(pd_FrpId); // 应答机制 sValue.append(pr_NeedResponse); //调用易宝工具类加密算法,对所有原文进行加密,返回密文(公司密钥) return PaymentUtil.hmacSign(sValue.toString(), keyValue); } /** * 返回校验hmac方法 * * @param hmac 支付网关发来的加密验证码 * @param p1_MerId 商户编号 * @param r0_Cmd 业务类型 * @param r1_Code 支付结果 * @param r2_TrxId 易宝支付交易流水号 * @param r3_Amt 支付金额 * @param r4_Cur 交易币种 * @param r5_Pid 商品名称 * @param r6_Order 商户订单号 * @param r7_Uid 易宝支付会员ID * @param r8_MP 商户扩展信息 * @param r9_BType 交易结果返回类型 * @param keyValue 密钥 * @return */ public static boolean verifyCallback(String hmac, String p1_MerId, String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt, String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid, String r8_MP, String r9_BType, String keyValue) { StringBuilder sValue = new StringBuilder(); // 商户编号 sValue.append(p1_MerId); // 业务类型 sValue.append(r0_Cmd); // 支付结果 sValue.append(r1_Code); // 易宝支付交易流水号 sValue.append(r2_TrxId); // 支付金额 sValue.append(r3_Amt); // 交易币种 sValue.append(r4_Cur); // 商品名称 sValue.append(r5_Pid); // 商户订单号 sValue.append(r6_Order); // 易宝支付会员ID sValue.append(r7_Uid); // 商户扩展信息 sValue.append(r8_MP); // 交易结果返回类型 sValue.append(r9_BType); String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue); return sNewString.equals(hmac); } /** * @param aValue * @param aKey * @return */ //把原文和公司密钥传入hmacSign方法进行算法加密得到密文(字符串) public static String hmacSign(String aValue, String aKey) { byte k_ipad[] = new byte[64]; byte k_opad[] = new byte[64]; byte keyb[]; byte value[]; try { keyb = aKey.getBytes(encodingCharset); value = aValue.getBytes(encodingCharset); } catch (UnsupportedEncodingException e) { keyb = aKey.getBytes(); value = aValue.getBytes(); } Arrays.fill(k_ipad, keyb.length, 64, (byte) 54); Arrays.fill(k_opad, keyb.length, 64, (byte) 92); for (int i = 0; i < keyb.length; i++) { k_ipad[i] = (byte) (keyb[i] ^ 0x36); k_opad[i] = (byte) (keyb[i] ^ 0x5c); } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } md.update(k_ipad); md.update(value); byte dg[] = md.digest(); md.reset(); md.update(k_opad); md.update(dg, 0, 16); dg = md.digest(); return toHex(dg); } public static String toHex(byte input[]) { if (input == null) return null; StringBuffer output = new StringBuffer(input.length * 2); for (int i = 0; i < input.length; i++) { int current = input[i] & 0xff; if (current < 16) output.append("0"); output.append(Integer.toString(current, 16)); } return output.toString(); } /** * * @param args * @param key * @return */ public static String getHmac(String[] args, String key) { if (args == null || args.length == 0) { return (null); } StringBuffer str = new StringBuffer(); for (int i = 0; i < args.length; i++) { str.append(args[i]); } return (hmacSign(str.toString(), key)); } /** * @param aValue * @return */ public static String digest(String aValue) { aValue = aValue.trim(); byte value[]; try { value = aValue.getBytes(encodingCharset); } catch (UnsupportedEncodingException e) { value = aValue.getBytes(); } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } return toHex(md.digest(value)); } // public static void main(String[] args) { // System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp杩?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t")); // } } merchantInfo.properties(配置文件) p1_MerId=10001126856 keyValue=69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl responseURL=http://api.ecps.com:8080/OrderServlet?method=callback (OrderServlet) @WebServlet(urlPatterns = "/OrderServlet") public class OrderServlet extends BaseServlet { //支付,请求方法 public void pay(HttpServletRequest request,HttpServletResponse response) throws Exception{ // 接受参数 String address=request.getParameter("address"); String name=request.getParameter("name"); String telephone=request.getParameter("telephone"); String oid=request.getParameter("oid"); // 调用业务层方法,更新订单信息 ordersService.updateOrder(name,address,telephone,oid); // 组织发送支付公司需要哪些数据 String pd_FrpId = request.getParameter("pd_FrpId"); String p0_Cmd = "Buy"; String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId"); String p2_Order = oid; String p3_Amt = "0.01"; String p4_Cur = "CNY"; String p5_Pid = ""; String p6_Pcat = ""; String p7_Pdesc = ""; // 支付成功回调地址 ---- 第三方支付公司会访问、用户访问 // 第三方支付可以访问网址 String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("responseURL"); String p9_SAF = ""; String pa_MP = ""; String pr_NeedResponse = "1"; // 加密hmac 需要密钥 String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue"); // 传入回调地址 String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue); // 发送给第三方 StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?"); sb.append("p0_Cmd=").append(p0_Cmd).append("&"); sb.append("p1_MerId=").append(p1_MerId).append("&"); sb.append("p2_Order=").append(p2_Order).append("&"); sb.append("p3_Amt=").append(p3_Amt).append("&"); sb.append("p4_Cur=").append(p4_Cur).append("&"); sb.append("p5_Pid=").append(p5_Pid).append("&"); sb.append("p6_Pcat=").append(p6_Pcat).append("&"); sb.append("p7_Pdesc=").append(p7_Pdesc).append("&"); sb.append("p8_Url=").append(p8_Url).append("&"); sb.append("p9_SAF=").append(p9_SAF).append("&"); sb.append("pa_MP=").append(pa_MP).append("&"); sb.append("pd_FrpId=").append(pd_FrpId).append("&"); sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&"); sb.append("hmac=").append(hmac); // Ajax跨域请求不能使用重定向,不能使用转发 // respone.sendRedirect(sb.toString()); //把sb的数据封装到JSON响应会页面 Result re = new Result(Result.SUCCESS,"",sb.toString()); response.getWriter().print(JSONObject.fromObject(re)); // return null; } /*callBack 获取易宝数据,并做比较.数据是否有效,有效则支付成功,支付后的回调方法*/ public String callback(HttpServletRequest request,HttpServletResponse response) throws Exception{ String p1_MerId = request.getParameter("p1_MerId"); String r0_Cmd = request.getParameter("r0_Cmd"); String r1_Code = request.getParameter("r1_Code"); String r2_TrxId = request.getParameter("r2_TrxId"); String r3_Amt = request.getParameter("r3_Amt"); String r4_Cur = request.getParameter("r4_Cur"); String r5_Pid = request.getParameter("r5_Pid"); String r6_Order = request.getParameter("r6_Order"); String r7_Uid = request.getParameter("r7_Uid"); String r8_MP = request.getParameter("r8_MP"); String r9_BType = request.getParameter("r9_BType"); String rb_BankId = request.getParameter("rb_BankId"); String ro_BankOrderId = request.getParameter("ro_BankOrderId"); String rp_PayDate = request.getParameter("rp_PayDate"); String rq_CardNo = request.getParameter("rq_CardNo"); String ru_Trxtime = request.getParameter("ru_Trxtime"); // 身份校验 --- 判断是不是支付公司通知你 String hmac = request.getParameter("hmac"); String keyValue = ResourceBundle.getBundle("merchantInfo").getString( "keyValue"); // 自己对上面数据进行加密 --- 比较支付公司发过来hamc boolean isValid = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue); //判断数据是否有效 if (isValid) { // 响应数据有效 if (r9_BType.equals("1")) { // 浏览器重定向 System.out.println("111"); request.setAttribute("msg", "您的订单号为:"+r6_Order+",金额为:"+r3_Amt+"已经支付成功,等待发货~~"); } else if (r9_BType.equals("2")) { // 修改订单状态: // 服务器点对点 --- 支付公司通知你 System.out.println("付款成功!222"); // 修改订单状态 为已付款 // 回复支付公司success,如果不回复,支付公司会一直通知 response.getWriter().print("success"); } //订单状态,更新订单状态为已经付款 ordersService.updateOrderState(r6_Order); } else { // 数据无效 System.out.println("数据被篡改!"); } return "/jsp/msg.jsp"; } ```
java 通过url地址下载
public static void downloadHttpFile(String sURL,String folder, String sFilePath){ try { // HttpServletResponse response = null; // response.setHeader( "Content-Disposition", "attachment;filename=" + new String( sURL.getBytes("UTF-8"), "ISO8859-1" ) ); int nStartPos = 0; int nRead = 0; URL url = new URL(sURL); HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("HEAD"); long nEndPos = getFileSize(sURL); // File file = new File(folder); // file.mkdir(); RandomAccessFile oSavedFile = new RandomAccessFile(folder+sFilePath, "rw"); httpConnection.setRequestProperty("User-Agent", "Internet Explorer"); String sProperty = "bytes=" + nStartPos + "-"; httpConnection.setRequestProperty("RANGE", sProperty); //System.out.println(sProperty); InputStream input = httpConnection.getInputStream(); // ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] b = new byte[4*1024]; while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos ) {//((length = in.read(b, offset, 1024)) != -1) oSavedFile.write(b, 0, nRead); nStartPos += nRead; } oSavedFile.close(); httpConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取文件大小 * @param sURL * @return */ public static long getFileSize(String sURL) { int nFileLength = -1; try { String newUrl1 = sURL.substring(0,sURL.lastIndexOf("/")+1); String newUrl2 = sURL.substring(sURL.lastIndexOf("/")+1); String newurl = newUrl1 + URLEncoder.encode(newUrl2, "UTF-8"); URL url = new URL(newurl); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestProperty("User-Agent", "Internet Explorer"); httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt;NetFox)"); long connSize = httpConnection.getContentLength(); long responseCode = httpConnection.getResponseCode(); httpConnection.getInputStream(); if (responseCode >= 400) { System.err.println("Error Code : " + responseCode); return -2; // -2 represent access is error } String sHeader; for (int i = 1;; i++) { sHeader = httpConnection.getHeaderFieldKey(i); if (sHeader != null) { if (sHeader.equals("Content-Length")) { nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader)); break; } } else break; } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } //System.out.println(nFileLength); return nFileLength; } 这是我下载文件的代码。 测试url我获取的文件长度是4.7K下载下来文件格式受损,无法打开,我通过右键-另存为文件大小为28K。是不是我的获取文件大小错误了。我已经找了很多方法。都不管用,求大神帮我看看这是什么原因。
java导出excel表格多sheet问题。已有模板。附代码。
Table2是我需要的。模板中字段、数目都是确定的。不知道怎么分sheet插入。 @Service public class ReportServiceImpl implements ReportService { @Resource SummarySheetMapper summarySheetMapper; @Resource private DicService dicService; @Override public byte[] getSummarySheet(String contextPath, String year) throws IOException { List<OrgOrder> orgOrders = summarySheetMapper.getOrgOrder(); List<Services> services = summarySheetMapper.getServiceData(year); List<Dept1> dept1s = summarySheetMapper.getDept1Data(year); List<Dept2> dept2s = summarySheetMapper.getDept2Data(year); List<Entities> entitys = summarySheetMapper.getEntityData(year); List<Techs> techs = summarySheetMapper.getTechData(year); List<Icu> icu = summarySheetMapper.getIcuData(year); List<Table1> list = mergeAndSort(orgOrders, services, dept1s, dept2s, entitys, techs); List<Table2> list1 = mergeAndSort(orgOrders, icu); ListXlsReport<Table1> report = new ListXlsReport<Table1>(4, 4) { @Override protected void write(Table1 data, HSSFSheet sheet, int rowIndex, int columnBeginIndex) throws IOException { int index = columnBeginIndex; List<String> row = data.getRow(); for (String s : row) { if (s != null) XlsUtils.setCellValue(sheet, rowIndex, index, s); index++; } } }; ListXlsReport<Table2> report1 = new ListXlsReport<Table2>(4, 4){ @Override protected void write(Table2 data, HSSFSheet sheet, int rowIndex, int columnBeginIndex) throws IOException { int index = columnBeginIndex; List<String> row = data.getRow(); for (String s : row) { if (s != null) XlsUtils.setCellValue(sheet, rowIndex, index, s); index++; } } }; report.addData(list); report1.addData(list1); System.out.println(list.size()); System.out.println(list1.size()); ByteArrayOutputStream buf = new ByteArrayOutputStream(1024 * 1024 * 2); File file = new File(contextPath, "files/template/summary_sheet.xls"); if (file.isFile()) { FileInputStream template = new FileInputStream(file); try { report.build(template, buf); report1.build(template, buf); } finally { template.close(); } return buf.toByteArray(); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } private List<Table1> mergeAndSort(List<OrgOrder> orgOrders, List<Services> services, List<Dept1> dept1s, List<Dept2> dept2s, List<Entities> entitys, List<Techs> techs) { List<Table1> list = new ArrayList<>(); for (OrgOrder o : orgOrders) { Integer orgId = o.getOrgId(); Services service = find(orgId, services); Dept1 dept1 = find(orgId, dept1s); Dept2 dept2 = find(orgId, dept2s); Entities entity = find(orgId, entitys); Techs tech = find(orgId, techs); if (tech != null) { tech.setDicService(dicService); } Table1 t = new Table1(o, service, dept1, dept2, entity, tech); list.add(t); } Collections.sort(list); return list; } /*@Override public byte[] getSummarySheet1(String contextPath, String year) throws IOException { List<OrgOrder> orgOrders = summarySheetMapper.getOrgOrder(); List<Icu> icu = summarySheetMapper.getIcuData(year); List<Table2> list1 = mergeAndSort(orgOrders, icu); ListXlsReport<Table2> report1 = new ListXlsReport<Table2>(4, 4){ @Override protected void write(Table2 data, HSSFSheet sheet, int rowIndex, int columnBeginIndex) throws IOException { int index = columnBeginIndex; List<String> row = data.getRow(); for (String s : row) { if (s != null) XlsUtils.setCellValue(sheet, rowIndex, index, s); index++; } } }; report1.addData(list1); ByteArrayOutputStream buf = new ByteArrayOutputStream(1024 * 1024 * 2); File file = new File(contextPath, "files/template/summary_sheet.xls"); if (file.isFile()) { FileInputStream template = new FileInputStream(file); try { report1.build(template, buf); } finally { template.close(); } return buf.toByteArray(); } else { throw new FileNotFoundException(file.getAbsolutePath()); } }*/ private List<Table2> mergeAndSort(List<OrgOrder> orgOrders, List<Icu> icu) { List<Table2> list = new ArrayList<>(); for (OrgOrder o : orgOrders) { Integer orgId = o.getOrgId(); Icu icus = find(orgId, icu); Table2 t = new Table2(o, icus); list.add(t); } Collections.sort(list); return list; } private static <T extends OrgData> T find(Integer orgId, List<T> list) { for (T d : list) { if (orgId.equals(d.getOrgId())) { return (T) d; } } return null; } }
我是个新手,请问如何让cilent接收完毕文件后,server停止服务,谢谢
server程序: ``` package com.alex; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import com.alex.dao.BaseDAO; import com.alex.util.FileIO; import com.alex.util.MD5Util; public class Server { private int port; private String serverpath; public Server() { BaseDAO base=new BaseDAO(); port = Integer.parseInt(base.getValue("port")); serverpath = base.getValue("serverpath"); } public static void main(String[] args) { Server server=new Server(); server.start(); } public void start(){ //1建立连接 ServerSocket serverSocket=null; try{ serverSocket=new ServerSocket(port); Socket socket=null; while(true){ socket=serverSocket.accept(); OutputStream os=socket.getOutputStream(); BufferedOutputStream bos=new BufferedOutputStream(os); InputStream is=socket.getInputStream(); BufferedInputStream bis=new BufferedInputStream(is); //2返送MD5值 System.out.println("-------------------"); System.out.println("server发送md5值开始"); String md5=MD5Util.getHash(serverpath); System.out.println("MD5:"+md5); System.out.println("server发送md5值结束"); System.out.println("-------------------"); byte[] buf=md5.getBytes(); bos.write(buf); bos.flush(); //发送文件 if(bis.read()==0){ System.out.println("server开始发送文件"); FileIO.sendFile(serverpath,bos); }else{ break; } socket.close(); } System.out.println("文件验证结束"); }catch(Exception e){ e.printStackTrace(); }finally{ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` client程序 ``` package com.alex; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import com.alex.dao.BaseDAO; import com.alex.util.FileIO; import com.alex.util.MD5Util; public class Client { private String ip; private int port; private String clientpath; public Client() { BaseDAO base=new BaseDAO(); ip = base.getValue("ip"); port =Integer.parseInt(base.getValue("port")); clientpath = base.getValue("clientpath"); } public static void main(String[] args){ Client client=new Client(); client.start(); } public void start(){ Socket socket=null; try { System.out.println("IP地址:"+ip+"Port号:"+port); //1.创建连接 socket=new Socket(ip,port); InputStream is=socket.getInputStream(); BufferedInputStream bis=new BufferedInputStream(is); OutputStream os=socket.getOutputStream(); BufferedOutputStream bos=new BufferedOutputStream(os); //2.获得MD5值 byte[] buf=new byte[32]; bis.read(buf); String serverMd5=new String(buf); System.out.println(serverMd5); System.out.println("开始计算client文件MD5"); try { String clientMd5=MD5Util.getHash(clientpath); System.out.println("ClientMd5:"+clientMd5); //3.比较MD5 if(serverMd5.equals(clientMd5)){ System.out.println("文件已存在,谢谢"); }else{ //4.返回0,等待服务器发送文件过来。 bos.write(0); bos.flush(); FileIO.saveFile(clientpath, bis); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ```
安卓使用Des NoSuchProviderException
调用的时候: mPassword = DES.encrypt(null, password, "UTF-8"); encrypt方法会返回“加密失败”,报异常java.security.NoSuchProviderException: Provider not available: SunJCE,是为什么呢, 下面是Des的代码 ``` package com.shishi.utils; import java.security.Key; import javax.crypto.Cipher; /** * * * * @author vlinux * * */ public class DES { private static String strDefaultKey = "aaaa"; private Cipher encryptCipher = null; private Cipher decryptCipher = null; /** * * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] * hexStr2ByteArr(String strIn) 互为可逆的转换过程 * * @param arrB * * 需要转换的byte数组 * * @return 转换后的字符串 * * @throws Exception * * 本方法不处理任何异常,所有异常全部抛出 */ public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; // 把负数转换为正数 while (intTmp < 0) { intTmp = intTmp + 256; } // 小于0F的数需要在前面补0 if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } /** * * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) * 互为可逆的转换过程 * * @param strIn * * 需要转换的字符串 * * @return 转换后的byte数组 * * @throws Exception * * 本方法不处理任何异常,所有异常全部抛出 @ <a * href="mailto:leo841001@163.com">LiGuoQing</a> */ public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } /** * * 默认构造方法,使用默认密钥 * * @throws Exception */ public DES() throws Exception { this(strDefaultKey); } /** * * 指定密钥构造方法 * * @param strKey * * 指定的密钥 * * @throws Exception */ public DES(String strKey) throws Exception { // 如果没有指定秘钥的话,使用默认秘钥 if (strKey == null || strKey.equals("")) strKey = strDefaultKey; Key key = getKey(strKey.getBytes()); // NoPadding // PKCS5Padding encryptCipher = Cipher.getInstance("DES/ECB/NoPadding", "SunJCE"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES/ECB/NoPadding", "SunJCE"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } /** * * 加密字节数组 * * @param arrB * 需加密的字节数组 * * @return 加密后的字节数组 * * @throws Exception */ public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } /** * * 加密字符串 * * * * @param strIn * * 需加密的字符串 * * @return 加 * * 密后的字符串 * * @throws Exception */ public String encrypt(String strIn, String encode) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes(encode))); } /** * * 解密字节数组 * * @param arrB * * 需解密的字节数组 * * @return 解密后的字节数组 * * @throws Exception */ public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } /** * * 解密字符串 * * * * @param strIn * * 需解密的字符串 * * @return 解密后的字符串 * * @throws Exception */ public String decrypt(String strIn, String encode) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn)), encode); } /** * * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * * * * @param arrBTmp * * 构成该字符串的字节数组 * * @return 生成的密钥 * * @throws Exception */ private Key getKey(byte[] arrBTmp) throws Exception { // 创建一个空的8位字节数组(默认值为0) byte[] arrB = new byte[8]; // 将原始字节数组转换为8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密钥 Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } /** * * DES加密 * * @param key * 使用的秘钥,传入null或是空值时使用默认秘钥 * * @param str * 待加密的明文 * * @param encode * 明文编码方式,一般为“GBK” * * @return */ public static String encrypt(String key, String str, String encode) { try { byte[] strBytes = str.getBytes(encode); byte[] newStrBytes = new byte[strBytes.length + (8 - strBytes.length % 8)]; for (int i = 0; i < newStrBytes.length; i++) { newStrBytes[i] = i < strBytes.length ? strBytes[i] : 32; }// for return new DES(key).encrypt(new String(newStrBytes, encode), encode); } catch (Exception e) { // throw new MPayException(MPayException.MPAY_DES_ERROR,"加密失败",e); return "加密失败"; }// try } /** * * DES解密 * * @param key * 使用的秘钥,传入null或是空值时使用默认秘钥 * * @param str * 待解密的密文 * * @param encode * 密文编码方式,一般为“GBK” * * @return */ public static String decrypt(String key, String str, String encode) { try { return new DES(key).decrypt(str, encode).replaceAll("\\s*$", ""); } catch (Exception e) { // throw new MPayException(MPayException.MPAY_DES_ERROR,"解密失败",e); return "解密失败"; }// try } public static void main(String[] args) throws Exception { // String str = DesUtil.encrypt("}7$#3@+1~/B\\[D&...","intf", "UTF-8"); // System.out.println("密文=" + str); // System.out.println("明文=#" + // DesUtil.decrypt("}7$#3@+1~/B\\[D&...",str, "UTF-8")+"#"); // System.out.println(DesUtil.decrypt("}7$#3@+1~/B\\[D&...","54c5b564c51868ba", // "UTF-8"));//f54c505c18c74894 54c5b564c51868ba // // System.out.println( DesUtil.decrypt("}7$#3@+1", "d40d315388d74f2d", // "GBK") ); String key = ""; String message = "23873d4a0da6f58d3863b5758c457e312015ba63f4e433a4a12b60ca79bab8347e185d6502a594989d2711e8239ed0a37f14a477140fb18593d5dafba217ba76cf1e6a5fdf0f3593ff9945ac10398f99d5f14de2d349c4914431cb11724ee801f64147ea46455215777980a12f18acc842a8545db0bfe6d739efd36f096defa1bf2b1e016b4af9f18e87a3f220da2a4741f2cb88f6a29f8293e53357b2e6f9f9b4434f4e0b76ef6a250ecc47fecde2248e419665de46fe8fa31accc171bcbb44758d3ed4d2ab6e5d3456caee683dd1a8758d3ed4d2ab6e5d7cb111627e687fd3a9634596dd187b8acc697ee8444988d6908adf9322636cf7201f575fb41823ec412eede8a8c5a5b4d2eac2b6ae6bf07ef8ba56572383d327ce8e3f64aec57b4f473c0534c91140f160acf86fa415611c65d068960831f7864eff47fcb5a2a675c1ddb1b39ea3aa047a0b9f4258a61ae8e0b4664f71df1ea1ff9945ac10398f99da4be1a7f28b5f2a"; System.out.println(DES.decrypt(key, message, "GBK")); String str = "123456.com"; System.out.println(DES.encrypt(key, str, "GBK")); } } ```
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
Linux(服务器编程):15---两种高效的事件处理模式(reactor模式、proactor模式)
前言 同步I/O模型通常用于实现Reactor模式 异步I/O模型则用于实现Proactor模式 最后我们会使用同步I/O方式模拟出Proactor模式 一、Reactor模式 Reactor模式特点 它要求主线程(I/O处理单元)只负责监听文件描述符上是否有事件发生,有的话就立即将时间通知工作线程(逻辑单元)。除此之外,主线程不做任何其他实质性的工作 读写数据,接受新的连接,以及处...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n
进程通信方式总结与盘点
​ 进程通信是指进程之间的信息交换。这里需要和进程同步做一下区分,进程同步控制多个进程按一定顺序执行,进程通信是一种手段,而进程同步是目标。从某方面来讲,进程通信可以解决进程同步问题。 ​ 首先回顾下我们前面博文中讲到的信号量机制,为了实现进程的互斥与同步,需要在进程间交换一定的信息,因此信号量机制也可以被归为进程通信的一种方式,但是也被称为低级进程通信,主要原因为: 效率低:一次只可操作少量的...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
听说了吗?阿里双11作战室竟1根网线都没有
双11不光是购物狂欢节,更是对技术的一次“大考”,对于阿里巴巴企业内部运营的基础保障技术而言,亦是如此。 回溯双11历史,这背后也经历过“小米加步枪”的阶段:作战室从随处是网线,交换机放地上的“一地狼藉”;到如今媲美5G的wifi网速,到现场却看不到一根网线;从当年使用商用AP(无线路由器),让光明顶双11当天断网一分钟,到全部使用阿里自研AP……阿里巴巴企业智能事业部工程师们提供的基础保障...
在阿里,40岁的奋斗姿势
在阿里,40岁的奋斗姿势 在阿里,什么样的年纪可以称为老呢?35岁? 在云网络,有这样一群人,他们的平均年龄接近40,却刚刚开辟职业生涯的第二战场。 他们的奋斗姿势是什么样的呢? 洛神赋 “翩若惊鸿,婉若游龙。荣曜秋菊,华茂春松。髣髴兮若轻云之蔽月,飘飖兮若流风之回雪。远而望之,皎若太阳升朝霞;迫而察之,灼若芙蕖出渌波。” 爱洛神,爱阿里云 2018年,阿里云网络产品部门启动洛神2.0升...
关于研发效能提升的思考
研发效能提升是最近比较热门的一个话题,本人根据这几年的工作心得,做了一些思考总结,由于个人深度有限,暂且抛转引入。 三要素 任何生产力的提升都离不开这三个因素:人、流程和工具,少了其中任何一个因素都无法实现。 人,即思想,也就是古人说的“道”,道不同不相为谋,是制高点,也是高层建筑的基石。 流程,即方法,也是古人说的“法”。研发效能的提升,也就是要提高投入产出比,既要增加产出,也要减...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆  每天早上8:30推送 作者| Mr.K   编辑| Emma 来源| 技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯
程序员该看的几部电影
##1、骇客帝国(1999) 概念:在线/离线,递归,循环,矩阵等 剧情简介: 不久的将来,网络黑客尼奥对这个看似正常的现实世界产生了怀疑。 他结识了黑客崔妮蒂,并见到了黑客组织的首领墨菲斯。 墨菲斯告诉他,现实世界其实是由一个名叫“母体”的计算机人工智能系统控制,人们就像他们饲养的动物,没有自由和思想,而尼奥就是能够拯救人类的救世主。 可是,救赎之路从来都不会一帆风顺,到底哪里才是真实的世界?
入职阿里5年,他如何破解“技术债”?
简介: 作者 | 都铎 作为一名技术人,你常常会听到这样的话: “先快速上线” “没时间改” “再缓一缓吧” “以后再解决” “先用临时方案处理” …… 当你埋下的坑越来越多,不知道哪天哪位同学就会踩上一颗雷。特别赞同“人最大的恐惧就是未知,当技术债可说不可见的时候,才是最让人不想解决的时候。” 作为一个程序员,我们反对复制粘贴,但是我们经常会见到相似的代码,相同的二方包,甚至整个代码...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布了 2019年国民经济报告 ,报告中指出:年末中国大陆总人口(包括31个
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
2020年的1月,我辞掉了我的第一份工作
其实,这篇文章,我应该早点写的,毕竟现在已经2月份了。不过一些其它原因,或者是我的惰性、还有一些迷茫的念头,让自己迟迟没有试着写一点东西,记录下,或者说是总结下自己前3年的工作上的经历、学习的过程。 我自己知道的,在写自己的博客方面,我的文笔很一般,非技术类的文章不想去写;另外我又是一个还比较热衷于技术的人,而平常复杂一点的东西,如果想写文章写的清楚点,是需要足够...
别低估自己的直觉,也别高估自己的智商
所有群全部吵翻天,朋友圈全部沦陷,公众号疯狂转发。这两周没怎么发原创,只发新闻,可能有人注意到了。我不是懒,是文章写了却没发,因为大家的关注力始终在这次的疫情上面,发了也没人看。当然,我...
Java坑人面试题系列: 包装类(中级难度)
Java Magazine上面有一个专门坑人的面试题系列: https://blogs.oracle.com/javamagazine/quiz-2。 这些问题的设计宗旨,主要是测试面试者对Java语言的了解程度,而不是为了用弯弯绕绕的手段把面试者搞蒙。 如果你看过往期的问题,就会发现每一个都不简单。 这些试题模拟了认证考试中的一些难题。 而 “中级(intermediate)” 和 “高级(ad
深度学习入门笔记(十八):卷积神经网络(一)
欢迎关注WX公众号:【程序员管小亮】 专栏——深度学习入门笔记 声明 1)该文章整理自网上的大牛和机器学习专家无私奉献的资料,具体引用的资料请看参考文献。 2)本文仅供学术交流,非商用。所以每一部分具体的参考资料并没有详细对应。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。 3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。 4)此属于第一版本,若有错误,还需继续修正与...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
节后首个工作日,企业们集体开晨会让钉钉挂了
By 超神经场景描述:昨天 2 月 3 日,是大部分城市号召远程工作的第一天,全国有接近 2 亿人在家开始远程办公,钉钉上也有超过 1000 万家企业活跃起来。关键词:十一出行 人脸...
Java基础知识点梳理
Java基础知识点梳理 摘要: 虽然已经在实际工作中经常与java打交道,但是一直没系统地对java这门语言进行梳理和总结,掌握的知识也比较零散。恰好利用这段时间重新认识下java,并对一些常见的语法和知识点做个总结与回顾,一方面为了加深印象,方便后面查阅,一方面为了学好java打下基础。 Java简介 java语言于1995年正式推出,最开始被命名为Oak语言,由James Gosling(詹姆
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
你也能看懂的:蒙特卡罗方法
蒙特卡罗方法,也称统计模拟方法,是1940年代中期由于科学技术的发展和电子计算机的发明,而提出的一种以概率统计理论为指导的数值计算方法。是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法 蒙特卡罗方法可以粗略地分成两类:一类是所求解的问题本身具有内在的随机性,借助计算机的运算能力可以直接模拟这种随机的过程。另一种类型是所求解问题可以转化为某种随机分布的特征数,比如随机事件出现的概率,或...
相关热词 c# 为空 判断 委托 c#记事本颜色 c# 系统默认声音 js中调用c#方法参数 c#引入dll文件报错 c#根据名称实例化 c#从邮件服务器获取邮件 c# 保存文件夹 c#代码打包引用 c# 压缩效率
立即提问