• 关于

    java null+

    的搜索结果

问题

SQLite查询报出异常

a123456678 2019-12-01 20:26:20 836 浏览量 回答数 1

回答

public class Util { public String ReadFile(String Path){ BufferedReader reader = null; String laststr = ""; try{ FileInputStream fileInputStream = new FileInputStream(Path); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); reader = new BufferedReader(inputStreamReader); String tempString = null; while((tempString = reader.readLine()) != null){ laststr += tempString; } reader.close(); }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return laststr; } } (2)Test.java: import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub String JsonContext = new Util().ReadFile("D:\\test\\apkinfo.json"); JSONArray jsonArray = JSONArray.fromObject(JsonContext); int size = jsonArray.size(); System.out.println("Size: " + size); for(int i = 0; i < size; i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println("[" + i + "]name=" + jsonObject.get("name")); System.out.println("[" + i + "]package_name=" + jsonObject.get("package_name")); System.out.println("[" + i + "]check_version=" + jsonObject.get("check_version")); } } }

蛮大人123 2019-12-02 02:40:45 0 浏览量 回答数 0

问题

使用Java编写MySQL数据库,eclipse总提示错误

爵霸 2019-12-01 19:23:05 916 浏览量 回答数 1

阿里云高校特惠,助力学生创业梦!0元体验,快速入门云计算!

学生动手场景应用,快速了解并掌握云服务器的各种新奇玩法!

问题

得到CursorIndexOutOfBoundsException的原因

吴孟桥 2019-12-01 19:49:19 917 浏览量 回答数 1

回答

