java基础数据类型和处理
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map;
import java.text.MessageFormat;
import java.util.Random; public class JavaBasic { //class_variable,for class object.VarName
static String name = "ss";
// instance variable,just for instance callable
private String addr = "south surface"; //without return result ,static method can be callable by static method and class,
// but can't be call by method or instance
public static void printMethod() {
System.out.println("iammmm");
} void defineArrays() {
int[] ai = {1, 2, 3, 4};
Arrays.fill(ai, 5);
for (int i = 0; i < ai.length; i++) {
System.out.println(false);
}
} /**
* format str : python "{0},{1}".foramt(v1,v2)
* python str: "%s is ,%s is ".format(v1,v2)
*/
public String formatStr(String str) {
String newstr = "my name is {0},age is {1}";
return (MessageFormat.format(newstr, "1", "22"));
} /**
* non static can't callable by static method ,just for normal method
*/
String defineStringMethod() {
String str = formatStr("sss");
System.out.println(str);
return "ss";
} /**
* create map
*/
private Map<String, Object> createDict() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", 1);
map.put("key2", "v2");
System.out.println(map);
return map;
} String defineChar() {
char[] mychar = {'a', 'b'};
return new String(mychar);
} // /**
* define array of int,
* and print Array.toString(arrayObject)
*/
void getArrayToStr() {
String[][] str = new String[3][4];
str[0][0] = new String("Good");
Object O = str[0][0];
int[] my = new int[]{1, 2, 3};
//数组对象转字符串输出
System.out.println(Arrays.toString(my) + " " + O);
} /**
* get type of Object
*
* @return : type String
*/
public void type(Object object) {
String tp = String.valueOf(object.getClass().getName());
System.out.println(tp.split("\\.").getClass().getName());
String[] array = tp.split("\\.");
//数组转列表
List<String> list = Arrays.asList(array);
String lastStr = list.get(array.length - 1);
System.out.println(lastStr);
// return lastStr; } /**
* ArrayList to Array : list1.toArray(array)
*/
public void createArrayList() {
List<String> list1 = new ArrayList<String>();
list1.add("index1");
list1.add("index2");
String[] test = list1.getClass().getName().split("\\.");
// array to arrayList
List<String> o = Arrays.asList(test);
String[] array = new String[list1.size()];
// ArrayList to ARRAY
String[] aa = list1.toArray(array);
System.out.println("list1 type is :" + list1.getClass().getName());
System.out.println(Arrays.toString(aa)); } String[] getArray() {
String[] m = new String[1];
return m;
} /**
* enumerate element and index :
*
* @return : ArrayList: [[index,value],[index1,value1]]
*/
void enumerateList() {
List<String> list1 = new ArrayList<String>();
list1.add("index1");
list1.add("index2");
List<Object> all = new ArrayList<Object>();
for (int i = 0; i < list1.size(); i++) {
List<Object> vec = new ArrayList<Object>();
vec.add(i);
vec.add(list1.get(i));
all.add(vec);
}
System.out.println(all);
} /**
* iter map by foreach ,but it cant change key or value in the iteral :
*/
List<Object> iterMap() {
List<Object> out = new ArrayList<Object>();
Map<String, Object> map = createDict();
for (String k : map.keySet()) {
List<Object> in = new ArrayList<Object>();
String value = String.valueOf(map.get(k));
in.add(k);
in.add(value);
out.add(in);
}
System.out.println(out);
return out;
} /**
* iter Map by use entrySet() : python dict.items():
*/
void iterMap2() {
List<Object> out = new ArrayList<Object>();
Map<String, Object> map = createDict();
for (Map.Entry<String, Object> item : map.entrySet()) {
List<Object> in = new ArrayList<Object>();
String k = String.valueOf(item.getKey());
String v = String.valueOf(item.getValue());
in.add(0, k);
in.add(1, v);
out.add(in);
}
System.out.println(out); } /**
* list remove element :
*/
void removeList() {
// == 比对象,equals 比value
List<Integer> out = new ArrayList<Integer>();
out.add(1);
out.add(3);
out.add(1);
for (int i = 0; i < out.size(); i++) {
if (out.get(i).equals(1)) {
out.remove(i);
}
}
System.out.println(out); } /**
* SIMPLE java return :三目运算:
*/
int javaSimple() {
int a, b, c;
a = 10;
b = 1;
// c= ;
return (a == 1) ? a : b;
} /**
* calculator timeInterval init type is long :100L:
*
* @return : String
*/
String timercount() throws InterruptedException {
long date = new Date().getTime();
Thread.sleep(1000);
long date_end = new Date().getTime();
String millions = String.valueOf(date_end - date);
return millions;
} /**
* sort ArrayList for same type elements in list
*/
public static void sortbyCollect() {
List<Integer> aa = new ArrayList<>();
List<Integer> bb = new ArrayList<>();
bb.add(100);
aa.add(9);
aa.add(4);
aa.set(0, 99);
aa.addAll(bb);
Collections.sort(aa);
Collections.reverse(aa);
System.out.println(aa.toString());
} public Map<String, String> sortMap(Map map) {
System.out.println(map);
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
System.out.println(map);
return map;
} void listWhileHas() {
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
//用迭代器 遍历
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
//添加泛型之后 可以省去 强转了行的麻烦
String next = it.next();
System.out.println(next);
} } /**
* gen timestamp str for example:
* 15576676767676
*/
public static String timestamp() {
return String.valueOf(System.currentTimeMillis());
} /**
* random ArrayList of [min,max) or [min,max]
*/
public static List genRandomlist(int START, int END) {
// 可以取到边界值上下
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < END - START + 1; i++) {
int numeric = new Random().nextInt(END - START + 1) + START;
list.add(numeric); }
System.out.println(list);
return list;
} /**
* random ArrayList of [min,max) or [min,max]
*/
public static List mathRandom(int min, int max) {
// max-min 不加1,只可以到[0,10);max-min+1 [1,10]
List list = new ArrayList();
for (int i = 0; i < max - min; i++) {
int num = (int) (Math.random() * (max - min + 1) + min);
list.add(num);
}
System.out.println(list);
return list;
} /**
* gen (0,1) str
*/
public static String genfloatZeroandOne() {
double db = new Random().nextDouble() * 1 + 0;
// DecimalFormat df = new DecimalFormat("0.00");
// return df.format(floats);
float ft = (float) db;
System.out.println(db);//四舍弃,五入
return String.format("%.3f", db);
} /**
* TYPE Transfer
*/
public static void chageType(String str) {
float ft = Float.valueOf(str).floatValue();
byte b = Byte.parseByte(str);
short t = Short.parseShort(str);
int i = Integer.parseInt(str);
long l = Long.parseLong(str);
Float f = Float.parseFloat(str);
Double d = Double.parseDouble(str);
System.out.println(ft);
} public static void genSecureRandom(int start, int end) { } /**
* gen uuidString
*/
public static void genuuid() {
String uuidstr = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
System.out.println(uuidstr);
} /**
* time format,default Calender.get() is int
* month start by 0
*/
public static String timeFormat() {
/**
Calendar now = Calendar.getInstance();
String year=String.valueOf(now.get(Calendar.YEAR));
String month=String.valueOf(now.get(Calendar.MONTH) + 1);
String day=String.valueOf(now.get(Calendar.DAY_OF_MONTH));
String hour=String.valueOf(now.get(Calendar.HOUR_OF_DAY));
String min=String.valueOf(now.get(Calendar.MINUTE));
String seconds=String.valueOf(now.get(Calendar.SECOND));
String str="%s-%s-%s %s:%s:%s";
String curtime= String.format(str,year,month,day,hour,min,seconds);
*/
Date d = new Date();
SimpleDateFormat simpeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String curtimestamp = simpeformat.format(d);
System.out.println(curtimestamp);
return curtimestamp;
} /**
* readfile method
* @return :fileString
* by FileInputStream
*/
public static String readfile(String filepath) throws IOException {
StringBuffer sb = new StringBuffer();
File file = new File(filepath);
if (file.exists() && file.isFile()) {
FileInputStream fip = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
while (reader.ready()) {
/** append char to string buffer*/
sb.append((char) reader.read());
}
/** close reader and fip stream */
reader.close();
fip.close();
}
System.out.println(sb.toString());
return sb.toString();
} /**
* writefile method
*@return :null
* @param : by FileOutputStream
*/
public static void writefile(String pdir,String filename) throws IOException {
File dir =new File(pdir);
if(!dir.exists()){
/** mkdir pdir */
dir.mkdir();
}
File filepath=new File(pdir+filename);
if(!filepath.exists()){
/** touch file */
filepath.createNewFile();
FileOutputStream fop = new FileOutputStream(filepath);
OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
writer.write("9999dftest花");
/**close write and fop stream */
writer.close();
fop.close();
}else{
System.out.println("file already exist");
FileOutputStream fop = new FileOutputStream(filepath);
OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
writer.append("我爱singer");
writer.append("\n9999dftest花");
/**close write and fop stream */
writer.close();
fop.close();
}
} /** delete file*/
public static void delfile(String filepath){
File file =new File(filepath);
if(file.exists()&&file.isFile()){
file.delete();
System.out.println("file delete ok ");
}else{
System.out.println("file not exist");
}
} /**
* delete dir
* @return:null
* @warning: clear all dirs and files under path and strart del path
*/
public static void deleteDir(String path) {
/** list pathdir under it's file and dir*/
File dir = new File(path);
if (dir.exists()) {
File[] tmp = dir.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isDirectory()) {
deleteDir(path + "/" + tmp[i].getName());
} else {
tmp[i].delete();
}
}
/** clear all dirs and files under path and strart del path */
dir.delete();
}
} public static String bufferReadeFile(String filepath){
StringBuffer sb=new StringBuffer();
try{
FileReader reader=new FileReader(filepath);
BufferedReader br =new BufferedReader(reader);
String line;
while((line=br.readLine())!=null){
sb.append(line);
} }catch (IOException e){
e.printStackTrace();
}
/**test output*/
System.out.println(sb.toString());
return sb.toString();
} public static void bufferWriteFile(String filepath){
try{
File filename=new File(filepath);
/** create newfile if doesn't exist,else pass */
if(!filename.exists()) {
filename.createNewFile();
}
try{
FileWriter writer=new FileWriter(filename);
BufferedWriter bw= new BufferedWriter(writer);
/** write content to buffer*/
bw.write(" Java is really awkward");
/** flush content from buffer to file */
bw.flush();
}catch (IOException f){
f.printStackTrace();
}
}catch (IOException e){
e.printStackTrace();
}
} /** Read jsonfile return jsonString */
public static String readJsonFile(String jsonpath){
StringBuffer sb=new StringBuffer();
try {
FileReader reader = new FileReader(new File(jsonpath));
BufferedReader br=new BufferedReader(reader);
String line =null;
while((line=br.readLine())!=null){
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return sb.toString(); }
/** get jsonobject attribute by alibaba fastjson .JsonObject*/
public static JSONObject jsonToJava(String jsonpath){
/** get json string from json file*/
String jsonString=readJsonFile(jsonpath);
/** jsonString to jsonobject*/
JSONObject object = JSONObject
.parseObject(jsonString);
/**
* value = object.get("key")
System.out.println(object.toString());
String str=object.getString("string");
Boolean bool=object.getBoolean("boolean");
List<Object> list=JSONObject.parseArray(object.getJSONArray("list").toString(),Object.class);
System.out.println(list);
*/
return object;
} /** fastjson use:
* 1.fastjson List转JSONArray
* List<T> list = new ArrayList<T>();
* JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
*
*
* 2.fastjson JSONArray转List
* JSONArray array = new JSONArray();
* List<EventColAttr> list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class);
*
*
* 3.fastjson 字符串转List
* String str = "";
* List<T> list = JSONObject.parseArray(str,T.class);
* @param jsonStr
* @return
*/ /** denpendended by fastjson.JSON */
public static Map jsonStrToMap(String jsonStr){
// Map<String,Object> map = JSON.parseObject(jsonStr,Map.class);
Map<String,Object> map = (Map)JSON.parse(jsonStr);
System.out.println(map);
return map;
}
/** 帕布里克,斯泰迪克沃伊得们,让世界从这里感受痛楚吧...*/
public static void main(String[] args) throws InterruptedException {
String path = System.getProperty("user.dir") + "/src/testdir/";
String filename = "test.json";
jsonStrToMap(readJsonFile(path+filename)); }
}
java基础数据类型和处理的更多相关文章
- Java基础-数据类型应用案例展示
Java基础-数据类型应用案例展示 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.把long数据转换成字节数组,把字节数组数据转换成long. /* @author :yinz ...
- Java基础-数据类型int,short,char,long,float,double,boolean,byte
Java语言是静态类型的(statical typed),也就是说所有变量和表达式的类型再编译时就已经完全确定.由于是statical typed,导致Java语言也是强类型(Strong typed ...
- java基础数据类型包装类
*/ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...
- 谈谈Java基础数据类型
Java的基本数据类型 类型 意义 取值 boolean 布尔值 true或false byte 8位有符号整型 -128~127 short 16位有符号整型 -pow(2,15)~pow(2,15 ...
- Java基础数据类型二进制转换
前言: 本文主要介绍java基础类型的二进制转换和二进制的基本概念. 二进制: 1,二进制是以0和1为码,逢2进1,比如3=11=1*2+1. 2,在计算机当中其它进制的算法基本基于2进制,因为计算机 ...
- java基础-数据类型之殇
一 前言 Java的数据类型分为2种,分别是基本数据类型和引用数据类型:java的数据类型是强数据类型,意味着每声明一个变量,其必定有与之对应的数据类型:面试常问的java8大基本数据类型其实是基本数 ...
- Java 基础数据类型
Java 提供的基础数据类型(也称内置数据类型)包含:整数类型.浮点类型.字符类型.布尔类型. 整数类型 整数类型变量用来表示整数的数据类型.整数类型又分为字节型(byte).短整型(short).整 ...
- [未完成]关于java基础数据类型中的一些总结
java基本数据类型转换图: 有时候也把char型成为字符型,是加上字符型也是一种特殊的整数类型.
- 【Demo 0001】Java基础-数据类型
本章学习要点: 1. 了解Java 语言 2. 了解Java程序结构; 3. 了解Java中基本数据类型; 4. 掌握基本数据类型之间的运算 ...
- JAVA基础数据类型
JAVA的数据类型粗略分两种 1.基本数据类型 整数类型: byte,short,int,long 浮点类型: float,double 字符类型: char 布尔类型: boolean 基本语法格式 ...
随机推荐
- 算法导论2-4 O(nlgn)时间复杂度求逆序对
def mergesort(nums,le,ri): if le>ri-2: return 0 mi=le+(ri-le)//2 a=mergesort(nums,le,mi) b=merges ...
- Json.Net的介绍与简单实用(兼容2.0/3.0/3.5/4.5/RT)
本文的前提是你已经熟悉Json,如果您还不知道什么是Json是什么,请自行查看维基百科. 一.Json.Net是什么? Json.Net是一个读写Json效率比较高的.Net框架.Json.Net 使 ...
- telnet不起作用
1.出现 'telnet' 不是内部或外部命令,也不是可运行的程序或批处理文件. 原因:因为本机的Telnet客户端默认是关闭的,所以我们要手动打开 解决方案:打开控制面板–>程序–>打开 ...
- MVC5+EF6 入门完整教程4 :EF基本的CRUD
上篇文章主要讲了如何配置EF, 我们回顾下主要过程: 创建Data Model ---> 创建Database Context --->创建databaseInitializer---&g ...
- 6.springboot----------JSR303校验
JSR303校验(Java Specification Requests的缩写,意思是Java 规范提案) 有一个注解叫:@Validated //数据校验 这是默认的↓ 这是你可以改的↓
- dea创建Maven工程用c3p0连接数据库报错java.sql.SQLException: Connections could not be acquired from the underlying
idea java.sql.SQLException: Connections could not be acquired from the underlying database! 转载自:ht ...
- AOP使用
package com.googosoft.db.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lan ...
- php curl请求 header头携带参数
$headers = array( 'api-key:'.$key, 'authorization:'.$authorization, ); //初始化 $curl = c ...
- input file弹出框选择文件后缀限制
在页面选择文件时的弹出框默认显示的是所有类型的文件,有时候文件太多不好选择,我们就要过滤掉不想展示的文件,这是需要用到input的accept属性,只有在type="file"才有 ...
- springmvc、 springboot 项目全局异常处理
异常在项目中那是不可避免的,通常情况下,我们需要对全局异常进行处理,下面介绍两种比较常用的情况. 准备工作: 在捕获到异常的时候,我们通常需要返回给前端错误码,错误信息等,所以我们需要手动封装一个js ...