一、阿拉伯数字转汉字大写
public static String HanDigiStr[] = new String[]{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
public static String HanDiviStr[] = new String[]{"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟"};
public static String createChinaNumber(String NumStr) {
String RMBStr = "";
boolean lastzero = false;
boolean hasvalue = false;
// 亿、万进位前有数值标记
int len, n;
len = NumStr.length();
if (len > 15) {
return "数值过大!";
}
for (int i = len - 1; i >= 0; i--) {
if (NumStr.charAt(len - i - 1) == ' ') {
continue;
}
n = NumStr.charAt(len - i - 1) - '0';
if (n < 0 || n > 9) {
return "输入含非数字字符!";
}
if (n != 0) {
if (lastzero) {
RMBStr += HanDigiStr[0];
// 若干零后若跟非零值,只显示一个零// 除了亿万前的零不带到后面
}
// if( !( n==1 && (i%4)==1 && (lastzero || i==len-1) ) ) //
// 如十进位前有零也不发壹音用此行
if (!(n == 1 && (i % 4) == 1 && i == len - 1)) {
// 十进位处于第一位不发壹音
RMBStr += HanDigiStr[n];
}
RMBStr += HanDiviStr[i];
// 非零值后加进位,个位为空
hasvalue = true;
// 置万进位前有值标记
} else {
if ((i % 8) == 0 || ((i % 8) == 4 && hasvalue)) {
RMBStr += HanDiviStr[i];
// 亿万之间必须有非零值方显示万
}
// “亿”或“万”
}
if (i % 8 == 0) {
hasvalue = false;
}
// 万进位前有值标记逢亿复位
lastzero = (n == 0) && (i % 4 != 0);
}
if (RMBStr.length() == 0) {
return HanDigiStr[0];
}
// 输入空字符或"0",返回"零"
return RMBStr;
}
二、urlEncoder和urlDecoder的作用和使用
1.URLEncoder.encode(String s, String enc)
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式
URLDecoder.decode(String s, String enc)
使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码。
2.发送的时候使用URLEncoder.encode编码,接收的时候使用URLDecoder.decode解码,都按指定的编码格式进行编码、解码,可以保证不会出现乱码
3.主要用来http get请求不能传输中文参数问题。http请求是不接受中文参数的。
这就需要发送方,将中文参数encode,接收方将参数decode,这样接收方就能收到准确的原始字符串了。
如:
String testString = "abcdefghijk二";
try
{
String encoderString = URLEncoder.encode(testString, "utf-8");
System.out.println(encoderString);
String decodedString = URLDecoder.decode(encoderString, "utf-8");
System.out.println(decodedString);
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
输出:
abcdefghijk%E4%BA%8C
abcdefghijk二
三、java 把多文件打包成zip,并下载
主要是对于ZipOutputStream的使用
/**
* 压缩并导出文件
* @param zipPath 压缩文件临时路径 路径最后不要有 /
* @param zipName 压缩为文件名 **.zip
* @param createFilesPath 需要压缩的文件列表
* @param request
* @param response
* @return
* @throws IOException
*/
public boolean downloadZip(String zipPath,String zipName,List<String>createFilesPath,HttpServletRequest request,HttpServletResponse response) {
//String tmpFileName = "report.zip";
byte[] buffer = new byte[1024];
// String strZipPath = COM_REPORT_PATH+"/"+user.getOid()+"/"+report.getOid()+"/"+tmpFileName;
String strZipPath=zipPath+"/"+zipName;
try {
File tmpZip=new File(zipPath);
if (!tmpZip.exists())
tmpZip.mkdirs();
File tmpZipFile = new File(strZipPath);
if (!tmpZipFile.exists())
tmpZipFile.createNewFile();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
// 需要同时下载的两个文件result.txt ,source.txt
File[] file1 =new File[createFilesPath.size()] ;
for(int i=0;i<createFilesPath.size();i++){
file1[i]=new File(createFilesPath.get(i));
}
for (int i = 0; i < file1.length; i++) {
FileInputStream fis = new FileInputStream(file1[i]);
out.putNextEntry(new ZipEntry(file1[i].getName()));
//设置压缩文件内的字符编码,不然会变成乱码
out.setEncoding("UTF-8");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
this.downloadFile(zipPath,zipName,response);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 以压缩文件导出
* @param fileName
* @param filePath
* @param response
*/
public void downloadFile(String filePath,String fileName,HttpServletResponse response){
response.setCharacterEncoding("utf-8");
// response.setContentType("application/octet-stream");
try {
File file=new File(filePath,fileName);
// 以流的形式下载文件。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
toClient.write(buffer);
toClient.flush();
toClient.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
四、freemarkertem基本使用
主要使用是按照模板生成响应的doc文档,大致思路:写好doc模板,改成html修改格式,在改成ftl,代码中写入相应值。
freemarker:
template-loader-path: classpath:/webapp/WEB-INF/ftl/
cache: true
check-template-location: true
content-type: text/html; charset=UTF-8
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
suffix: .ftl
以下代码是用于向前端.ftl文件传值的。
@Api("表单")
@Controller
@RequestMapping("/freemarker")
public class FreemarkerController extends AbstractController {
@Autowired
private PunishService punishService;
@GetMapping("/test")
@ApiOperation(value = "文件下载", notes = "文件下载")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "令牌", paramType = "header", dataType = "String", required = true),
@ApiImplicitParam(name = "processId", value = "processId", paramType = "query", dataType = "String", required = false),
})
public String fileDownLoadById(@RequestParam String processId, Model model) {
PunishVO jtProcess = punishService.getInfo(getUser(), processId);
if (jtProcess != null) {
model.addAttribute("punishCompanyName", jtProcess.getPunishCompanyName());
model.addAttribute("projectName", jtProcess.projectName);
model.addAttribute("content", StringUtils.isNotBlank(jtProcess.content) ? jtProcess.getContent() : "暂无");
model.addAttribute("punishBasis", StringUtil.createOrder(jtProcess.getPunishBasis()));
model.addAttribute("amount", jtProcess.getPunishAmount());
model.addAttribute("amountChina", StringUtil.createChinaNumber(jtProcess.getPunishAmount(), null, null));
model.addAttribute("applicationCompanyName", jtProcess.getApplicationCompanyName());
}
return "test";
}
}
https://blog.csdn.net/viqqw/article/details/80499333
五、ArrayUtils类常用方法
1.add():将给定的数据添加到指定的数组中,返回一个新的数组。
2.addAll():合并两个数组。
3.contains():检查该数据在该数组中是否存在,返回一个boolean值。
4.getLength():返回该数组长度。
5.indexOf():从数组的第一位开始查询该数组中是否有指定的数值,存在返回index的数值,否则返回-1。
6.lastIndexOf():从数组的最后一位开始往前查询该数组中是否有指定的数值,存在返回index的数值,否则返回-1。
7.Insert():向指定的位置往该数组添加指定的元素,返回一个新的数组。
8.isEmpty():判断该数组是否为空,返回一个boolean值。
9.isNotEmpty():判断该数组是否为空,而不是null。
10.isSameLength():判断两个数组的长度是否一样,当数组为空视长度为0。返回一个boolean值。
11.isSameType():判断两个数组的类型是否一样,返回一个boolean值。
12.isSorted():判断该数组是否按照自然排列顺序排序,返回一个boolean值。
13.nullToEmpty():
14.remove():删除该数组指定位置上的元素,返回一个新的数组。
15.removeAll():删除指定位置上的元素,返回一个新的数组。
16.removeAllOccurences():从该数组中删除指定的元素,返回一个新的数组。
17.removeElement():从该数组中删除第一次出现的指定元素,返回一个新的数组。
18.removeElements():从该数组中删除指定数量的元素,返回一个新的数组。
19.reverse():数组反转。也可以指定开始和结束的反转位置。
20.subarray():截取数组(包头不包尾),返回一个新的数组。
21.swap():指定该数组的两个位置的元素交换或者指定两个位置后加len的长度元素进行交换。
22.toMap():将数组转换成Map,返回一个map的Object的集合。
23.toObject():将原始数据类型的数组转换成对象类型数组。
24.toPrimitive():将对象类型数组转换成原始数据类型数组。
25.toString():将数组输出为Stirng,返回一个字符串。
26.toStringArray():将Object数组转换为String数组类型。
例子如下:
public class ArraryTest {
public static void main(String[] args) {
int []array={4,5,9};
//add()添加方法结果为:{4,5,9,6}
int[] newArray=ArrayUtils.add(array, 6);
System.out.println(ArrayUtils.toString(newArray));
//addAll()方法,结果为:{4,5,9,5,9,6,7}
int []arrayAll={4,5,9};
int[] newArrayAll=ArrayUtils.addAll(arrayAll,5,9,6,7);
System.out.println(ArrayUtils.toString(newArrayAll));
//contains():结果为:true、false
System.out.println(ArrayUtils.contains(arrayAll, 9));
System.out.println(ArrayUtils.contains(arrayAll, 3));
//getLength():结果为3
System.out.println(ArrayUtils.getLength(arrayAll));
//indexOf():2。
//indexOf(newArrayAll, 9,3):3是指定从哪一位开始查找,返回结果4
System.out.println(ArrayUtils.indexOf(newArrayAll, 9));
System.out.println(ArrayUtils.indexOf(newArrayAll, 9,3));
//lastIndexOf()返回结果是4、2
System.out.println(ArrayUtils.lastIndexOf(newArrayAll, 9));
System.out.println(ArrayUtils.lastIndexOf(newArrayAll, 9,3));
//insert():结果为{4,5,3,9}
int [] arr=ArrayUtils.insert(2, arrayAll, 3);
System.out.println("insert"+ArrayUtils.toString(arr));
//isEmpty():结果为false、true
int []a=null;
System.out.println(ArrayUtils.isEmpty(arr));
System.out.println(ArrayUtils.isEmpty(a));
//isNotEmpty():结果是false、true
System.out.println("isNotEmpty:"+ArrayUtils.isNotEmpty(a));
System.out.println("isNotEmpty:"+ArrayUtils.isNotEmpty(arr));
//isSorted():结果为false和true
int[]sort1={5,6,9,1};
int [] sort2={1,6,8,9};
System.out.println("sort1:"+ArrayUtils.isSorted(sort1));
System.out.println("sort2:"+ArrayUtils.isSorted(sort2));
//remove():返回结果为{5,6,1}
int [] newRe=ArrayUtils.remove(sort1, 2);
for(int nr:newRe){
System.out.print(nr);
}
//reverse():返回new reverse:{1,9,6,5}
ArrayUtils.reverse(sort1);
System.out.println("new reverse:"+ArrayUtils.toString(sort1));
//subarray():返回结果subarray:{3,9}
int[] sub={7,5,3,9,8,4};
int [] newsub=ArrayUtils.subarray(sub, 2, 4);
System.out.println("subarray:"+ArrayUtils.toString(newsub));
Object[] subs={7,5,3,9,8,4};
Map<Object, Object>map=ArrayUtils.toMap(subs);
}
}
六、url访问、可增加实现CSDN访问量
经过测试下面代码测试,csdn在同一个ip下:每间隔一个小时,访问会加一,每次不同的访问方式也会加一,同一ip下,手机、浏览器,java都会加一。经过一个星期,csdn访问量从2k+到1W+。我原来blog访问量是2k,是真实的访问量,刷访问量是没有意思的,好好写文章,好好积累才是正路。
public static void main(String[] args) {
List<String> urls = new ArrayList<>();
//任意url地址
urls.add("https://blog.csdn.net/qq_22161527/article/details/**");
for (String url : urls) {
openUrl(url);
}
}
private static void openUrl(String urlStr) {
URL url = null;
try {
url = new URL(urlStr);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.connect();
InputStream is = urlcon.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
StringBuffer bs = new StringBuffer();
String l = null;
while ((l = buffer.readLine()) != null) {
bs.append(l).append("/n");
}
System.out.println(bs.toString());
} catch (IOException e1) {
e1.printStackTrace();
}
}
七、数组转List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
需要注意的是, Arrays.asList() 返回一个受指定数组决定的固定大小的列表。所以不能做 add 、 remove 等操作,否则会报错。
List staffsList = Arrays.asList(staffs);
staffsList.add("Mary");
// UnsupportedOperationException
staffsList.remove(0);
如果想再做增删操作呢?将数组中的元素一个一个添加到列表,这样列表的长度就不固定了,可以进行增删操作。
List staffsList = new ArrayList<String>();
for(String temp: staffs){
staffsList.add(temp);
}
staffsList.add("Mary");
// ok
staffsList.remove(0);
数组转Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary");
// ok
staffsSet.remove("Tom");
List转数组
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Object[] result = staffsList.toArray();
List转Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Set result = new HashSet(staffsList);
Set转数组
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
Object[] result = staffsSet.toArray();
Set转List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
List<String> result = new ArrayList<>(staffsSet);
八、map的方法
removeIf,为true执行删除
fileForms.removeIf(form -> !form.getCreateAt().equals(jtProcess.getGmtCreate()));
merge的用法有很多,如果使用map做计数,可以选这样写
for (TaskFast fast : grandTaskFasts) {
//merge 方法
totalMap.merge(fast.getParentId(), 1, (x, y) -> x + y);
}
Java中映射Map的merge、compute、computeIfAbsent、computeIfPresent基本用法参考一下链接
https://blog.csdn.net/mengxb12138/article/details/80893937
九、ZoneId.systemDefault() 默认时区
public static void main(String[] args) {
String timeStr = "2017-8-24 11:17:10";
// 字面时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
// 设置北京时区
Date d = null;
try {
d = sdf.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(sdf.format(d) + ", " + d.getTime());
SimpleDateFormat utcSDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utcSDf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("北京时间: " + timeStr + "对应的东京时间为:" + utcSDf.format(d));
strToDate("2017-8-24 11:17:10", DateUtils.YYYY_MM_DD_HH_MM_SS, ZoneId.of("UTC"));
}
十、去重
去除List中重复的String
List uniqueStr = list.stream().distinct().collect(Collectors.toList());
按对象属性去重
users = users.stream().collect(collectingAndThen( toCollection(() -> new TreeSet<>(Comparator.comparing(UserInDeptDto::getUserId))), ArrayList::new) );
十一、Date、Calendar
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
(2) Date转化为Calendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
十二、Spring获取上下文,推断类型和类
@Override
public ProcessExecutive getProcessExecutive(Integer executiveType) {
if (executiveType == null) {
return null;
}
Map<String, ProcessExecutive> processExecutives = applicationContext.getBeansOfType(ProcessExecutive.class);
for (ProcessExecutive processExecutive : processExecutives.values()) {
if (processExecutive.enableHandel(executiveType)) {
return processExecutive;
}
}
return null;
}
十三、JSON<->字符串
List<String> ids = new ArrayList<>();
ids.add("123");
ids.add("321");
ids.add("321");
ids.add("321");
ids.add("321");
String s = JSON.toJSONString(ids);
System.out.println(s);
// JSONObject jsonObject = JSONObject.parseObject(s);
List<String> list = JSON.parseArray(s, String.class);
System.out.println(list.toString());