import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class TestPOIP1Title { public static void main(String[] args) throws Exception { String pathname = "E:\\files\\title.xlsx"; File file = new File(pathname); InputStream in = new FileInputStream(file); //得到整个excel对象 XSSFWorkbook excel = new XSSFWorkbook(in); //获取整个excel有多少个sheet int sheets = excel.getNumberOfSheets(); //便利第一个sheet Map<String,String> colMap = new HashMap<String, String>(); for(int i = 0 ; i < sheets ; i++ ){ XSSFSheet sheet = excel.getSheetAt(i); if(sheet == null){ continue; } int mergedRegions = sheet.getNumMergedRegions(); XSSFRow row2 = sheet.getRow(0); Map<Integer,String> category = new HashMap<Integer, String>(); for(int j = 0 ; j < mergedRegions; j++ ){ CellRangeAddress rangeAddress = sheet.getMergedRegion(j); int firstRow = rangeAddress.getFirstColumn(); int lastRow = rangeAddress.getLastColumn(); category.put(rangeAddress.getFirstColumn(), rangeAddress.getLastColumn()+"-"+row2.getCell(firstRow).toString()); } //便利每一行 for( int rowNum = 1 ; rowNum <= sheet.getLastRowNum() ; rowNum++ ){ System.out.println(); XSSFRow row = sheet.getRow(rowNum); if(row == null){ continue; } short lastCellNum = row.getLastCellNum(); String cate = ""; Integer maxIndex = 0; for( int col = row.getFirstCellNum() ; col < lastCellNum ; col++ ){ XSSFCell cell = row.getCell(col); if(cell == null ){ continue; } if("".equals(cell.toString())){ continue; } int columnIndex = cell.getColumnIndex(); String string = category.get(columnIndex); if(string != null && !string.equals("")){ String[] split = string.split("-"); cate = split[1]; maxIndex = Integer.parseInt(split[0]); System.out.println(cate+"<-->"+cell.toString()); }else { //如果当前便利的列编号小于等于合并单元格的结束,说明分类还是上面的分类名称 if(columnIndex<=maxIndex){ System.out.println(cate+"<-->"+cell.toString()); }else { System.out.println("分类未知"+"<-->"+cell.toString()); } } } } } } } 运行的结果如下:

蛮大人123 2019-12-02 01:59:25 0 浏览量 回答数 0

问题

阿里云消息服务使用示例代码报空指针

hbwhypw 2019-12-01 20:10:25 1768 浏览量 回答数 0

回答

<%@ page language="java" import="java.util.*, java.sql.*" import="java.text.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> * { margin: 0; padding: 0; } body { background: url(0.jpg) no-repeat; background-position: center; margin-top: 30px; height: 500px; } #head { height: 30px; background-color: #D18B00; width: 500px; margin: 0 auto; position: relative; margin-top: 130px; margin-left: 200px; } #table { background-position: center; } <% //到数据库中判断读取出的cookie中的用户名密码是否正确 try { //创建路、人、桶三个对象 Connection conn = null; Statement stmt = null; ResultSet rs = null; //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.创建连接字符串 String url = "jdbc:mysql://localhost:3306/information"; //3.创建路 conn = DriverManager.getConnection(url, "root", ""); //4.创建人 stmt = conn.createStatement(); //增删改查 //数据库添加、更新、删除数据 //String str1="insert into book values(987,'chen',32.00)"; //String str2="update book set price=50.00 where id=123"; //删除的行数= ID out.print("已经修改的行数为:"); out.print(request.getParameter("ID")); String a = request.getParameter("ID"); String b = request.getParameter("useName"); String c = request.getParameter("password"); out.println("用户名和密码是:"+b); out.println("用户名和密码是:"+c); String str="update user set useName='"+b+"', password='"+c+"' where ID='"+a+"'"; //i代表的是受影响行数 int i = stmt.executeUpdate(str); out.print("受影响行数"+i); if(i==1){ response.sendRedirect("Update.jsp"); } else if(i==0){ response.sendRedirect("Index.jsp"); } } catch (Exception ex) { out.println(ex.toString()); } %>

蛮大人123 2019-12-02 02:38:43 0 浏览量 回答数 0

回答

我的做法是: 1、写一个过程调用类,实现ICallback接口,完整代码如下: import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import oracle.jdbc.OracleTypes; import com.jfinal.plugin.activerecord.ICallback; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.ModelBuilder; /** * 统计分析数据 * @author Administrator * */ public class ProcedureTool implements ICallback { private Object[] paras; private String procedure; private List<?> result; @SuppressWarnings("rawtypes") private Class<? extends Model> mdClass; /** * @param proc 存储过程名称及参数:如 prcName(?,?,?,?) * @param paras 输入\输出 参数,默认最后一个为游标参数 */ @SuppressWarnings("rawtypes") public void setParas(Class<? extends Model> modelClass,String proc,Object...paras){ procedure=proc; this.paras=paras; mdClass=modelClass; } /** * 结果集 * @return */ public List<?> getResultList(){ return result; } @Override public Object run(Connection conn) throws SQLException { // TODO Auto-generated method stub CallableStatement proc = null; result=null; proc = conn.prepareCall("{ call "+procedure+" }"); for (int i=0; i<paras.length; i++) { proc.setObject(i + 1, paras[i]); } proc.registerOutParameter(paras.length+1, OracleTypes.CURSOR); proc.execute(); ResultSet rs = (ResultSet) proc.getObject(paras.length+1); try { result=ModelBuilder.build(rs, mdClass); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } 2、调用getResultList就可以得到结果集了。 以上就是大概思路 南客南客 9个月前引用来自“车开源”的评论我的做法是: 1、写一个过程调用类,实现ICallback接口,如下: public class ProcedureTool implements ICallback { private Object[] paras; private String procedure; private List<?> result; @SuppressWarnings("rawtypes") private Class<? extends Model> mdClass; /** * @param proc 存储过程名称及参数:如 prcName(?,?,?,?) * @param paras 输入\输出 参数,默认最后一个为游标参数 */ @SuppressWarnings("rawtypes") public void setParas(Class<? extends Model> modelClass,String proc,Object...paras){ procedure=proc; this.paras=paras; mdClass=modelClass; } /** * 结果集 * @return */ public List<?> getResultList(){ return result; } @Override public Object run(Connection conn) throws SQLException { // TODO Auto-generated method stub CallableStatement proc = null; result=null; proc = conn.prepareCall("{ call "+procedure+" }"); for (int i=0; i<paras.length; i++) { proc.setObject(i + 1, paras[i]); } proc.registerOutParameter(paras.length+1, OracleTypes.CURSOR); proc.execute(); ResultSet rs = (ResultSet) proc.getObject(paras.length+1); try { result=ModelBuilder.build(rs, mdClass); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } 2、调用getResultList就可以得到结果集了。

小旋风柴进 2019-12-02 02:05:36 0 浏览量 回答数 0

问题

sdk手册---并发下载文件丢失

叶芝殇 2019-12-01 19:45:03 2309 浏览量 回答数 1

回答

package cn.slahser.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; /** * 代码行统计工具 * * @author xiaoE * */ public class CodeCount { /** 不统计与主程序无关文件 */ public static final Set<String> OUT_FILE; static { OUT_FILE = new HashSet<String>(); // 代码备份工具 OUT_FILE.add("CodeBackup.java"); // 代码行统计工具 OUT_FILE.add("CodeCount.java"); } /** 代码行 */ public long code; /** 注释行 */ public long doc; /** 空行 */ public long sp; private CodeCount(){} /** * 递归目录下所有的.java文件 * * @author xiaoE * @param dir 要查找的目录 * @throws Exception */ private void conuntAllFile(File dir) throws Exception { File[] childs = dir.listFiles(); for (int i = 0; i < childs.length; i++) { if(OUT_FILE.contains(childs[i].getName())) { continue; } if (childs[i].isDirectory()) { this.conuntAllFile(childs[i]); } else if (childs[i].getName().matches(".*\\.java$")) { this.countCodeInFile(childs[i]); } } } /** * 统计单个文件的 * 代码行,空行,注释行 * * @author xiaoE * @param file 要统计文件 * @throws Exception */ private void countCodeInFile(File file) throws Exception { BufferedReader br = null; boolean isComment = false; br = new BufferedReader(new FileReader(file)); String line = ""; while ((line = br.readLine()) != null) { line = line.trim(); if (line.matches("^[\\s&&[^\\n]]*$")) { // 满足正则表达式,则为空行 this.sp++; } else if (line.startsWith("/*") || isComment) { // 以「/*」开头的为注释 this.doc++; // 不以「*/」结尾,则下一行是注释 isComment = !line.endsWith("*/"); } else if (line.startsWith("//")) { // 以「//」开头的为注释 this.doc++; } else { // 其余为代码行 this.code++; } } br.close(); } public static void main(String[] args) throws Exception { CodeCount count = new CodeCount(); count.conuntAllFile(new File("src")); System.out.println("代码行:\t" + count.code); System.out.println("注释行:\t" + count.doc); System.out.println("空行:\t" + count.sp); } }

爵霸 2019-12-02 02:39:46 0 浏览量 回答数 0

问题

linux执行jar访问axis接口错误

蛮大人123 2019-12-01 20:17:38 1153 浏览量 回答数 1

问题

怎样让js和java之间传值?

小旋风柴进 2019-12-01 20:28:53 1852 浏览量 回答数 1

回答

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Listip { public static void main(String[] args) throws Exception { System.out.println("本机的外网IP是:" + Listip.getWebIp("http://iframe.ip138.com/ic.asp")); } public static String getWebIp(String strUrl) { try { URL url = new URL(strUrl); BufferedReader br = new BufferedReader(new InputStreamReader(url .openStream())); String s = ""; StringBuffer sb = new StringBuffer(""); String webContent = ""; while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } br.close(); webContent = sb.toString(); int start = webContent.indexOf("[") + 1; int end = webContent.indexOf("]"); System.out.println("webContent=" + webContent); System.out.println("start=" + start); System.out.println("end=" + end); if (start < 0 || end < 0) { return null; } webContent = webContent.substring(start, end); return webContent; } catch (Exception e) { e.printStackTrace(); return "error open url:" + strUrl; } }

云栖技术 2019-12-02 02:35:40 0 浏览量 回答数 0

问题

memcpy函数相关问题

a123456678 2019-12-01 19:51:03 930 浏览量 回答数 1

回答

只建一个HashMap,在里面记录每个连接的唯一ID和最后心跳时间,然后每隔一段时间去检测距离现在的时间,如果超过某个限定值就判定它已经停止。下面是写的代码,仅供参考: 108 package com.raymon.receivefile.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.raymon.receivefile.utils.ReadResourceMapping; //import org.apache.log4j.Logger; public class downFileServlet extends HttpServlet{ private static final long serialVersionUID = -5142659230279721142L; ReadResourceMapping readproperties = new ReadResourceMapping(); //记录下载数 static int countLive = 0; //记录每个连接信息的最后心跳时间,用作判断该连接是否还在下载 static HashMap<String,Date> lastAliveMap = new HashMap<String, Date>(); //用于比较式储存需要删除的key static List<String> lostList = new ArrayList<String>(); //初始化代码,开始定时检测,只执行一次 @Override public void init() throws ServletException { //判断哪个连接信息的最后心跳时间距离超时,用作判断该连接是否还在下载 System.out.println("调用init方法"); Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { //遍历HashMap作判断 System.out.println("开始计算各个连接最后心跳时间到现在的时差,当前countLive:"+countLive); Iterator it1 = lastAliveMap.entrySet().iterator(); while(it1.hasNext()){ Entry obj = (Entry) it1.next(); System.out.println("lastAliveMap:"+obj.getKey()+":"+obj.getValue()); //如果某个连接的最后心跳距离现在超过限制,说明已经没有在下载,移出连接并连接数减一 long l=(new Date()).getTime()-((Date)(obj.getValue())).getTime(); //如果某连接已停止,记录下key,countLive减一 System.out.println("连接于对应时间距离:"+obj.getKey()+":"+l/1000); if(l/1000>10){ System.out.println("检测出该连接停止:"+"lastAliveMap:"+obj.getKey()+":"+obj.getValue()); lostList.add((String)obj.getKey()); System.out.println("-------下载数减一--------"); countLive--; System.out.println("当前下载数:"+countLive); } } //比较完后再删除已停止的下载连接 for(String lostKey : lostList){ lastAliveMap.remove(lostKey); } } }, 7000,7000);// 7秒后,每隔7秒检测一次 super.init(); } public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { if(req.getParameter("clientId")!=null){ //如果是下载心跳请求 //获取该下载链接的唯一key // String key = req.getParameter("clientId") + req.getParameter("fileName"); String key = req.getParameter("clientId"); //初始化记录 lastAliveMap.put(key, new Date()); System.out.println("记录了连接,打印Map--"); Iterator it3 = lastAliveMap.entrySet().iterator(); while(it3.hasNext()){ Entry obj = (Entry) it3.next(); System.out.println("lastAliveMap:"+obj.getKey()+":"+obj.getValue()); } System.out.println("--打印map"); }else if(req.getParameter("over")!=null){ //如果是下载结束请求,可能不需要 // countLive--; System.out.println("下载完成:"+countLive); }else if(countLive<=5){ //如果是正常下载请求,这里控制下载数 countLive++; //增加下载数标记 System.out.println("开始下载!当前下载数:"+countLive); //fileBasePath要改为从请求传入,统一配置 String fileBasePath = req.getParameter("fileBasePath"); System.out.println("fileBasePath:"+fileBasePath); //System.out.println("newRealFileName:"+new String(fileName.getBytes("ISO-8859-1"), "utf-8")); //重新构建下载url String fileUrl = fileBasePath + req.getParameter("fileName"); System.out.println("fileUrl: " + fileUrl + " from " + req.getLocalAddr()); response.sendRedirect(fileUrl); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

落地花开啦 2019-12-02 02:28:45 0 浏览量 回答数 0

回答

这个怎么没有回复啊我去,手动回复 【关羽大侠】如果阿里云检测我已有的服务的稳定性和安全性,完全可以接受,但为什么会检测我没有服务,全包404,还有访问请求是 null/null的,太扯淡了如下图,我的服务里根本就不应该有这些请求的27.0.0.1 - - [05/Sep/2018:15:00:13 +0800] "GET /PuGxslCx.stm HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:14 +0800] "GET /PuGxslCx.showsource HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:14 +0800] "GET /PuGxslCx.htm HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:14 +0800] "GET null null" 400 -127.0.0.1 - - [05/Sep/2018:15:00:14 +0800] "GET /PuGxslCx.cgi+ HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:15 +0800] "GET /PuGxslCx.save HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:15 +0800] "GET /PuGxslCx.ca HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:15 +0800] "GET /PuGxslCx.it HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:16 +0800] "GET /PuGxslCx.ncf HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:16 +0800] "GET /PuGxslCx.java HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:16 +0800] "GET /PuGxslCx.Htm HTTP/1.0" 404 41756127.0.0.1 - - [05/Sep/2018:15:00:17 +0800] "GET /PuGxslCx.tcl HTTP/1.0" 404 41756

化仙入蝶魂 2019-12-02 01:33:10 0 浏览量 回答数 0

回答

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Lianxi { static Map map=new HashMap(); public static void main(String[] args) throws IOException { String line = null; String a=null,a1 =null; String b=null,b1 =null; BufferedReader in = new BufferedReader(new FileReader("F:\\a.txt")); while((line = in.readLine())!=null) { a=line.split(",")[0]; b=line.split(",")[1]; if(map.get(a)!=null) { b1= (String) map.get(a); map.remove(a); int temp=Integer.parseInt(b)+Integer.parseInt(b1); String temp1=String.valueOf(temp); map.put(a, temp1); } else { map.put(a, b); } } BufferedReader in1 = new BufferedReader(new FileReader("F:\\b.txt")); while((line=in1.readLine())!=null) { a1=line.split(",")[0]; b1=line.split(",")[1]; if(a1.equals("id")) { } else if(map.get(a1)!=null) { b= (String) map.get(a1); map.remove(a1); int temp=Integer.parseInt(b1)+Integer.parseInt(b); // String temp1=String.valueOf(temp); map.put(a1, temp); } else { map.put(a1, b1); } } StringBuffer str = new StringBuffer(); FileWriter fw = new FileWriter("F:\\c.txt", true); Set set = map.entrySet(); Iterator iter = set.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); str.append(entry.getKey()+" , "+entry.getValue()+"\r\n"); } fw.write(str.toString()); fw.close(); } }

蛮大人123 2019-12-02 02:38:26 0 浏览量 回答数 0

回答

java bytecode 是基于栈的。局部变量区在栈帧里面,同时还有操作数栈和帧数据区。只不过java的栈跟x86的栈不一样的地方是,x86的栈可以拿ebp加偏移来随便访问,java不行,局部变量区和操作数栈都有专门的访问指令,互不相通。比如:public static void main(String[] args) { int i = 0; int j = 4; int k = i + j; float a = 0; float b = 1; float c = a + b; long x = 0; long y = 1; long z = x + y; String string = null; }会被编译成:public static void main(java.lang.String[]); Code: // int i = 0; 0: iconst_0 1: istore_1 // int j = 4; 2: iconst_4 3: istore_2 // int k = i + j; 4: iload_1 5: iload_2 6: iadd 7: istore_3 // float a = 0; 8: fconst_0 9: fstore 4 // float b = 1; 11: fconst_1 12: fstore 5 // float c = a + b; 14: fload 4 16: fload 5 18: fadd 19: fstore 6 // long x = 0; 21: lconst_0 22: lstore 7 // long y = 1; 24: lconst_1 25: lstore 9 // long z = x + y; 27: lload 7 29: lload 9 31: ladd 32: lstore 11 // String string = null; 34: aconst_null 35: astore 13 37: return一般书中不会提及这些,需要你自己拿着jd-gui反编译你写的程序来看。

蛮大人123 2019-12-02 02:05:45 0 浏览量 回答数 0

回答

反射机制什么是反射机制简单来说,放射可以帮助我们在动态运行的时候,对于任意一个类,可以获得其所有的方法(包括 public protected private 默认状态的),所有的变量 (包括 public protected private 默认状态的)。是不是很强大呢。 反射机制有什么作用呢?获取某些类的一些变量,调用某些类的私有方法。(例如在Android开发中我们可以用来开启 WiFi 热点,调用 WifiManager 中的 setWifiApEnabled() 方法 )增加代码的灵活性。很多主流框架都使用了反射技术.像ssh框架都采用两种技术 xml做配置文件+反射技术.假如有这样一个类 Person,它拥有多个成员变量,country,city,name,province,height,age 等,同时它拥有多个 构造方法,多个方法,这些变量,方法的访问权限既有 public 也有 private 的。下面我们以这个为例子,一起看怎样使用反射获得相应的 Filed,Constructor,Method。 public class Person { public String country; public String city; private String name; private String province; private Integer height; private Integer age; public Person() { System.out.println("调用Person的无参构造方法"); } private Person(String country, String city, String name) { this.country = country; this.city = city; this.name = name; } public Person(String country, Integer age) { this.country = country; this.age = age; } private String getMobile(String number) { String mobile = "010-110" + "-" + number; return mobile; } private void setCountry(String country) { this.country=country; } public void getGenericHelper(HashMap<String, Integer> hashMap) { } public Class getGenericType() { try { HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); Method method = getClass().getDeclaredMethod("getGenericHelper",HashMap.class); Type[] genericParameterTypes = method.getGenericParameterTypes(); if (null == genericParameterTypes || genericParameterTypes.length < 1) { return null; } ParameterizedType parameterizedType=(ParameterizedType)genericParameterTypes[0]; Type rawType = parameterizedType.getRawType(); System.out.println("----> rawType=" + rawType); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments==genericParameterTypes || actualTypeArguments.length<1) { return null; } for (int i = 0; i < actualTypeArguments.length; i++) { Type type = actualTypeArguments[i]; System.out.println("----> type=" + type); } } catch (Exception e) { } return null; } @Override public String toString() { return "Person{" + "country='" + country + '\'' + ", city='" + city + '\'' + ", name='" + name + '\'' + ", province='" + province + '\'' + ", height=" + height + '}'; } } 使用反射获得所有构造方法(包括私有的,非私有的)默认权限的指的是没有修饰符修饰的 几个重要的方法讲解方法 描述public Constructor getConstructor(Class… parameterTypes) 获得指定的构造方法,注意只能获得 public 权限的构造方法,其他访问权限的获取不到public Constructor getDeclaredConstructor(Class… parameterTypes) 获得指定的构造方法,注意可以获取到任何访问权限的构造方法。public Constructor[] getConstructors() throws SecurityException 获得所有 public 访问权限的构造方法public Constructor[] getDeclaredConstructors() throws SecurityException 获得所有的构造方法,包括(public, private,protected,默认权限的)看了上面的几个方法,其实很好区分 后缀带 s 的返回对象时数组类型,是可以获得相应权限的所有方法的,如 Constructor getConstructor() 方法 和 Constructor获得所有的构造方法public static void printConstructor(String className) { try { Class<?> aClass = Class.forName(className); Constructor<?>[] constructors = aClass.getConstructors(); print(constructors); Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors(); print(declaredConstructors); } catch (ClassNotFoundException e) { e.printStackTrace(); } }print: private com.example.reflectdemo.Person(java.lang.String,java.lang.String,java.lang.String) print: public com.example.reflectdemo.Person() print:public com.example.reflectdemo.Person(java.lang.String,java.lang.Integer) print:public com.example.reflectdemo.Person(java.lang.String,java.lang.Integer) 对比 Person 里面所有的构造方法,可以知道我们代码的逻辑是正确的 获得指定的构造方法public static Constructor getConstructor(String className, Class<?>... clzs) { try { Class<?> aClass = Class.forName(className); Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(clzs); print(declaredConstructor); // if Constructor is not public,you should call this declaredConstructor.setAccessible(true); return declaredConstructor; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } public class TestHelper { public static final String TAG="xujun"; public static final String CLASS_NAME = "com.example.reflectdemo.Person"; public static final String CHINA = "China"; public static void testConstructor(){ ReflectHelper.printConstructor(CLASS_NAME); Constructor constructor = ReflectHelper.getConstructor(CLASS_NAME, String.class, Integer.class); try { Object meinv = constructor.newInstance(CHINA, 12); Person person = (Person) meinv; Log.i(TAG, "testConstructor: =" + person.toString()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } 我们将可以看到以下的输出结果 testConstructor: =Person [country=China, city=null, name=null, province=null, height=null, age=12] 可以看到 country=China,age=12 这说明我们成功通过反射调用 Person 带两个参数的沟改造方法。 注意事项如果该方法,或者该变量不是 public 访问权限的,我们应该调用相应的 setAccessible(true) 方法,才能访问得到 //if Constructor is not public,you should call thisdeclaredConstructor.setAccessible(true);12使用反射获得所有的 Filed 变量获得所有的 Filed 变量public static void printFiled(String className) { try { Class<?> aClass = Class.forName(className); Field[] fields = aClass.getFields(); PrintUtils.print(fields); Field[] declaredFields = aClass.getDeclaredFields(); PrintUtils.print(declaredFields); } catch (ClassNotFoundException e) { e.printStackTrace(); } } 获得指定的成员变量现在假如我们要获得 Person 中的私有变量 age ,我们可以通过以下的代码获得,同时并打印出所有的成员变量。 public static Field getFiled(String className, String filedName) { Object o = null; try { Class<?> aClass = Class.forName(className); Field declaredField = aClass.getDeclaredField(filedName); // if not public,you should call this declaredField.setAccessible(true); return declaredField; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return null; } public static void testFiled(){ ReflectHelper.printFileds(CLASS_NAME); Person person = new Person(CHINA, 12); Field field = ReflectHelper.getFiled(CLASS_NAME, "age"); try { Integer integer = (Integer) field.get(person); PrintUtils.print("integer="+integer); } catch (IllegalAccessException e) { e.printStackTrace(); } } 我们可以看到以下的输出结果 print: public java.lang.String com.example.reflectdemo.Person.country print: public java.lang.String com.example.reflectdemo.Person.city print: public java.lang.String com.example.reflectdemo.Person.country print: public java.lang.String com.example.reflectdemo.Person.city print: private java.lang.String com.example.reflectdemo.Person.name print: private java.lang.String com.example.reflectdemo.Person.province print: private java.lang.Integer com.example.reflectdemo.Person.height print: private java.lang.Integer com.example.reflectdemo.Person.age print:integer=12 使用反射执行相应的 Method主要有以下几个方法, public Method[] getDeclaredMethods()public Method[] getMethods() throws SecurityExceptionpublic Method getDeclaredMethod()public Method getMethod(String name, Class获取所有的 Method public static void printMethods(String className) { try { Class<?> aClass = Class.forName(className); Method[] declaredMethods = aClass.getDeclaredMethods(); PrintUtils.print(declaredMethods); } catch (ClassNotFoundException e) { e.printStackTrace(); } } print: public java.lang.String com.example.reflectdemo.Person.toString() print: public java.lang.Class com.example.reflectdemo.Person.getGenericType() print: private void com.example.reflectdemo.Person.setCountry(java.lang.String) print: public void com.example.reflectdemo.Person.getGenericHelper(java.util.HashMap) print: private java.lang.String com.example.reflectdemo.Person.getMobile(java.lang.String) 对比 Person 里面的所有方法,毫无疑问我们的代码逻辑是正确的。 获取指定的 Method我们可以使用 getDeclaredMethod(String name, Class public static void testMethod(){ ReflectHelper.printMethods(CLASS_NAME); Person person=new Person(); Method method = ReflectHelper.getMethod(CLASS_NAME, "setCountry", String.class); try { // 执行方法,结果保存在 person 中 Object o = method.invoke(person, CHINA); // 拿到我们传递进取的参数 country 的值 China String country=person.country; PrintUtils.print(country); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } public class ReflectHelper { private static final String TAG = "ReflectHelper"; public static Method getMethod(String className, String methodName, Class<?>... clzs) { try { Class<?> aClass = Class.forName(className); Method declaredMethod = aClass.getDeclaredMethod(methodName, clzs); declaredMethod.setAccessible(true); return declaredMethod; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } } 执行上面的函数,将可以看到下面的结果 print:China 即我们成功利用反射调用 Person 的 setCountry 方法,并将值成功改变。 使用反射操作数组/** * 利用反射操作数组 * 1 利用反射修改数组中的元素 * 2 利用反射获取数组中的每个元素 */ public static void testArrayClass() { String[] strArray = new String[]{"5","7","暑期","美女","女生","女神"}; Array.set(strArray,0,"帅哥"); Class clazz = strArray.getClass(); if (clazz.isArray()) { int length = Array.getLength(strArray); for (int i = 0; i < length; i++) { Object object = Array.get(strArray, i); String className=object.getClass().getName(); System.out.println("----> object=" + object+",className="+className); } } } —-> object=帅哥,className=java.lang.String —-> object=7,className=java.lang.String —-> object=暑期,className=java.lang.String —-> object=美女,className=java.lang.String —-> object=女生,className=java.lang.String —-> object=女神,className=java.lang.String 从结果可以说明,我们成功通过 Array.set(strArray,0,”帅哥”) 改变数组的值。 使用反射获得泛型类型public static void getGenericHelper(HashMap map) { } 现在假设我们有这样一个方法,那我们要怎样获得 HashMap 里面的 String,Person 的类型呢? 对于 Java Type还不熟悉的可以先读这一篇博客 java Type 详解 public static void getGenericType() { try { Method method =TestHelper.class.getDeclaredMethod("getGenericHelper",HashMap.class); Type[] genericParameterTypes = method.getGenericParameterTypes(); // 检验是否为空 if (null == genericParameterTypes || genericParameterTypes.length < 1) { return ; } // 取 getGenericHelper 方法的第一个参数 ParameterizedType parameterizedType=(ParameterizedType)genericParameterTypes[0]; Type rawType = parameterizedType.getRawType(); System.out.println("----> rawType=" + rawType); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments==genericParameterTypes || actualTypeArguments.length<1) { return ; } // 打印出每一个类型 for (int i = 0; i < actualTypeArguments.length; i++) { Type type = actualTypeArguments[i]; System.out.println("----> type=" + type); } } catch (Exception e) { } } 执行上面的代码,输出结果 —-> rawType=class java.util.HashMap —-> type=class java.lang.String —-> type=class com.example.reflectdemo.Person 怎样获得 Metho,Field,Constructor 的访问权限 ( public,private,ptotected 等)其实很简单,我们阅读文档可以发现他们都有 getModifiers() 方法,该方法放回 int 数字, 我们在利用 Modifier.toString() 就可以得到他们的访问权限 int modifiers = method.getModifiers();Modifier.toString(modifiers);

hiekay 2019-12-02 01:41:01 0 浏览量 回答数 0

问题

Java TreeMap的put()方法中利用泛型创建接口对象?

蛮大人123 2019-12-01 20:12:34 947 浏览量 回答数 1

问题

java 对象引用关系疑问

蛮大人123 2019-12-01 19:45:28 769 浏览量 回答数 1

问题

IO流统计英文单词的问题

蛮大人123 2019-12-01 19:56:11 1401 浏览量 回答数 1

回答

提供一种程序实现的思路 具体还的你自己修改· import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Test { /** * @param args */ public static void main(String[] args) { Map<String,String[]> map=new HashMap<String,String[]>();//存放叠加的数据 List<String[]> list=new ArrayList<String[]>();//数据list list.add(new String[]{"金点子","封面","彩板","5","1","4"}); list.add(new String[]{"金点子","封面","彩板","5","1","4"}); list.add(new String[]{"金点子","封面","彩板","5","1","4"}); list.add(new String[]{"金点子","封面","彩板","5","1","4"}); list.add(new String[]{"金点子","头版","信息版","8","1","7"}); list.add(new String[]{"金点子","头版","信息版","5","1","4"}); list.add(new String[]{"金点子","头版","信息版","12","1","11"}); for(String[] strs : list){//循环数据 String[] strTemp=map.get(strs[1]);//判断是否已存在 if(strTemp!=null){//存在就数据相加 strTemp[3]=(Integer.parseInt(strTemp[3])+Integer.parseInt(strs[3]))+""; strTemp[4]=(Integer.parseInt(strTemp[4])+Integer.parseInt(strs[4]))+""; strTemp[5]=(Integer.parseInt(strTemp[5])+Integer.parseInt(strs[5]))+""; }else{//不存在就添加数据 map.put(strs[1], strs); } } //迭代输出结果 System.out.println("DM\t版面\t类型\t总数量\t已使用\t空闲"); for(String key : map.keySet()){ String[] strTemp=map.get(key); System.out.println(strTemp[0]+"\t"+strTemp[1]+"\t"+strTemp[2]+"\t"+strTemp[3]+"\t"+strTemp[4]+"\t"+strTemp[5]); } } }

小旋风柴进 2019-12-02 01:58:13 0 浏览量 回答数 0

问题

springcloud+security+oauth2.0+jwt实现安全框架怎?400报错

爱吃鱼的程序员 2020-06-06 10:48:40 0 浏览量 回答数 1

回答

解决方法:继承IdentifierGenerator,Configurable 这2个接口 package com.testplatform.idGenerator; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.Configurable; import org.hibernate.id.IdentifierGenerator; import org.hibernate.type.Type; public class IDGenerator implements IdentifierGenerator,Configurable { private String prefix; private String seq; static Logger log4j = Logger.getLogger(IDGenerator.class.getClass()); public Serializable generate(SessionImplementor session, Object arg1) throws HibernateException { // TODO Auto-generated method stub Connection connection = session.connection(); try { //SELECT seq_date_info_id.nextval from dual; PreparedStatement ps = connection .prepareStatement("SELECT "+seq+".nextval from dual"); ResultSet rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt("nextval"); String code = prefix+id; //String code = prefix + StringUtils.leftPad("" + id,3, '0'); log4j.warn("IDGenerator: " + code); return code; } } catch (SQLException e) { log4j.warn(e); throw new HibernateException( "Unable to generate id "); } return null; } public void configure(Type arg0, Properties params, Dialect arg2) throws MappingException { // TODO Auto-generated method stub // System.out.println("configure"); /* table = params.getProperty("table"); if (table == null) table = params.getProperty(PersistentIdentifierGenerator.TABLE);*/ seq = params.getProperty("seq"); prefix = params.getProperty("prefix"); } }

爵霸 2019-12-02 01:56:56 0 浏览量 回答数 0

回答

1. 查询整个映射对象所有字段 Java代码 //直接from查询出来的是一个映射对象,即:查询整个映射对象所有字段 String hql = "from Users"; Query query = session.createQuery(hql); List<Users> users = query.list(); for(Users user : users){ System.out.println(user.getName() + " : " + user.getPasswd() + " : " + user.getId()); } 输出结果为: name1 : password1 : 1 name2 : password2 : 2 name3 : password3 : 3 2.查询单个字段 Java代码 //查询单个字段 String hql = " select name from Users"; Query query = session.createQuery(hql); List<String> list = query.list(); for(String str : list){ System.out.println(str); } 输出结果为: name1 name2 name3 3.查询其中几个字段 Java代码 //查询其中几个字段 String hql = " select name,passwd from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组 List<Object[]> list = query.list(); for(Object[] object : list){ String name = (String)object[0]; String passwd = (String)object[1]; System.out.println(name + " : " + passwd); } 输出结果为: name1 : password1 name2 : password2 name3 : password3 4.修改默认查询结果(query.list())不以Object[]数组形式返回,以List形式返回 引用 //查询其中几个字段,添加new list(),注意list里的l是小写的。也不需要导入包,这样通过query.list()出来的list里存放的不再是默认的Object数组了,而是List集合了 String hql = " select new list(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是List集合了 List<List> list = query.list(); for(List user : list){ String name = (String)user.get(0); String passwd = (String)user.get(1); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 5.修改默认查询结果(query.list())不以Object[]数组形式返回,以Map形式返回 Java代码 收藏代码 //查询其中几个字段,添加new map(),注意map里的m是小写的。也不需要导入包,这样通过query.list()出来的list里存放的不再是默认的Object数组了,而是map集合了 String hql = " select new map(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是Map集合了 List<Map> list = query.list(); for(Map user : list){ //一条记录里所有的字段值都是map里的一个元素,key是字符串0,1,2,3....,value是字段值 //如果将hql改为:String hql = " select new map(name as username,passwd as password) from Users";,那么key将不是字符串0,1,2...了,而是"username","password"了 String name = (String)user.get("0");//get("0");是get(key),注意:0,1,2...是字符串,而不是整形 String passwd = (String)user.get("1"); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 6.修改默认查询结果(query.list())不以Object[]数组形式返回,以Set形式返回,但是因为Set里是不允许有重复的元素,所以:username和password的值不能相同。只需将hql改为:String hql = " select new set(name,passwd) from Users"; 7.修改默认查询结果(query.list())不以Object[]数组形式返回,以自定义类型返回 自定义类: Java代码 package com.domain; public class MyUser { private String username; private String password; //因为:String hql = " select new com.domain.MyUser(name,passwd) from Users";所以必须要有接受2个参数的构造函数 public MyUser(String username,String password){ this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Java代码 //通过query.list()出来的list里存放的不再是默认的Object数组了,而是自定义的类MyUser,必须加包名,String hql = "from Users";中的Users类也是必须加包名的,但是因为再Users.hbm.xml里<hibernate-mapping auto-import="true"> auto-import默认值为true(所以auto-import属性也可以不写),自动导入了 String hql = " select new com.domain.MyUser(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是MyUser对象了 List<MyUser> myUsers = query.list(); for(MyUser myUser : myUsers){ String name = myUser.getUsername(); String passwd = myUser.getPassword(); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 8:条件查询 Java代码 //条件查询,参数索引值从0开始,索引位置。通过setString,setParameter设置参数 String hql = "from Users where name=? and passwd=?"; Query query = session.createQuery(hql); //第1种方式 // query.setString(0, "name1"); // query.setString(1, "password1"); //第2种方式 query.setParameter(0, "name1",Hibernate.STRING); query.setParameter(1, "password1",Hibernate.STRING); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } Java代码 //条件查询,自定义索引名(参数名):username,:password.通过setString,setParameter设置参数 String hql = "from Users where name=:username and passwd=:password"; Query query = session.createQuery(hql); //第1种方式 // query.setString("username", "name1"); // query.setString("password", "password1"); //第2种方式,第3个参数确定类型 query.setParameter("username", "name1",Hibernate.STRING); query.setParameter("password", "password1",Hibernate.STRING); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } Java代码 //条件查询,通过setProperties设置参数 String hql = "from Users where name=:username and passwd=:password"; Query query = session.createQuery(hql); //MyUser类的2个属性必须和:username和:password对应 MyUser myUser = new MyUser("name1","password1"); query.setProperties(myUser); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } [java] view plaincopy package com.hp.ts.bca.user.bo; import com.hp.ts.bca.common.BaseObject; public class StationUser extends BaseObject { private static final long serialVersionUID = -1175811459644997844L; private int id; private String username; private String officePhone; private String mobilePhone1; private String officeEmail; private Integer ifDefault; public StationUser(int id, String username, String officePhone, String mobilePhone1, String officeEmail, Integer ifDefault) { super(); this.id = id; this.username = username; this.officePhone = officePhone; this.mobilePhone1 = mobilePhone1; this.officeEmail = officeEmail; this.ifDefault = ifDefault; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getMobilePhone1() { return mobilePhone1; } public void setMobilePhone1(String mobilePhone1) { this.mobilePhone1 = mobilePhone1; } public String getOfficeEmail() { return officeEmail; } public void setOfficeEmail(String officeEmail) { this.officeEmail = officeEmail; } public Integer getIfDefault() { return ifDefault; } public void setIfDefault(Integer ifDefault) { if(ifDefault==null) ifDefault=0; else this.ifDefault = ifDefault; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((ifDefault == null) ? 0 : ifDefault.hashCode()); result = prime * result + ((mobilePhone1 == null) ? 0 : mobilePhone1.hashCode()); result = prime * result + ((officeEmail == null) ? 0 : officeEmail.hashCode()); result = prime * result + ((officePhone == null) ? 0 : officePhone.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StationUser other = (StationUser) obj; if (id != other.id) return false; if (ifDefault == null) { if (other.ifDefault != null) return false; } else if (!ifDefault.equals(other.ifDefault)) return false; if (mobilePhone1 == null) { if (other.mobilePhone1 != null) return false; } else if (!mobilePhone1.equals(other.mobilePhone1)) return false; if (officeEmail == null) { if (other.officeEmail != null) return false; } else if (!officeEmail.equals(other.officeEmail)) return false; if (officePhone == null) { if (other.officePhone != null) return false; } else if (!officePhone.equals(other.officePhone)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "StationUser [id=" + id + ", username=" + username + ", officePhone=" + officePhone + ", mobilePhone1=" + mobilePhone1 + ", officeEmail=" + officeEmail + ", ifDefault=" + ifDefault + "]"; } } [java] view plaincopy @Override public PageResponse<User> getUserListByStationId(int currentPage, int rowsPerPage, String sidx, String sord, Integer stationId) { StringBuilder hql = new StringBuilder(); hql.append("select new com.hp.ts.bca.user.bo.StationUser(a.id,a.username,a.officePhone,a.mobilePhone1,a.officeEmail,ug.ifDefault) FROM User a, UserGroup ug WHERE a.id=ug.userId and ug.groupId="); hql.append(stationId); //hql.append("FROM User AS user, UserGroup AS ug WHERE user.id=ug.userId"); PageResponse<User> userList = this.groupDao.excutePage(hql.toString(), currentPage, rowsPerPage, sidx, sord); return userList; }

小旋风柴进 2019-12-02 02:11:27 0 浏览量 回答数 0

回答

java api里的Object.hashcode(): (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.) 看代码可以知道, hashcode()是一个native函数, 但实际JVM会不会直接用对象地址来做hashcode有待探讨, 因为现代的JVM 堆都是分代管理的, 一个Object很可能在一次 GC后改变其对象地址.而对一个对象来说, 其生命周期内的hashcode是不会变的. Effective Java里提到自定义hashcode()的recipe(实际上在Eclipse里, 右键-> Source -> Generate hashcode and Equals可以代劳).大概例子这样: private String s; private int a; private short b; private Date d; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; result = prime * result + ((d == null) ? 0 : d.hashCode()); result = prime * result + ((s == null) ? 0 : s.hashCode()); return result; }

蛮大人123 2019-12-02 01:57:33 0 浏览量 回答数 0

回答

如果没猜错的话题主是想要对wav文件进行读取操作: package com.chinasoft.cn; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; @SuppressWarnings("unused") public class WaveFileReader { private String filename = null; private int[][] data = null; private int len = 0; private String chunkdescriptor = null; private long chunksize = 0; private String waveflag = null; private String fmtsubchunk = null; private long subchunk1size = 0; private int audioformat = 0; private int numchannels = 0; private long samplerate = 0; private long byterate = 0; private int blockalign = 0; private int bitspersample = 0; private String datasubchunk = null; private long subchunk2size = 0; private FileInputStream fis = null; private BufferedInputStream bis = null; private boolean issuccess = false; public WaveFileReader(String filename) { this.initReader(filename); } // 判断是否创建wav读取器成功 public boolean isSuccess() { return issuccess; } // 获取每个采样的编码长度,8bit或者16bit public int getBitPerSample() { return this.bitspersample; } // 获取采样率 public long getSampleRate() { return this.samplerate; } // 获取声道个数,1代表单声道 2代表立体声 public int getNumChannels() { return this.numchannels; } // 获取数据长度,也就是一共采样多少个 public int getDataLen() { return this.len; } // 获取数据 // 数据是一个二维数组,[n][m]代表第n个声道的第m个采样值 public int[][] getData() { return this.data; } private void initReader(String filename) { this.filename = filename; try { fis = new FileInputStream(this.filename); bis = new BufferedInputStream(fis); this.chunkdescriptor = readString(WaveConstants.LENCHUNKDESCRIPTOR); if (!chunkdescriptor.endsWith("RIFF")) throw new IllegalArgumentException("RIFF miss, " + filename + " is not a wave file."); this.chunksize = readLong(); this.waveflag = readString(WaveConstants.LENWAVEFLAG); if (!waveflag.endsWith("WAVE")) throw new IllegalArgumentException("WAVE miss, " + filename + " is not a wave file."); this.fmtsubchunk = readString(WaveConstants.LENFMTSUBCHUNK); if (!fmtsubchunk.endsWith("fmt ")) throw new IllegalArgumentException("fmt miss, " + filename + " is not a wave file."); this.subchunk1size = readLong(); this.audioformat = readInt(); this.numchannels = readInt(); this.samplerate = readLong(); this.byterate = readLong(); this.blockalign = readInt(); this.bitspersample = readInt(); this.datasubchunk = readString(WaveConstants.LENDATASUBCHUNK); if (!datasubchunk.endsWith("data")) throw new IllegalArgumentException("data miss, " + filename + " is not a wave file."); this.subchunk2size = readLong(); this.len = (int) (this.subchunk2size / (this.bitspersample / 8) / this.numchannels); this.data = new int[this.numchannels][this.len]; // 读取数据 for (int i = 0; i < this.len; ++i) { for (int n = 0; n < this.numchannels; ++n) { if (this.bitspersample == 8) { this.data[n][i] = bis.read(); } else if (this.bitspersample == 16) { this.data[n][i] = this.readInt(); } } } issuccess = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (fis != null) fis.close(); } catch (Exception e1) { e1.printStackTrace(); } } } private String readString(int len) { byte[] buf = new byte[len]; try { if (bis.read(buf) != len) throw new IOException("no more data!!!"); } catch (IOException e) { e.printStackTrace(); } return new String(buf); } private int readInt() { byte[] buf = new byte[2]; int res = 0; try { if (bis.read(buf) != 2) throw new IOException("no more data!!!"); res = (buf[0] & 0x000000FF) | (((int) buf[1]) << 8); } catch (IOException e) { e.printStackTrace(); } return res; } private long readLong() { long res = 0; try { long[] l = new long[4]; for (int i = 0; i < 4; ++i) { l[i] = bis.read(); if (l[i] == -1) { throw new IOException("no more data!!!"); } } res = l[0] | (l[1] << 8) | (l[2] << 16) | (l[3] << 24); } catch (IOException e) { e.printStackTrace(); } return res; } private byte[] readBytes(int len) { byte[] buf = new byte[len]; try { if (bis.read(buf) != len) throw new IOException("no more data!!!"); } catch (IOException e) { e.printStackTrace(); } return buf; } public static int[] readSingleChannel(String filename) { if (filename == null || filename.length() == 0) { return null; } try { WaveFileReader reader = new WaveFileReader(filename); int[] res = reader.getData()[0]; return res; } catch (Exception e) { e.printStackTrace(); } return null; } } 第二个问题,java虽然没有无符号数,但是不管有无符号,对于二进制数据来说,在内存里存储的值是一样的,只不过打印出来时显示的值不一样,同时在做逻辑对比时有符号和无符号,虽然存储的值一样,但是“大小”可能不同。顺便说一下,如果你感觉java确实不熟,可以尝试一下JNI。

蛮大人123 2019-12-02 01:54:16 0 浏览量 回答数 0

回答

给你个java的代码你,希望对你有帮助 package standard.system; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Random; public class RSACrypt { private static int _PrivateKey = 32823; // 私钥 private static int _PublicKey = 20643; // 公钥 private static int _Modulus = 29893; // 模数 // 对数字进行加密解密运算,根据key为公钥或是私钥来判断对数字进行加密或解密操作 private static int Crypt(int number, int key) { int mod; int i; int result = 0; try { mod = number * number % _Modulus; if (key % 2 == 0) { result = 1; for (i = 0; i < key / 2; i++) { result = mod * result % _Modulus; } } else { result = number; for (i = 0; i < key / 2; i++) { result = mod * result % _Modulus; } } } catch (Exception e) { } return result; } // 根据字符位置将字符的ASCII数值进行偏移,并得到密文 public static String Encode(String message) { int length = message.length(); // 明文的长度 int ascCode; // ASCII码 int cryptCode; // 密码 int rndCode; // 随机码 int index; String encodeString = ""; // 密文 if (length == 0) { return null; } // 产生随机码 Random rnd = new Random(); rndCode = 1 + rnd.nextInt(99); for (index = 0; index < length; index++) { // 获取单字符的ASCII码 ascCode = (int) message.charAt(index); // 同一字符根据随机码偏移保证每次不同 ascCode += rndCode; // 同一字符在不同位置保证不同 ascCode += index + 1; // 因索引值与domino不同(domino起始为1),所以此处加1 // 同一字符在字符串长度变化时保证不同 ascCode += length; ascCode = ascCode % 128; // 加密为密码 cryptCode = Crypt(ascCode, _PublicKey); // 将密码转换为4位16进制字符串 encodeString += DecimalToHex(cryptCode, 4); } // 最后附上随机码的2位16进制字符串 encodeString += DecimalToHex(rndCode, 2); return encodeString; } // 将密文转换为明文,再对明文进行字位偏移,最终得到原文 public static String Decode(String message) { int length = message.length() - 2; // 剥离随机码后的密文长度 int ascCode; // ASCII码 int cryptCode; // 密码 int rndCode; // 随机码 int index; String decodeString = ""; // 明文 // 获取随机码的10进制数字 rndCode = HexToDecimal(message.substring(length)); for (index = 0; index < length; index += 4) { // 将4位16进制字符串转换为10进制密码 cryptCode = HexToDecimal(message.substring(index, index + 4)); // 解密为明码 ascCode = Crypt(cryptCode, _PrivateKey); // 还原随机码偏移 ascCode -= rndCode; // 还原字位偏移 ascCode += (length / 4 % 128 + 1) * 128 - (index + 1) / 4 - 1; // 因索引值与domino不同(domino起始为1),所以此处加1 // 还原字符串长度偏移 ascCode += (length / 4 % 128 + 1) * 128 - length / 4; ascCode = ascCode % 128; // 将ASCII码转换为字符 decodeString += (char) ascCode; } return decodeString; } // 10进制数字转16进制字符串 private static String DecimalToHex(int decNumber, int hexWidth) { String hexString = Integer.toHexString(decNumber); while (hexString.length() < hexWidth) hexString = "0" + hexString; return hexString; } // 16进制字符串转10进制数字 private static int HexToDecimal(String hexString) { return Integer.parseInt(hexString, 16); } public static void main(String[] args) throws UnsupportedEncodingException { String str = "测试158228&&2008-10-23_15:39:58"; System.out.println(str); str = URLEncoder.encode(str, "UTF-8"); System.out.println(str); for (int i = 0; i < 10; i++) { String r = RSACrypt.Encode(str); System.out.println(r); System.out.println(URLDecoder.decode(RSACrypt.Decode(r), "UTF-8")); } } }

寒凝雪 2019-12-02 01:26:34 0 浏览量 回答数 0

问题

java加载spring时找不到配置文件.

a123456678 2019-12-01 20:23:44 1044 浏览量 回答数 1
阿里云大学 云服务器ECS com域名 网站域名whois查询 开发者平台 小程序定制 小程序开发 国内短信套餐包 开发者技术与产品 云数据库 图像识别 开发者问答 阿里云建站 阿里云备案 云市场 万网 阿里云帮助文档 免费套餐 开发者工具 企业信息查询 小程序开发制作 视频内容分析 企业网站制作 视频集锦 代理记账服务 企业建站模板