Java 语法清单翻译自 egek92 的 JavaCheatSheet,从属于笔者的 Java 入门与实践系列。时间仓促,笔者只是简单翻译了些标题与内容整理,支持原作者请前往原文点赞。需要注意的是,此文在 Reddit 上也引起了广泛的讨论,此文讲解的语法要点还是以 Java 7 为主,未涉及 Java 8 中内容,略显陈旧,读者可以带着批判的视角去看。

Java CheatSheet

01

基础

hello, world! :

if-else:

loops:

do-while:

do { System.out.println("Count is: " + count);count++;} while (count < 11);switch-case:

数组:

二维数组:

对象:

类:

方法:

Java IDE 比较:

图片来自 Wikipedia

个人推荐 IntelliJ IDEA 并且对于 学生免费.

02

字符串操作

字符串比较:

boolean result = str1.equals(str2);boolean result = str1.equalsIgnoreCase(str2);

搜索与检索:

int result = str1.indexOf(str2);int result = str1.indexOf(str2,5);String index = str1.substring(14);

字符串反转:

public classMain { public staticvoid main(String[] args) {String str1 = "whatever string something";StringBuffer str1buff = newStringBuffer(str1);String str1rev = str1buff.reverse().toString(); System.out.println(str1rev); }}

按单词的字符串反转:

publicclass Main {publicstaticvoidmain(String[] args) { String str1 = "reverse this string"; Stack stack = new Stack<>(); StringTokenizer strTok = new StringTokenizer(str1); while(strTok.hasMoreTokens()){stack.push(strTok.nextElement()); } StringBuffer str1rev = new StringBuffer();while(!stack.empty()){ str1rev.append(stack.pop()); str1rev.append(" "); } System.out.println(str1rev);}

大小写转化:

String strUpper = str1.toUpperCase();String strLower = str1.toLowerCase();

首尾空格移除:

String str1 = " asdfsdf ";str1.trim(); //asdfsdf

空格移除:

str1.replace(" ","");

字符串转化为数组:

String str = "tim,kerry,timmy,camden";String[] results = str.split(",");

03

数据结构

重置数组大小:

int[] myArray = newint[10];int[] tmp = newint[myArray.length + 10];System.arraycopy(myArray, , tmp, , myArray.length);myArray = tmp;

集合遍历:

for (Iterator it = map.entrySet().iterator();it.hasNext();){ Map.Entry entry = (Map.Entry)it.next(); Object key = entry.getKey(); Object value = entry.getValue();}

创建映射集合:

HashMap map = new HashMap();map.put(key1,obj1);map.put(key2,obj2);map.put(key2,obj2);

数组排序:

int[] nums = {1,4,7,324,,-4}; Arrays.sort(nums);System.out.println(Arrays.toString(nums));

列表排序:

ListunsortList = new ArrayList();unsortList.add("CCC");unsortList.add("111");unsortList.add("AAA");Collections.sort(unsortList);

列表搜索:

intindex = arrayList.indexOf(obj);

finding an object by value in a hashmap:

hashmap.containsValue(obj);

finding an object by key in a hashmap:

hashmap.containsKey(obj);

二分搜索:

int[] nums = newint[]{7,5,1,3,6,8,9,2};Arrays.sort(nums);int index = Arrays.binarySearch(nums,6);System.out.println("6 is at index: "+ index);

arrayList 转化为 array:

Object[] objects = arrayList.toArray();

将 hashmap 转化为 array:

Object[] objects = hashmap.entrySet().toArray();

04

时间与日期类型

打印时间与日期:

Date todaysDate = newDate(); //todays dateSimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); //date formatString formattedDate = formatter.format(todaysDate);System.out.println(formattedDate);

将日期转化为日历:

Date mDate = newDate();Calendar mCal = Calendar.getInstance();mCal.setTime(mDate);

将 calendar 转化为 date:

Calendar mCal = Calendar.getInstance();Date mDate = mDate.getTime();

字符串解析为日期格式:

publicvoid StringtoDate(String x) throws ParseException{String date = "March 20, 1992 or 3:30:32pm"; DateFormat df = DateFormat.getDateInstance();Date newDate = df.parse(date); }

date arithmetic using date objects:

Date date = newDate();long time = date.getTime();time += 5*24*60*60*1000; //may give a numeric overflow error on IntelliJ IDEADate futureDate = newDate(time);System.out.println(futureDate);

date arithmetic using calendar objects:

Calendar today = Calendar.getInstance();today.add(Calendar.DATE,5);

difference between two dates:

long diff = time1 - time2; diff = diff/(1000*60*60*24);comparing dates:

boolean result = date1.equals(date2);

getting details from calendar:

Calendar cal = Calendar.getInstance();cal.get(Calendar.MONTH);cal.get(Calendar.YEAR);cal.get(Calendar.DAY_OF_YEAR);cal.get(Calendar.WEEK_OF_YEAR);cal.get(Calendar.DAY_OF_MONTH);cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);cal.get(Calendar.DAY_OF_MONTH);cal.get(Calendar.HOUR_OF_DAY);

calculating the elapsed time:

long startTime = System.currentTimeMillis();//times flies by..long finishTime = System.currentTimeMillis();long timeElapsed = startTime-finishTime;System.out.println(timeElapsed);

05

正则表达式

使用 REGEX 寻找匹配字符串:

String pattern = "[TJ]im"; Pattern regPat = Patternpile(pattern,Pattern.CASE_INSENSITIVE); String text = "This is Jim and that's Tim";Matcher matcher = regPat.matcher(text); if (matcher.find()){ String matchedText = matcher.group(); System.out.println(matchedText);}

替换匹配字符串:

String pattern = "[TJ]im";Pattern regPat = Patternpile(pattern,Pattern.CASE_INSENSITIVE); String text = "This is jim and that's Tim";Matcher matcher = regPat.matcher(text);String text2 = matcher.replaceAll("Tom");System.out.println(text2);

使用 StringBuffer 替换匹配字符串:

Pattern p = Patternpile("My");Matcher m = p.matcher("My dad and My mom");StringBuffer sb = newStringBuffer();boolean found = m.find(); while(found){ m.appendReplacement(sb,"Our"); found = m.find();}m.appendTail(sb);System.out.println(sb);

打印所有匹配次数:

String pattern = "\\sa(\\w)*t(\\w)*"; //contains "at"Pattern regPat = Patternpile(pattern);String text = "words something at atte afdgdatdsf hey";Matcher matcher = regPat.matcher(text);while(matcher.find()){ String matched = matcher.group(); System.out.println(matched);}

打印包含固定模式的行:

String pattern = "^a"; Pattern regPat = Patternpile(pattern);Matcher matcher = regPat.matcher("");BufferedReader reader = new BufferedReader(new FileReader("file.txt"));String line; while ((line = reader.readLine())!= null){ matcher.reset(line);if (matcher.find()){ System.out.println(line); }}

匹配新行:

String pattern = "\\d$"; //any single digitString text = "line one\n line two\n line three\n"; Pattern regPat = Patternpile(pattern, Pattern.MULTILINE);Matcher matcher = regPat.matcher(text);while (matcher.find()){ System.out.println(matcher.group());}

regex:

beginning of a string: ^

end of a string: $

0 or 1 times: ?

0 or more times: (*) //without brackets

1 or more times: +

alternative characters: [...]

alternative patterns: |

any character: .

a digit: d

a non-digit: D

whitespace: s

non-whitespace: S

word character: w

non word character: W

06

数字与数学操作处理

内建数据类型:

byte: 8bits, Byte

short: 16bits, Short

long: 64bits, Long

float: 32bits, Float

判断字符串是否为有效数字:

String str = "dsfdfsd54353%%%"; try{ int result = Integer.parseInt(str);}catch (NumberFormatException e){ System.out.println("not valid");}

比较 Double:

Double a = 4.5; Double b= 4.5;boolean result = a.equals(b);if (result) System.out.println("equal");

rounding:

double doubleVal = 43.234234200000000234040324;float floatVal = 2.98f;long longResult = Math.round(doubleVal);int intResult = Math.round(floatVal);System.out.println(longResult + " and " + intResult); // 43 and 3

格式化数字:

double value = 2343.8798;NumberFormat numberFormatter; String formattedValue;numberFormatter = NumberFormat.getNumberInstance();formattedValue = numberFormatter.format(value);System.out.format("%s%n",formattedValue); //2.343,88

格式化货币:

double currency = 234546457.99;NumberFormat currencyFormatter; String formattedCurrency;currencyFormatter = NumberFormat.getCurrencyInstance();formattedCurrency = currencyFormatter.format(currency);System.out.format("%s%n",formattedCurrency); // $ 234.546.457,99

二进制、八进制、十六进制转换:

int val = 25;String binaryStr = Integer.toBinaryString(val);String octalStr = Integer.toOctalString(val);String hexStr = Integer.toHexString(val);

随机数生成:

double rn = Math.random(); int rint = (int) (Math.random()*10); // random int between 0-10System.out.println(rn);System.out.println(rint);

计算三角函数:

doublecos = Math.cos(45);doublesin = Math.sin(45); doubletan = Math.tan(45);

计算对数

double logVal = Math.log(125.5);

Math library:

07

StringBuffer buffer = newStringBuffer();Formatter formatter = new Formatter(buffer, Locale.US);formatter.format("PI: "+Math.PI);System.out.println(buffer.toString());

formatter format calls:

打开文件:

BufferedReader br = new BufferedReader(new FileReader(textFile.txt)); //for readingBufferedWriter bw = new BufferedWriter(new FileWriter(textFile.txt)); //for writing

读取二进制数据:

InputStream is = new FileInputStream(fileName);int offset = ; int bytesRead = is.read(bytes, ofset, bytes.length-offset);

文件随机访问:

File file = new File(something.bin);RandomAccessFile raf = new RandomAccessFile(file,"rw");raf.seek(file.length());

读取 Jar/zip/rar 文件:

ZipFile file =new ZipFile(filename);Enumeration entries = file.entries(); while(entries.hasMoreElements()){ ZipEntry entry = (ZipEntry) entries.nextElement();if (entry.isDirectory()){//do something } else{ //do something }}file.close();

08

文件与目录

创建文件:

File f = new File("textFile.txt");boolean result = f.createNewFile();

文件重命名:

File f = new File("textFile.txt");File newf = new File("newTextFile.txt");boolean result = f.renameto(newf);

删除文件:

File f = new File("somefile.txt");f.delete();

改变文件属性:

File f = new File("somefile.txt");f.setReadOnly(); // making the file read onlyf.setLastModified(desired time);

获取文件大小:

File f = new File("somefile.txt");long length = file.length();

判断文件是否存在:

File f = new File("somefile.txt");boolean status = f.exists();

移动文件:

File f = new File("somefile.txt");File dir = new File("directoryName");boolean success = f.renameTo(new File(dir, file.getName()));

获取绝对路径:

File f = new File("somefile.txt");File absPath = f.getAbsoluteFile();

判断是文件还是目录:

File f = new File("somefile.txt");boolean isDirectory = f.isDirectory();System.out.println(isDirectory); //false

列举目录下文件:

File directory = new File("users/ege");String[] result = directory.list();

创建目录:

boolean result = new File("users/ege").mkdir();

09

网络客户端

服务器连接:

String serverName = "";Socket socket = new Socket(serverName, 80);System.out.println(socket);

网络异常处理:

try { Socket sock = new Socket(server_name, tcp_port); System.out.println("Connected to " + server_name); sock.close( ); } catch (UnknownHostException e) { System.err.println(server_name + " Unknown host"); return; } catch (NoRouteToHostException e) { System.err.println(server_name + " Unreachable" );return; } catch (ConnectException e) { System.err.println(server_name + " connect refused");return; } catch (java.io.IOException e) { System.err.println(server_name + ' ' + e.getMessage( )); return; }

10

包与文档

创建包:

packagecom.ege.example;使用 JavaDoc 注释某个类:

javadoc -d \home\html -sourcepath \home\src -subpackages java

Jar 打包:

jarcfproject.jar *.class

运行 Jar:

java-jarsomething.jar

排序算法

Bubble Sort

Linear Search

Binary Search

Selection Sort

Insertion Sort

精选文章

99%的人都理解错了HTTP中GET与POST的区别

《阿里巴巴Java开发手册》终极版IDE插件

Spring思维导图,让Spring不再难懂(mvc篇)

Spring思维导图,让Spring不再难懂(aop篇)

Spring思维导图,让Spring不再难懂(ioc篇)

Spring思维导图,让spring不再难懂(一)

Spring思维导图,让Spring不再难懂(cache篇)

word java_java操作word相关推荐

  1. php com操作word,php 操作word 的使用com组件的总结

    set_time_limit(0);//不超时error_reporting(E_ALL);//打印所有的错误$empty = new VARIANT(); com_load_typelib('Wor ...

  2. java操作跨页的word cell_Java 操作Word表格——创建嵌套表格、添加/复制表格行或列、设置表格是否禁止跨页断行...

    本文将对如何在Java程序中操作Word表格作进一步介绍.操作要点包括 如何在Word中创建嵌套表格. 对已有表格添加行或者列 复制已有表格中的指定行或者列 对跨页的表格可设置是否禁止跨页断行 创建表 ...

  3. php com操作word,PHP操作word方法(读取和写入)

    PHP操作word方法(读取和写入) 发布于 2014-07-21 22:52:41 | 131 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hypertext ...

  4. html操作word,javascript 操作Word和Excel的实现代码

    1.保存html页面到word 单元格1 单元格2 单元格3 单元格4 单元格合并 test function MakeWord() { var word = new ActiveXObject(&q ...

  5. 关于.net Microsoft.Office.Interop.Word组建操作word的问题,如何控制word表格单元格内部段落的样式。...

    控制word表格单元格内部文字样式.我要将数据导出到word当中,对于word表格一个单元格中的一段文字,要设置不同的样式,比如第一行文字作为标题要居中,加粗,第二行为正常的正文. 代码如下 publ ...

  6. c#调用Aspose.Word组件操作word 插入文字/图片/表格 书签替换套打

    由于NPOI暂时没找到书签内容替换功能,所以换用Apose.Word组件. using System; using System.Collections.Generic; using System.C ...

  7. python操作word文档(python-docx)

    python操作word文档(python-docx) 1. 效果图 1.1 python-docx文档标题段落(等级.加粗.斜体.居中)效果图 1.2 python-docx字体(加粗.斜体.居中. ...

  8. javascript 操作Word和Excel的实现代码

    1.保存html页面到word 复制代码 代码如下: <HTML> <HEAD> <title> </title> </HEAD> < ...

  9. phpexcel_cell 获取表格样式_Java 操作Word表格——创建嵌套表格、添加/复制表格行或列、设置表格是否禁止跨页断行...

    精品推荐 国内稀缺优秀Java全栈课程-Vue+SpringBoot通讯录系统全新发布! Docker快速手上视频教程(无废话版)[免费] 作者:E-iceblue https://www.cnblo ...

最新文章

  1. 目标检测--Focal Loss for Dense Object Detection
  2. 嵌入式开发笔记-存储控制器
  3. Rxjava、Retrofit返回json数据解析异常处理
  4. [置顶] 混响音效
  5. php socket keepalive,linux keepalive探测对应用层socket api的影响
  6. nginx 中文文档
  7. gurobi和java_Gurobi和java和空解决方案
  8. 判断数组、集合list、string、int、double等是否为空,判断是否为值类型
  9. sql join后显示二维数据_大数据交叉报表解决案例(方案)
  10. 华为服务器重装操作系统,华为服务器安装操作系统
  11. 计算机常用的英语单词及缩写,常见计算机英语缩写及单词
  12. 计算机u盘病毒清除方式,彻底清除u盘病毒有什么方法呢
  13. 计算机毕业设计Java出彩校园信息交流平台(源码+系统+mysql数据库+lw文档)
  14. 微信公众号 模板消息开发
  15. 使用kali对同一局域网内的设备进行断网和查看设备图片
  16. 7-3 大炮打蚊子(15 分)
  17. server取出多个最小值 sql_sql-server
  18. 感悟SEO,感悟互联网营销!
  19. Ljava/lang/Class o.s.c.support.DefaultLifecycleProcessor : Failed to stop bean ‘quartzScheduler‘
  20. Cocos2d-x的多线程与异步加载实现详解

热门文章

  1. 基于 Web 的 Java Swing Kiosk 应用程序
  2. SSM实训: 2、博客中间内容(首页2)
  3. mysql fabric HA测试
  4. dell服务器T420装系统,ThinkPad T420笔记本一键u盘装系统win7教程
  5. 线性代数--线性方程组
  6. Python实战小项目—绘制玫瑰花送给女朋友叭
  7. RK3568J edp屏幕点亮 时序调试总结
  8. Kafka:分布式消息系统
  9. php choose handler,Guzzle 源码分析
  10. 产品工作_技术与产品的异同