├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── org │ │ ├── javacore │ │ ├── base │ │ │ ├── String │ │ │ │ ├── StringT.java │ │ │ │ └── StringT2.java │ │ │ ├── copy │ │ │ │ └── CopyT.java │ │ │ └── inter │ │ │ │ ├── ApplyClass.java │ │ │ │ └── ApplyInter.java │ │ ├── colgoogle │ │ │ ├── MapMakerT.java │ │ │ └── MapMakerT0.java │ │ ├── collection │ │ │ ├── PerBtwnAllCollectionsT.java │ │ │ ├── hash │ │ │ │ ├── HashList.java │ │ │ │ └── SkuObj.java │ │ │ ├── list │ │ │ │ ├── ArrayListT.java │ │ │ │ ├── ListT0.java │ │ │ │ └── PerBtwnArlAndLklT.java │ │ │ ├── map │ │ │ │ ├── HashMapObjT.java │ │ │ │ ├── HaspMapT.java │ │ │ │ └── TreeMapT.java │ │ │ ├── queue │ │ │ │ └── PriorityQueueT.java │ │ │ ├── set │ │ │ │ ├── HashSetObjT.java │ │ │ │ ├── HashSetT.java │ │ │ │ ├── HashSetsCopyT.java │ │ │ │ ├── SetContainT.java │ │ │ │ └── TreeSetT.java │ │ │ └── util │ │ │ │ ├── CollectionsT.java │ │ │ │ ├── IterAndListIterT.java │ │ │ │ └── PerBtwnEmptyMapAndHashMapT.java │ │ ├── concurrent │ │ │ └── CountDownLatchT.java │ │ ├── img │ │ │ └── ImgCircleCut.java │ │ ├── initAndCleanup │ │ │ ├── SimpleConstructor.java │ │ │ ├── SimpleConstructor2.java │ │ │ └── VoidConstructor.java │ │ ├── io │ │ │ ├── BufferedInputFileT.java │ │ │ ├── ChangeSystemOut.java │ │ │ ├── CopyFileT.java │ │ │ ├── DirListT.java │ │ │ ├── Directory.java │ │ │ ├── FileIOStreamT.java │ │ │ ├── FileMethodsT.java │ │ │ ├── FileT.java │ │ │ ├── FilenameFilterT.java │ │ │ ├── FormatteMemoryInput.java │ │ │ ├── JavaFileListT.java │ │ │ ├── MemoryInputT.java │ │ │ ├── OSExecuteT.java │ │ │ ├── PipeStreamT.java │ │ │ ├── RandomAccessFileT.java │ │ │ ├── SByteArrayInputStream.java │ │ │ ├── SFileInputStream.java │ │ │ ├── SFileOutputStream.java │ │ │ ├── SInputStream.java │ │ │ ├── SOutputStream.java │ │ │ ├── StoringAndRecoveringData.java │ │ │ ├── SystemStreamT.java │ │ │ ├── TextFile.java │ │ │ ├── UsingRandomAccessFile.java │ │ │ ├── byteoper │ │ │ │ ├── IntegerConvertT.java │ │ │ │ ├── IntegerOperT.java │ │ │ │ ├── LongConvertT.java │ │ │ │ └── StringConvertT.java │ │ │ ├── serializable │ │ │ │ └── SerializableT.java │ │ │ └── zip │ │ │ │ ├── GZIPcompress.java │ │ │ │ └── ZipCompress.java │ │ ├── lambda │ │ │ ├── LambdaListCompare.java │ │ │ ├── LambdaOperators.java │ │ │ └── LambdaRunnable.java │ │ ├── nio │ │ │ ├── AvailableCharSets.java │ │ │ ├── BufferToText.java │ │ │ ├── ChannelCopy.java │ │ │ ├── Endians.java │ │ │ ├── FileChannelT.java │ │ │ ├── FileChannelTransferTo.java │ │ │ ├── FileLocking.java │ │ │ ├── GetChannel.java │ │ │ ├── GetData.java │ │ │ ├── IntBufferDemo.java │ │ │ ├── LargeMappedFiles.java │ │ │ ├── LockingMappedFiles.java │ │ │ ├── MappedIO.java │ │ │ ├── UsingBuffers.java │ │ │ └── ViewBuffers.java │ │ ├── reflection │ │ │ ├── ArrayCopy.java │ │ │ ├── EmployeeClass.java │ │ │ ├── ObjectAnalyzer.java │ │ │ ├── ReflectionTest.java │ │ │ ├── User.java │ │ │ └── UserConstructorReflect.java │ │ ├── rtti │ │ │ ├── ClassInitialization.java │ │ │ └── ShowMethods.java │ │ ├── scheduler │ │ │ ├── SchedulerExecutorTest.java │ │ │ ├── SchedulerExecutorTest2.java │ │ │ └── TimerTest.java │ │ ├── stream │ │ │ ├── CollectStreamTest.java │ │ │ ├── CollectionStreamTest.java │ │ │ ├── CollectionStreamTest01.java │ │ │ ├── ConcatStreamTest.java │ │ │ ├── CountFilterStreamTest.java │ │ │ ├── CreateStreamTest.java │ │ │ ├── DistinctStreamTest.java │ │ │ └── SortedStreamTest.java │ │ ├── thread │ │ │ ├── BasicThreads.java │ │ │ ├── CachedThreadPool.java │ │ │ ├── CallableDemo.java │ │ │ ├── DaemonFromFactory.java │ │ │ ├── DaemonThreadFactory.java │ │ │ ├── DaemonsDontRunFinally.java │ │ │ ├── FixedThreadPool.java │ │ │ ├── LiftOff.java │ │ │ ├── MoreBasicThreads.java │ │ │ ├── MyRunnable.java │ │ │ ├── MyThread.java │ │ │ ├── ProcessBuilderTest.java │ │ │ ├── SimpleDaemons.java │ │ │ ├── SimplePriorities.java │ │ │ ├── SingleThreadExecutor.java │ │ │ ├── SleepRunThread.java │ │ │ ├── SleepingTask.java │ │ │ ├── ThreadInfo.java │ │ │ ├── ThreadInterrupt.java │ │ │ ├── daemon │ │ │ │ ├── CleanerTask.java │ │ │ │ ├── DaemonTest.java │ │ │ │ ├── Event.java │ │ │ │ └── WriterTask.java │ │ │ ├── join │ │ │ │ ├── DSLoader.java │ │ │ │ ├── JoinTest.java │ │ │ │ └── NetLoader.java │ │ │ ├── threadlocal │ │ │ │ ├── SafeTask.java │ │ │ │ ├── SafeTest.java │ │ │ │ ├── UnsafeTask.java │ │ │ │ └── UnsafeTest.java │ │ │ └── uncaughtexp │ │ │ │ ├── ExceptionHadler.java │ │ │ │ ├── UncaughtTask.java │ │ │ │ └── UncaughtTest.java │ │ └── time │ │ │ ├── Duration.java │ │ │ └── TimeUtil.java │ │ └── jee │ │ └── rpc │ │ ├── EchoService.java │ │ ├── EchoServiceImpl.java │ │ ├── RpcExporter.java │ │ ├── RpcImporter.java │ │ └── RpcTest.java └── resources │ ├── collections │ └── 绘图1.vsdx │ └── io │ ├── file │ ├── file.vsdx │ ├── file01.vsdx │ └── filenameFilter.vsdx │ └── iostream │ └── iostream.vsdx └── test └── java └── org └── javacore ├── io └── DirectoryTest.java ├── param ├── Param.java ├── ParamService.java └── ParamTest.java ├── thread ├── MyRunnableTest.java └── MyThreadTest.java └── time ├── DurationTest.java ├── InstantTest.java ├── LocalDateTest.java ├── LocalDateTest1.java ├── LocalDateTest2.java ├── PlayDuration.java └── TimeUtilTest.java /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | # Change these settings to your own preference 10 | indent_style = space 11 | indent_size = 4 12 | 13 | # We recommend you to keep these unchanged 14 | end_of_line = lf 15 | charset = utf-8 16 | trim_trailing_whitespace = true 17 | insert_final_newline = true 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | 22 | [{package,bower}.json] 23 | indent_style = space 24 | indent_size = 2 25 | 26 | [pom.xml] 27 | indent_style = tab 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | out/ 4 | java-core-learning-example.iml 5 | /java-core-learning-example.iml 6 | /.idea/modules.xml 7 | /.idea/vcs.xml 8 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.javacore 7 | java-core-learning-example 8 | 0.0.1-SNAPSHOT 9 | 10 | java core learning example 11 | java core learning example 12 | war 13 | 14 | 15 | 1.0 16 | 17 | 18 | 19 | 20 | com.google.collections 21 | google-collections 22 | ${google-collections.version} 23 | 24 | 25 | 26 | org.projectlombok 27 | lombok 28 | 1.16.8 29 | provided 30 | 31 | 32 | 33 | junit 34 | junit 35 | 4.12 36 | test 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-compiler-plugin 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/base/String/StringT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.base.String; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * @author BYSocket 19 | * @since 2016-01-06 19:51:00 20 | * 常见面试题:String作为方法参数传递,另外一个例子 ${@link StringT2} 21 | * 这就叫做“值传递”,即方法操作的是参数变量(也就是原型变量的一个值的拷贝) 22 | * 改变的也只是原型变量的一个拷贝而已,而非变量本身 23 | */ 24 | public class StringT { 25 | public static void main(String[] args) { 26 | String str = "123"; 27 | change(str); 28 | System.out.println(str); 29 | } 30 | 31 | public static void change(String str) { 32 | str = "456"; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/base/String/StringT2.java: -------------------------------------------------------------------------------- 1 | package org.javacore.base.String; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * @author BYSocket 19 | * @since 2016-01-06 20:07:00 20 | * 对象含有String作为方法参数传递 21 | */ 22 | public class StringT2 { 23 | 24 | public static void main(String[] args) { 25 | StringObject sb = new StringObject(); 26 | sb.setName("123"); 27 | change(sb); 28 | System.out.println(sb.getName()); 29 | } 30 | 31 | public static void change(StringObject sb) { 32 | sb = new StringObject(); 33 | sb.setName("456"); 34 | } 35 | 36 | } 37 | class StringObject { 38 | String name; 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | 44 | public void setName(String name) { 45 | this.name = name; 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/base/copy/CopyT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.base.copy; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-11-16 13:53:51 22 | * 深拷贝与浅拷贝 23 | */ 24 | class Family implements Cloneable{ 25 | private String name; 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | /** 36 | * 深拷贝 37 | * @return 38 | */ 39 | /*@Override 40 | public Object clone() { 41 | Object o = null; 42 | try { 43 | o = super.clone(); 44 | } catch (CloneNotSupportedException e) { 45 | e.printStackTrace(); 46 | } 47 | return o; 48 | }*/ 49 | } 50 | class Student implements Cloneable{ 51 | private String name; 52 | private Family family; 53 | 54 | public String getName() { 55 | return name; 56 | } 57 | 58 | public void setName(String name) { 59 | this.name = name; 60 | } 61 | 62 | public Family getFamily() { 63 | return family; 64 | } 65 | 66 | public void setFamily(Family family) { 67 | this.family = family; 68 | } 69 | 70 | /** 71 | * 浅拷贝 对其对象的引用却没有拷贝 72 | * @return 73 | * @throws CloneNotSupportedException 74 | */ 75 | @Override 76 | protected Object clone() throws CloneNotSupportedException { 77 | return super.clone(); 78 | } 79 | 80 | /** 81 | * 深拷贝 82 | */ 83 | /*@Override 84 | protected Object clone() { 85 | Student o = null; 86 | try { 87 | o = (Student)super.clone(); 88 | } catch (CloneNotSupportedException e) { 89 | e.printStackTrace(); 90 | } 91 | o.family = (Family) family.clone(); 92 | return o; 93 | }*/ 94 | } 95 | 96 | public class CopyT { 97 | public static void main(String[] args) throws CloneNotSupportedException { 98 | Family family = new Family(); 99 | family.setName("Jeff Family"); 100 | Student student1 = new Student(); 101 | student1.setFamily(family); 102 | student1.setName("Jeff"); 103 | 104 | Student student2 = (Student) student1.clone(); 105 | student2.setName("Jeff2"); 106 | student2.getFamily().setName("Jeff2 Family"); 107 | System.out.println(student1.getName() + " " + student1.getFamily().getName()); 108 | System.out.println(student2.getName() + " " + student2.getFamily().getName()); 109 | } 110 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/base/inter/ApplyClass.java: -------------------------------------------------------------------------------- 1 | package org.javacore.base.inter; 2 | 3 | import java.util.Arrays; 4 | 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-12-1 13:04:30 24 | * 不使用接口的接口案例 25 | */ 26 | class Processor { 27 | public String name(){ 28 | return getClass().getSimpleName(); 29 | } 30 | 31 | Object process(Object input){return input;} 32 | } 33 | 34 | class Upcase extends Processor { 35 | @Override 36 | Object process(Object input) { 37 | return ((String)input).toUpperCase(); 38 | } 39 | } 40 | 41 | class Splitcase extends Processor { 42 | @Override 43 | Object process(Object input) { 44 | return Arrays.toString(((String) input).split(" ")); 45 | } 46 | } 47 | 48 | public class ApplyClass { 49 | public static void process(Processor p , Object input){ 50 | System.out.println("调用对象名:" + p.name()); 51 | System.out.println(p.process(input)); 52 | } 53 | 54 | public static String s = "BYSocket's Blog is www.bysocket.com"; 55 | public static void main(String[] args) { 56 | process(new Upcase(),s); 57 | process(new Splitcase(),s); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/base/inter/ApplyInter.java: -------------------------------------------------------------------------------- 1 | package org.javacore.base.inter; 2 | 3 | import java.util.Arrays; 4 | 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-12-1 13:04:30 24 | * 使用接口的接口案例 25 | */ 26 | interface ProcessorInter { 27 | String name(); 28 | 29 | Object process(Object input); 30 | } 31 | 32 | class UpcaseImpl implements ProcessorInter { 33 | @Override 34 | public String name() { 35 | return this.getClass().getSimpleName(); 36 | } 37 | 38 | @Override 39 | public Object process(Object input) { 40 | return ((String)input).toUpperCase(); 41 | } 42 | } 43 | 44 | class SplitcaseImpl implements ProcessorInter { 45 | @Override 46 | public String name() { 47 | return this.getClass().getSimpleName(); 48 | } 49 | 50 | @Override 51 | public Object process(Object input) { 52 | return Arrays.toString(((String) input).split(" ")); 53 | } 54 | } 55 | 56 | public class ApplyInter { 57 | public static void process(ProcessorInter p , Object input){ 58 | System.out.println("调用对象名:" + p.name()); 59 | System.out.println(p.process(input)); 60 | } 61 | 62 | public static String s = "BYSocket's Blog is www.bysocket.com"; 63 | public static void main(String[] args) { 64 | process(new UpcaseImpl(),s); 65 | process(new SplitcaseImpl(),s); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/colgoogle/MapMakerT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.colgoogle; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.collect.MapMaker; 5 | 6 | import java.util.concurrent.ConcurrentMap; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | * Created by 子木 on 2016/2/20. 11 | */ 12 | public class MapMakerT { 13 | // 使用案例:存储验证码 14 | // == <用户唯一,验证码> 15 | // expiration(15, TimeUnit.MINUTES) 有效期15分钟 16 | ConcurrentMap capthcaMap = new MapMaker().expiration(15, TimeUnit.MINUTES).makeMap(); 17 | 18 | // 设置ConcurrentMap的concurrencyLevel参数 ,例如ConcurrentHashMap是用来控制其Segment数组的大小 19 | ConcurrentMap map1 = new MapMaker().concurrencyLevel(8).makeMap(); 20 | 21 | // 构造各种不同reference作为key和value的map 22 | ConcurrentMap map2 = new MapMaker().softKeys().weakValues().makeMap(); 23 | 24 | // 提供当Map里面不包含所get的项,可以自动加入到Map的功能 25 | ConcurrentMap map3 = new MapMaker() 26 | .makeComputingMap( 27 | new Function() { 28 | public Integer apply(String key) { 29 | return 1; 30 | } 31 | } 32 | ); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/colgoogle/MapMakerT0.java: -------------------------------------------------------------------------------- 1 | package org.javacore.colgoogle; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.collect.MapMaker; 5 | 6 | import java.util.concurrent.ConcurrentMap; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | * Created by 子木 on 2016/2/20. 11 | */ 12 | public class MapMakerT0 { 13 | public static void main(String[] args) { 14 | /** 15 | * expiration(3, TimeUnit.SECONDS)设置超时时间为3秒 16 | */ 17 | ConcurrentMap map = new MapMaker().concurrencyLevel(32).softKeys().weakValues() 18 | .expiration(3, TimeUnit.SECONDS).makeComputingMap( 19 | /** 20 | * 提供当Map里面不包含所get的项,可以自动加入到Map的功能 21 | * 可以将这里的返回值放到对应的key的value中 22 | */ 23 | new Function() { 24 | public String apply(String s) { 25 | return "creating " + s + " -> Object"; 26 | } 27 | } 28 | ); 29 | 30 | map.put("a","testa"); 31 | map.put("b","testb"); 32 | 33 | System.out.println(map.get("a")); 34 | System.out.println(map.get("b")); 35 | System.out.println(map.get("c")); 36 | 37 | try { 38 | // 4秒后,大于超时时间,缓存失效。 39 | Thread.sleep(4000); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | 44 | System.out.println(map.get("a")); 45 | System.out.println(map.get("b")); 46 | System.out.println(map.get("c")); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/hash/HashList.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.hash; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by bysocket on 16/9/26. 8 | */ 9 | public class HashList { 10 | public static void main(String[] args) { 11 | // init data list 12 | List reqSkuObjList = new ArrayList<>(); 13 | List existSkuObjList = new ArrayList<>(); 14 | for (int i = 0 ; i < 5000; i++) { 15 | SkuObj skuObj = new SkuObj(); 16 | skuObj.setId(i); 17 | skuObj.setName("name" + i); 18 | skuObj.setAge(i + 666); 19 | skuObj.setDesc("desc" + i); 20 | reqSkuObjList.add(skuObj); 21 | } 22 | 23 | for (int i = 0 ; i < 5000; i++) { 24 | SkuObj skuObj = new SkuObj(); 25 | skuObj.setId(i); 26 | skuObj.setName("nameexist" + i); 27 | skuObj.setAge(i + 888); 28 | skuObj.setDesc("descexist" + i); 29 | existSkuObjList.add(skuObj); 30 | } 31 | 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/hash/SkuObj.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.hash; 2 | 3 | /** 4 | * Created by bysocket on 16/9/26. 5 | */ 6 | public class SkuObj { 7 | 8 | Integer id; 9 | 10 | String name; 11 | 12 | Integer age; 13 | 14 | String desc; 15 | 16 | public Integer getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Integer id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public Integer getAge() { 33 | return age; 34 | } 35 | 36 | public void setAge(Integer age) { 37 | this.age = age; 38 | } 39 | 40 | public String getDesc() { 41 | return desc; 42 | } 43 | 44 | public void setDesc(String desc) { 45 | this.desc = desc; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/list/ArrayListT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.list; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-6-18 21:05:38 25 | * ArrayList的使用 26 | */ 27 | public class ArrayListT{ 28 | 29 | public static void main(String[] args){ 30 | listMethods(); 31 | } 32 | 33 | /** 34 | * 测试ArrayList基本操作方法,其角标的使用及迭代器next()的使用。 35 | */ 36 | @SuppressWarnings({ "rawtypes", "unchecked" }) 37 | public static void listMethods(){ 38 | List a1 = new ArrayList(); 39 | a1.add("List01"); 40 | a1.add("List03"); 41 | a1.add("List04"); 42 | System.out.print("原来集合:\n\t"+a1+"\n"); 43 | a1.add(1,"List02"); 44 | System.out.print("指定角标1插入:\n\t"+a1+"\n"); 45 | a1.remove(2); 46 | System.out.print("指定角标2删除:\n\t"+a1+"\n"); 47 | System.out.print("指定角标2查询:\n\t"+a1.get(2)+"\n"); 48 | 49 | Iterator i1 = a1.iterator(); 50 | System.out.println("用迭代器查询全部元素:"); 51 | while (i1.hasNext()) 52 | System.out.print(i1.next()+"\t"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/list/ListT0.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.list; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.ListIterator; 20 | 21 | /** 22 | * @author BYSocket 23 | * @since 2016-01-06 20:11:00 24 | * 打印list 全部元素,并找到其中元素aaa删除。要求:所有元素都遍历完 25 | * ListIterator 的使用 26 | * list那个remove回抛异常是因为快速失败的机制, 27 | * 他内置了一个modifyCount的变量记录list的长度变化,用Iter可以删除掉 28 | */ 29 | public class ListT0 { 30 | public static void main(String[] args) { 31 | List list =new ArrayList<>(); 32 | list.add("1"); 33 | list.add("2"); 34 | list.add("3"); 35 | list.add("4"); 36 | list.add("aaa"); 37 | list.add("6"); 38 | list.add("7"); 39 | 40 | ListIterator listIterator = list.listIterator(); 41 | while (listIterator.hasNext()) { 42 | Object o = listIterator.next(); 43 | System.out.println(o); 44 | if (o.equals("aaa")) { 45 | listIterator.remove(); 46 | } 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/list/PerBtwnArlAndLklT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.list; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-6-18 21:05:38 24 | * ArrayList与LinkedList性能的对比 25 | */ 26 | public class PerBtwnArlAndLklT{ 27 | 28 | public static void main(String[] args) { 29 | testPerBtwnArlAndLkl(); 30 | } 31 | 32 | /** 33 | * ArrayList与LinkedList各方法性能的对比 34 | */ 35 | public static void testPerBtwnArlAndLkl(){ 36 | ArrayList arrayList = new ArrayList(); 37 | LinkedList linkedList = new LinkedList(); 38 | 39 | // ArrayList add方法 40 | long startTime = System.nanoTime(); 41 | long endTime; 42 | long duration; 43 | for (int i = 0; i < 100000; i++) 44 | arrayList.add(i); 45 | endTime = System.nanoTime(); 46 | duration = endTime - startTime; 47 | System.out.println("ArrayList add: " + duration); 48 | 49 | // LinkedList add方法 50 | startTime = System.nanoTime(); 51 | for (int i = 0; i < 100000; i++) 52 | linkedList.add(i); 53 | endTime = System.nanoTime(); 54 | duration = endTime - startTime; 55 | System.out.println("LinkedList add: " + duration); 56 | 57 | // ArrayList get方法 58 | startTime = System.nanoTime(); 59 | for (int i = 0; i < 10000; i++) 60 | arrayList.get(i); 61 | endTime = System.nanoTime(); 62 | duration = endTime - startTime; 63 | System.out.println("ArrayList get: " + duration); 64 | 65 | // LinkedList get方法 66 | startTime = System.nanoTime(); 67 | for (int i = 0; i < 10000; i++) 68 | linkedList.get(i); 69 | endTime = System.nanoTime(); 70 | duration = endTime - startTime; 71 | System.out.println("LinkedList get: " + duration); 72 | 73 | // ArrayList remove方法 74 | startTime = System.nanoTime(); 75 | for (int i = 9999; i >=0; i--) 76 | arrayList.remove(i); 77 | endTime = System.nanoTime(); 78 | duration = endTime - startTime; 79 | System.out.println("ArrayList remove: " + duration); 80 | 81 | // LinkedList remove方法 82 | startTime = System.nanoTime(); 83 | for (int i = 9999; i >=0; i--) 84 | linkedList.remove(i); 85 | endTime = System.nanoTime(); 86 | duration = endTime - startTime; 87 | System.out.println("LinkedList remove: " + duration); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/map/HashMapObjT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.map; 2 | 3 | import java.util.HashMap; 4 | 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-6-18 22:05:44 24 | * HashMap 操作对象的决定因子:hashCode与equals 25 | */ 26 | public class HashMapObjT{ 27 | public static void main(String[] args){ 28 | HashMap hashMapA = new HashMap(); 29 | hashMapA.put(new A(), 10); 30 | hashMapA.put(new A(), 5); 31 | System.out.println("HashMapA Elements:"); 32 | System.out.print("\t" + hashMapA + "\n"); 33 | 34 | HashMap hashMapB = new HashMap(); 35 | hashMapB.put(new B(), 10); 36 | hashMapB.put(new B(), 5); 37 | System.out.println("HashMapB Elements:"); 38 | System.out.print("\t" + hashMapB + "\n"); 39 | 40 | HashMap hashMapC = new HashMap(); 41 | hashMapC.put(new C(), 10); 42 | hashMapC.put(new C(), 5); 43 | System.out.println("HashMapC Elements:"); 44 | System.out.print("\t" + hashMapC + "\n"); 45 | } 46 | } 47 | 48 | class A{ 49 | public boolean equals(Object obj){ 50 | return true; 51 | } 52 | } 53 | 54 | class B{ 55 | public int hashCode(){ 56 | return 1; 57 | } 58 | } 59 | 60 | class C{ 61 | public int hashCode(){ 62 | return 2; 63 | } 64 | 65 | public boolean equals(Object obj){ 66 | return true; 67 | } 68 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/map/HaspMapT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.map; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-6-18 21:36:04 23 | * HashMap的Add方法 24 | */ 25 | public class HaspMapT{ 26 | public static void main(String[] args) 27 | { 28 | objOper(); 29 | nullOper(); 30 | } 31 | 32 | /** 33 | * HaspMap操作对象方法 34 | */ 35 | public static void objOper(){ 36 | Map employees = new HashMap(); 37 | 38 | String number = "1206010035"; 39 | //设置对象 40 | employees.put(number, new Employee()); 41 | System.out.println(employees); 42 | 43 | // 获取对象 44 | System.out.println(employees.get(number)); 45 | } 46 | 47 | /** 48 | * HaspMap的put方法 49 | */ 50 | @SuppressWarnings({ "unchecked", "rawtypes" }) 51 | public static void nullOper(){ 52 | Map map = new HashMap(); 53 | map.put(null, "null01"); 54 | map.put(null, "null02"); 55 | System.out.println(map); 56 | System.out.println(map.get(null)); 57 | } 58 | } 59 | class Employee 60 | {} -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/map/TreeMapT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.map; 2 | 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-6-18 21:36:04 23 | * TreeMap 的使用 24 | */ 25 | public class TreeMapT 26 | { 27 | @SuppressWarnings({ "rawtypes", "unchecked" }) 28 | public static void main(String[] args) 29 | { 30 | Map map = new TreeMap(); 31 | map.put("1", "1"); 32 | map.put("4", "4"); 33 | map.put("2", "2"); 34 | map.put("2", "3"); 35 | // 注意排序 36 | System.out.println(map); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/queue/PriorityQueueT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.queue; 2 | 3 | import java.util.PriorityQueue; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-6-17 23:32:30 23 | * PriorityQueue的使用 24 | */ 25 | public class PriorityQueueT { 26 | public static void main(String[] args) { 27 | int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 }; 28 | PriorityQueue pq1 = new PriorityQueue(); 29 | 30 | for (int x : ia) 31 | pq1.offer(x); 32 | // 注意排序 33 | System.out.println("pq1: " + pq1); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/set/HashSetObjT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.set; 2 | 3 | import java.util.HashSet; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-6-19 15:41:03 23 | * HashSet 操作对象的决定因子:hashCode与equals 24 | */ 25 | public class HashSetObjT{ 26 | @SuppressWarnings({ "rawtypes", "unchecked" }) 27 | public static void main(String[] args){ 28 | HashSet objs = new HashSet(); 29 | objs.add(new A()); 30 | objs.add(new B()); 31 | objs.add(new C()); 32 | objs.add(new A()); 33 | objs.add(new B()); 34 | objs.add(new C()); 35 | System.out.println("HashSet Elements:"); 36 | System.out.print("\t" + objs + "\n"); 37 | } 38 | } 39 | class A { 40 | public boolean equals(Object obj){ 41 | return true; 42 | } 43 | } 44 | 45 | class B { 46 | public int hashCode(){ 47 | return 1; 48 | } 49 | } 50 | 51 | class C { 52 | public int hashCode(){ 53 | return 2; 54 | } 55 | 56 | public boolean equals(Object obj){ 57 | return true; 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/set/HashSetT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.set; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-6-19 15:46:37 24 | * HashSet的Add方法 25 | */ 26 | public class HashSetT{ 27 | @SuppressWarnings({ "rawtypes", "unchecked" }) 28 | public static void main(String[] args){ 29 | Set h1 = new HashSet(); 30 | h1.add("List"); 31 | h1.add(new String("List")); 32 | h1.add("List"); 33 | h1.add("Set"); 34 | h1.add("Queue"); 35 | h1.add("Map"); 36 | // 注意排序 37 | System.out.println("HashSet Elements:"); 38 | System.out.print("\t" + h1 + "\n"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/set/HashSetsCopyT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.set; 2 | 3 | import java.util.HashSet; 4 | import java.util.LinkedHashSet; 5 | import java.util.Set; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-6-18 21:02:07 25 | * HashSet及其子类的转换使用 26 | */ 27 | public class HashSetsCopyT{ 28 | 29 | @SuppressWarnings({ "rawtypes", "unchecked" }) 30 | public static void main(String[] args){ 31 | Set s1 = new HashSet(); 32 | s1.add("List"); 33 | s1.add("Queue"); 34 | s1.add("Set"); 35 | s1.add("Map"); 36 | 37 | System.out.println("HashSet Elements:"); 38 | System.out.print("\t" + s1 + "\n"); 39 | 40 | Set s2 = copy(s1); 41 | System.out.println("HashSet Elements After Copy:"); 42 | System.out.print("\t" + s2 + "\n"); 43 | } 44 | 45 | @SuppressWarnings({ "rawtypes", "unchecked" }) 46 | public static Set copy(Set set) { 47 | Set setCopy = new LinkedHashSet(set); 48 | return setCopy; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/set/SetContainT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.set; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-6-19 15:46:37 25 | * Set的Contains方法 26 | */ 27 | public class SetContainT { 28 | public static void main(String[] args) { 29 | HashSet s1 = new HashSet(Arrays.asList(1,2,3)); 30 | HashSet s2 = new HashSet(Arrays.asList(4,2,5)); 31 | 32 | System.out.println(getUnion(s1, s2)); 33 | } 34 | 35 | /** 36 | * 获取Set中不同对象的个数 37 | * @param s1 38 | * @param s2 39 | * @return 40 | */ 41 | public static int getUnion(Set s1,Set s2){ 42 | int count = s1.size(); 43 | for( Object obj : s2){ 44 | if (!s1.contains(obj)) 45 | count++; 46 | } 47 | return count; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/set/TreeSetT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.set; 2 | 3 | import java.util.Iterator; 4 | import java.util.TreeSet; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-6-19 15:46:37 24 | * TreeSet操作已实现Comparable接口的对象 25 | */ 26 | public class TreeSetT{ 27 | public static void main(String[] args){ 28 | TreeSet bSet = new TreeSet(); 29 | bSet.add(new Bird(1)); 30 | bSet.add(new Bird(3)); 31 | bSet.add(new Bird(2)); 32 | 33 | // 注意排序 34 | Iterator iter = bSet.iterator(); 35 | while (iter.hasNext()){ 36 | Bird bird = (Bird) iter.next(); 37 | System.out.println(bird); 38 | } 39 | } 40 | } 41 | /** 42 | * Bird对象 实现了Comparable接口 43 | */ 44 | class Bird implements Comparable{ 45 | int size; 46 | public Bird(int s){ 47 | size = s; 48 | } 49 | 50 | public String toString(){ 51 | return size + "号鸟"; 52 | } 53 | 54 | @Override 55 | public int compareTo(Bird o){ 56 | return size - o.size; 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/util/CollectionsT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-6-17 23:32:30 25 | * Collections的使用 26 | */ 27 | public class CollectionsT{ 28 | public static void main(String[] args){ 29 | // 测试集合工具类Sort方法 30 | testSort(); 31 | testAddAll(); 32 | } 33 | 34 | /** 35 | * 测试集合工具类Sort方法 36 | */ 37 | private static void testSort(){ 38 | List list = new ArrayList(); 39 | list.add(1); 40 | list.add(3); 41 | list.add(2); 42 | list.add(4); 43 | // 调用集合工具类Sort方法 44 | Collections.sort(list); 45 | 46 | System.out.println("list sorted:"); 47 | System.out.print("\t" + list + "\n"); 48 | } 49 | 50 | private static void testAddAll() { 51 | List list = new ArrayList<>(); 52 | list.add("s2"); 53 | list.add("s4"); 54 | list.add("s1"); 55 | list.add("s3"); 56 | System.out.println(list); 57 | Collections.addAll(list, "s5","s7",null,"s9"); 58 | System.out.println(list); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/util/IterAndListIterT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | import java.util.ListIterator; 7 | 8 | /* 9 | * Copyright [2015] [Jeff Lee] 10 | * 11 | * Licensed under the Apache License, Version 2.0 (the "License"); 12 | * you may not use this file except in compliance with the License. 13 | * You may obtain a copy of the License at 14 | * 15 | * http://www.apache.org/licenses/LICENSE-2.0 16 | * 17 | * Unless required by applicable law or agreed to in writing, software 18 | * distributed under the License is distributed on an "AS IS" BASIS, 19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | * See the License for the specific language governing permissions and 21 | * limitations under the License. 22 | */ 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-6-18 21:36:04 27 | * Iterator与ListIterator的区别 28 | */ 29 | public class IterAndListIterT { 30 | 31 | public static void main(String[] args) { 32 | //iterator(); 33 | listIterator(); 34 | } 35 | 36 | /** 37 | * 并发修改异常产生。 38 | * 原因:Iterator(Object obj = it.next()) 会检查HashMap的size, 39 | * size发生变化,抛出错误ConcurrentModificationException。 40 | */ 41 | @SuppressWarnings({ "unchecked", "rawtypes" }) 42 | public static void iterator(){ 43 | List a1 = new ArrayList(); 44 | a1.add("List01"); 45 | a1.add("List02"); 46 | a1.add("List04"); 47 | a1.add("List05"); 48 | 49 | Iterator i1 = a1.iterator(); 50 | while (i1.hasNext()){ 51 | Object obj = i1.next(); 52 | if (obj.equals("List02")) 53 | a1.add("List03"); 54 | } 55 | 56 | System.out.print("集合:\n\t"+a1+"\n"); 57 | } 58 | 59 | /** 60 | * ListIterator可以实现对象的修改。 61 | */ 62 | @SuppressWarnings({ "unchecked", "rawtypes" }) 63 | public static void listIterator(){ 64 | List a1 = new ArrayList(); 65 | a1.add("List01"); 66 | a1.add("List"); 67 | a1.add("List03"); 68 | a1.add("List04"); 69 | 70 | ListIterator l1 = a1.listIterator(); 71 | while (l1.hasNext()){ 72 | Object obj = l1.next(); 73 | if (obj.equals("List")){ 74 | l1.remove(); 75 | l1.add("List02"); 76 | } 77 | } 78 | System.out.print("集合:\n\t"+a1+"\n"); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/collection/util/PerBtwnEmptyMapAndHashMapT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.collection.util; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-6-19 16:03:10 25 | * Collections.EMPTY_MAP 与 new HashMap 性能对比 26 | * 场景:webservice接口,根据某些条件直接返回空Map,则使用Collections.EMPTY_MAP。 27 | */ 28 | public class PerBtwnEmptyMapAndHashMapT { 29 | @SuppressWarnings({"unused", "rawtypes"}) 30 | public static void main(String[] args) { 31 | long startTime = System.nanoTime(); 32 | long endTime; 33 | long duration; 34 | for (int i = 0; i < 100000000; i++) { 35 | Map map = Collections.EMPTY_MAP; 36 | } 37 | endTime = System.nanoTime(); 38 | duration = endTime - startTime; 39 | System.out.println("Collections.EMPTY_MAP: " + duration); 40 | 41 | startTime = System.nanoTime(); 42 | for (int i = 0; i < 100000000; i++) { 43 | Map map = new HashMap<>(); 44 | } 45 | endTime = System.nanoTime(); 46 | duration = endTime - startTime; 47 | System.out.println("new HashMap: " + duration); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/concurrent/CountDownLatchT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.concurrent; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.CountDownLatch; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | * 同步辅助类:完成一组线程执行前,使得一个或多个线程一直等待 11 | * 12 | * Created by bysocket on 16/4/26. 13 | */ 14 | public class CountDownLatchT { 15 | 16 | // 线程中止的计数器 17 | private final static int COUNT = 10; 18 | private final static CountDownLatch count = new CountDownLatch(COUNT); 19 | 20 | // 线程池 21 | private final static ExecutorService service = Executors.newFixedThreadPool(5); 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | for (int i = 0; i < COUNT; i++) { 25 | service.execute(() -> { 26 | try { 27 | int time = new Random().nextInt(5); 28 | TimeUnit.SECONDS.sleep(time); 29 | System.out.printf("Thread %s ## 耗时:%d\n", Thread.currentThread().getId(), time); 30 | // 线程结束后,计数器减一 31 | count.countDown(); 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } 35 | 36 | }); 37 | } 38 | 39 | // 主线程一直被阻塞,直到count为0,实现线程同步 40 | count.await(); 41 | service.shutdown(); 42 | 43 | System.out.println("同步线程执行组结束!"); 44 | 45 | } 46 | } 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/img/ImgCircleCut.java: -------------------------------------------------------------------------------- 1 | package org.javacore.img; 2 | 3 | import javax.imageio.ImageIO; 4 | import java.awt.*; 5 | import java.awt.geom.Ellipse2D; 6 | import java.awt.image.BufferedImage; 7 | import java.io.File; 8 | import java.io.IOException; 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2016-06-28 14:05:26 28 | * 图片裁成椭圆 29 | */ 30 | public class ImgCircleCut { 31 | 32 | public static boolean ImgCircleCut(String srcFile, String targetFile) { 33 | try { 34 | // 获取img的BufferedImage对象,可以考虑创建不带透明色的BufferedImage对象:BufferedImage.TYPE_INT_ARGB 35 | BufferedImage srcBi = ImageIO.read(new File(srcFile)); 36 | // 创建一个带透明色的BufferedImage对象 37 | BufferedImage targetBi = new BufferedImage(srcBi.getWidth(), srcBi.getHeight(), 38 | BufferedImage.TYPE_INT_ARGB); 39 | // 获取img窗体矩形定义的椭圆 40 | Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, 41 | srcBi.getWidth(), srcBi.getHeight()); 42 | // 创建目标图的Graphics2D对象 43 | Graphics2D g2 = targetBi.createGraphics(); 44 | // 创建不透明 SRC_OVER 规则的 AlphaComposite 对象 45 | AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f); 46 | g2.setComposite(ac); 47 | g2.setBackground(new Color(22, 2, 2, 0)); 48 | // 是圆形 还是 椭圆 自定义参数 49 | g2.fill3DRect(200, 200, 180, 80, false); 50 | g2.setClip(shape); 51 | g2.drawImage(srcBi, 0, 0, null); 52 | g2.dispose(); 53 | ImageIO.write(targetBi, "png", new File(targetFile)); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | return false; 57 | } 58 | return true; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/initAndCleanup/SimpleConstructor.java: -------------------------------------------------------------------------------- 1 | package org.javacore.initAndCleanup; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-9-7 16:54:19 21 | * 简单构造器的展示 22 | */ 23 | public class SimpleConstructor { 24 | public static void main(String[] args) { 25 | for (int i = 0; i < 10; i++) { 26 | new Child(); 27 | } 28 | } 29 | } 30 | 31 | // Child类 32 | class Child { 33 | Child() { // Child类的构造器 34 | System.out.print("Child init... "); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/initAndCleanup/SimpleConstructor2.java: -------------------------------------------------------------------------------- 1 | package org.javacore.initAndCleanup; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-9-7 16:54:19 21 | * 带参数简单构造器的展示 22 | */ 23 | public class SimpleConstructor2 { 24 | public static void main(String[] args) { 25 | for (int i = 0; i < 10; i++) { 26 | new Child2(i); 27 | } 28 | } 29 | } 30 | 31 | // Child类 32 | class Child2 { 33 | Child2(int i) {// 带参数的Child类构造器 34 | System.out.print("Child init " + i + " "); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/initAndCleanup/VoidConstructor.java: -------------------------------------------------------------------------------- 1 | package org.javacore.initAndCleanup; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-9-8 09:31:12 21 | * 默认构造函数和方法的区别 22 | */ 23 | public class VoidConstructor { 24 | 25 | VoidConstructor(){ 26 | // this is a constructor 27 | } 28 | 29 | void VoidConstructor() { 30 | // this is a method,not a constructor 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/BufferedInputFileT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | 8 | /* 9 | * Copyright [2015] [Jeff Lee] 10 | * 11 | * Licensed under the Apache License, Version 2.0 (the "License"); 12 | * you may not use this file except in compliance with the License. 13 | * You may obtain a copy of the License at 14 | * 15 | * http://www.apache.org/licenses/LICENSE-2.0 16 | * 17 | * Unless required by applicable law or agreed to in writing, software 18 | * distributed under the License is distributed on an "AS IS" BASIS, 19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | * See the License for the specific language governing permissions and 21 | * limitations under the License. 22 | */ 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-7-14 08:54:24 27 | * 缓冲输入文件 28 | */ 29 | public class BufferedInputFileT { 30 | 31 | /** 32 | * 通过文件名,读取文件并缓冲 33 | * @param filename 34 | * @return 35 | * @throws IOException 36 | */ 37 | public static String read(String filename) 38 | throws IOException { 39 | // 通过行读取输入 40 | BufferedReader in = new BufferedReader(new FileReader(filename)); 41 | String s; 42 | StringBuilder sb = new StringBuilder(); 43 | while((s = in.readLine()) != null) 44 | sb.append(s + "\n");// 不考了线程安全,StringBuilder 比 StringBuffer效率高 45 | // 关闭文件 46 | in.close(); 47 | return sb.toString(); 48 | } 49 | 50 | public static void main(String[] rags) throws IOException { 51 | // 缓冲输入文件,并打印 52 | System.out.println(read( 53 | "src" + File.separator + 54 | "org" + File.separator + 55 | "javacore" + File.separator + 56 | "io" + File.separator + 57 | "BufferedInputFileT.java")); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/ChangeSystemOut.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.PrintWriter; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-10-6 18:38:15 23 | * 改变System.out输出案例 24 | */ 25 | public class ChangeSystemOut { 26 | public static void main(String[] args) { 27 | PrintWriter out = new PrintWriter(System.out,true); 28 | out.println("Hello PrintWriter"); 29 | out.close(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/CopyFileT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | 8 | /* 9 | * Copyright [2015] [Jeff Lee] 10 | * 11 | * Licensed under the Apache License, Version 2.0 (the "License"); 12 | * you may not use this file except in compliance with the License. 13 | * You may obtain a copy of the License at 14 | * 15 | * http://www.apache.org/licenses/LICENSE-2.0 16 | * 17 | * Unless required by applicable law or agreed to in writing, software 18 | * distributed under the License is distributed on an "AS IS" BASIS, 19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | * See the License for the specific language governing permissions and 21 | * limitations under the License. 22 | */ 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-8-11 11:44:59 27 | * 文件复制 28 | */ 29 | public class CopyFileT { 30 | public static void main(String[] args) throws IOException { 31 | String dir = "src" + File.separator + 32 | "org" + File.separator + 33 | "javacore" + File.separator + 34 | "io"; 35 | 36 | copyFile(dir + File.separator + "/CopyFileT.java", "D://Copy.java"); 37 | } 38 | 39 | public static void copyFile(String srcFile,String destFile) 40 | throws IOException { 41 | copyFile(new File(srcFile), new File(destFile)); 42 | } 43 | 44 | public static void copyFile(File srcFile,File destFile) 45 | throws IOException { 46 | // 文件不存在 47 | if (!srcFile.exists()) { 48 | throw new IllegalArgumentException("文件:" + srcFile + "不存在"); 49 | } 50 | // 文件不是文件类型 51 | if (!srcFile.isFile()) { 52 | throw new IllegalArgumentException(srcFile + "不是文件"); 53 | } 54 | FileInputStream in = new FileInputStream(srcFile); 55 | FileOutputStream out = new FileOutputStream(destFile); 56 | byte[] bytes = new byte[2 * 1024]; 57 | int b; 58 | while ((b=in.read(bytes, 0, bytes.length)) != -1) { 59 | out.write(bytes, 0, b); 60 | out.flush(); 61 | } 62 | out.close(); 63 | in.close(); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/DirListT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.util.Arrays; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-7-13 07:58:56 24 | * 列出目录并排序 25 | */ 26 | public class DirListT { 27 | public static void main(String[] args) { 28 | // 获取当前目录 29 | File path = new File(".");// .表示当前目录 30 | // 文件路径名数组 31 | String list[] = path.list(); 32 | 33 | // 对String文件名进行排序 34 | Arrays.sort(list,String.CASE_INSENSITIVE_ORDER); 35 | 36 | // 打印 37 | for(String dirItem : list) 38 | System.out.println(dirItem); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/Directory.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.FilenameFilter; 5 | import java.util.ArrayList; 6 | import java.util.Iterator; 7 | import java.util.List; 8 | import java.util.regex.Pattern; 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-7-13 09:17:11 28 | * 目录实用工具 29 | */ 30 | public final class Directory { 31 | 32 | public static File[] local(File dir,final String regex){ 33 | return dir.listFiles(new FilenameFilter() { // 文件过滤接口 34 | private Pattern pattern = Pattern.compile(regex); 35 | 36 | @Override 37 | public boolean accept(File dir, String name) { 38 | return pattern.matcher(new File(name).getName()).matches(); 39 | } 40 | }); 41 | } 42 | 43 | public static File[] local(String path, final String regex){ 44 | return local(new File(path),regex); 45 | } 46 | 47 | public static class TreeInfo implements Iterable{ 48 | public List files = new ArrayList<>(); 49 | public List dirs = new ArrayList<>(); 50 | 51 | @Override 52 | public Iterator iterator() { 53 | return files.iterator(); 54 | } 55 | 56 | public void addAll(TreeInfo other) { 57 | files.addAll(other.files); 58 | dirs.addAll(other.dirs); 59 | } 60 | 61 | @Override 62 | public String toString() { 63 | return "dirs: " + dirs + 64 | "\n\nfiles: " + files; 65 | } 66 | } 67 | 68 | public static TreeInfo walk(String start,String regex) { 69 | return recuresDirs(new File(start),regex); 70 | } 71 | 72 | public static TreeInfo walk(File start,String regex) { 73 | return recuresDirs(start, regex); 74 | } 75 | 76 | public static TreeInfo walk(File start) { 77 | return recuresDirs(start, ".*");// 全部 78 | } 79 | 80 | public static TreeInfo walk(String start) { 81 | return recuresDirs(new File(start), ".*");// 全部 82 | } 83 | 84 | public static TreeInfo recuresDirs(File startDir,String regex) { 85 | TreeInfo result = new TreeInfo(); 86 | for(File item : startDir.listFiles()) { 87 | if (item.isDirectory()) { 88 | result.dirs.add(item); 89 | result.addAll(recuresDirs(item, regex)); 90 | } else 91 | if (item.getName().matches(regex)) 92 | result.files.add(item); 93 | } 94 | return result; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/FileIOStreamT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | 8 | /* 9 | * Copyright [2015] [Jeff Lee] 10 | * 11 | * Licensed under the Apache License, Version 2.0 (the "License"); 12 | * you may not use this file except in compliance with the License. 13 | * You may obtain a copy of the License at 14 | * 15 | * http://www.apache.org/licenses/LICENSE-2.0 16 | * 17 | * Unless required by applicable law or agreed to in writing, software 18 | * distributed under the License is distributed on an "AS IS" BASIS, 19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | * See the License for the specific language governing permissions and 21 | * limitations under the License. 22 | */ 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-10-8 20:06:03 27 | * FileInputStream&FileOutputStream使用案例 28 | */ 29 | public class FileIOStreamT { 30 | private static final String thisFilePath = 31 | "src" + File.separator + 32 | "org" + File.separator + 33 | "javacore" + File.separator + 34 | "io" + File.separator + 35 | "FileIOStreamT.java"; 36 | public static void main(String[] args) throws IOException { 37 | // 创建文件输入流 38 | FileInputStream fileInputStream = new FileInputStream(thisFilePath); 39 | // 创建文件输出流 40 | FileOutputStream fileOutputStream = new FileOutputStream("data.txt"); 41 | 42 | // 创建流的最大字节数组 43 | byte[] inOutBytes = new byte[fileInputStream.available()]; 44 | // 将文件输入流读取,保存至inOutBytes数组 45 | fileInputStream.read(inOutBytes); 46 | // 将inOutBytes数组,写出到data.txt文件中 47 | fileOutputStream.write(inOutBytes); 48 | 49 | fileOutputStream.close(); 50 | fileInputStream.close(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/FileMethodsT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-7-13 10:06:28 23 | * File方法详细使用 24 | */ 25 | public class FileMethodsT { 26 | 27 | private static void fileData(File f) { 28 | System.out.println( 29 | " 绝对路径:" + f.getAbsolutePath() + 30 | "\n 可读:" + f.canRead() + 31 | "\n 可写:" + f.canWrite() + 32 | "\n 文件名:" + f.getName() + 33 | "\n 上级目录:" + f.getParent() + 34 | "\n 相对地址:" + f.getPath() + 35 | "\n 长度:" + f.length() + 36 | "\n 最近修改时间:" + f.lastModified() 37 | ); 38 | if(f.isFile()) 39 | System.out.println(" 是一个文件"); 40 | else if(f.isDirectory()) 41 | System.out.println(" 是一个目录"); 42 | } 43 | 44 | public static void main(String[] args) { 45 | // 获取src目录 46 | File file = new File("src"); 47 | // file详细操作 48 | fileData(file); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/FileT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | import java.io.IOException; 20 | /* 21 | * Copyright [2015] [Jeff Lee] 22 | * 23 | * Licensed under the Apache License, Version 2.0 (the "License"); 24 | * you may not use this file except in compliance with the License. 25 | * You may obtain a copy of the License at 26 | * 27 | * http://www.apache.org/licenses/LICENSE-2.0 28 | * 29 | * Unless required by applicable law or agreed to in writing, software 30 | * distributed under the License is distributed on an "AS IS" BASIS, 31 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 32 | * See the License for the specific language governing permissions and 33 | * limitations under the License. 34 | */ 35 | 36 | /** 37 | * @author Jeff Lee 38 | * @since 2015-6-30 14:21:47 39 | * File类的使用 40 | */ 41 | public class FileT { 42 | 43 | public static void main(String[] args) { 44 | try { 45 | // 创建一个目录 46 | File dir = new File("E:" + File.separator + "dir"); 47 | dir.mkdir(); 48 | // 创建一个文件 49 | File file = new File(dir,"file.txt"); 50 | file.createNewFile(); 51 | 52 | // 是否是一个目录 53 | System.out.println(dir.isDirectory()); 54 | // 是否是一个文件 55 | System.out.println(file.isFile()); 56 | 57 | // 删除文件 58 | if (file.delete()) { 59 | System.out.println(file.getName() + "被删除了!"); 60 | } else { 61 | System.out.println("文件删除失败!"); 62 | } 63 | } catch (IOException e) { e.printStackTrace(); } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/FilenameFilterT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.FilenameFilter; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-7-20 13:31:41 24 | * 类名过滤器的使用 25 | */ 26 | public class FilenameFilterT { 27 | 28 | public static void main(String[] args) { 29 | // IO包路径 30 | String dir = "src" + File.separator + 31 | "org" + File.separator + 32 | "javacore" + File.separator + 33 | "io"; 34 | File file = new File(dir); 35 | // 创建过滤器文件 36 | MyFilter filter = new MyFilter("y.java"); 37 | // 过滤 38 | String files[] = file.list(filter); 39 | 40 | // 打印 41 | for (String name : files) { 42 | System.err.println(name); 43 | } 44 | } 45 | 46 | /** 47 | * 内部类实现过滤器文件接口 48 | */ 49 | static class MyFilter implements FilenameFilter { 50 | 51 | private String type; 52 | 53 | public MyFilter (String type) { 54 | this.type = type; 55 | } 56 | 57 | @Override 58 | public boolean accept(File dir, String name) { 59 | return name.endsWith(type);// 以Type结尾 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/FormatteMemoryInput.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.DataInputStream; 5 | import java.io.EOFException; 6 | import java.io.File; 7 | import java.io.IOException; 8 | /** 9 | * @author Jeff Lee 10 | * @since 2015-7-15 20:42:47 11 | * 格式化内存输入 12 | */ 13 | public class FormatteMemoryInput { 14 | public static void main(String[] args) throws IOException { 15 | String filePath = "src" + File.separator + 16 | "org" + File.separator + 17 | "javacore" + File.separator + 18 | "io" + File.separator + 19 | "FormatteMemoryInput.java"; 20 | try { 21 | DataInputStream in = new DataInputStream( 22 | // 缓冲区字节输入 23 | new ByteArrayInputStream( 24 | BufferedInputFileT.read(filePath).getBytes())); 25 | while(true) 26 | System.out.println((char)in.readByte()); 27 | } catch (EOFException e) { 28 | System.out.println("End of Stream"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/JavaFileListT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.FilenameFilter; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-7-13 21:13:58 24 | * FilenameFilter文件过滤器的使用 25 | */ 26 | public class JavaFileListT { 27 | 28 | // 文件过滤接口 29 | // 作为匿名内部类,变量type必须声明为final类型 30 | public static FilenameFilter javaFileFilter(final String type) { 31 | // 过滤接口-匿名内部类 32 | return new FilenameFilter() { 33 | @Override 34 | public boolean accept(File dir, String name) { 35 | return new File(name).getName().indexOf(type) != -1; 36 | } 37 | }; 38 | } 39 | 40 | public static void main(String[] args) { 41 | // 创建一个目录 42 | File file = new File("src\\org\\javacore\\io");// 当前目录 43 | // 获取文件名数组 44 | String fileNames[] = file.list(javaFileFilter(".java")); 45 | // 打印 46 | for (String item : fileNames) { 47 | System.out.println(item); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/MemoryInputT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.StringReader; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-7-14 08:54:24 25 | * 内存中输入 26 | */ 27 | public class MemoryInputT { 28 | public static void main(String[] args) throws IOException { 29 | StringReader in = new StringReader(BufferedInputFileT.read( 30 | "src" + File.separator + 31 | "org" + File.separator + 32 | "javacore" + File.separator + 33 | "io" + File.separator + 34 | "BufferedInputFileT.java")); 35 | int c; 36 | while((c = in.read()) != -1)// int形式 37 | System.out.println((char)c);// int字节,转char显示 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/OSExecuteT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-10-6 18:40:24 24 | * 操作系统进程流的案例 25 | */ 26 | public class OSExecuteT { 27 | public static void commond(String command) { 28 | boolean err = false; 29 | 30 | try { 31 | // 创建操作系统进程 32 | Process process = 33 | new ProcessBuilder(command.split(" ")).start(); 34 | 35 | // 读取进程的输入流 36 | BufferedReader results = new BufferedReader( 37 | new InputStreamReader(process.getInputStream())); 38 | String s; 39 | while ((s = results.readLine()) != null) 40 | System.out.println(s); 41 | 42 | // 读取进程的错误流 43 | BufferedReader errors = new BufferedReader( 44 | new InputStreamReader(process.getErrorStream())); 45 | while ((s = errors.readLine()) != null) { 46 | System.err.println(s); 47 | if (!err) 48 | err = true; 49 | } 50 | 51 | } catch (Exception e) { 52 | if (!command.startsWith("CMD /C")) 53 | commond("CMD /C " + command); 54 | else 55 | throw new RuntimeException(e); 56 | } 57 | 58 | if (err) 59 | throw new OSExecuteException("Errors Executing " + command); 60 | } 61 | 62 | public static void main(String[] args) { 63 | commond("java -version"); 64 | } 65 | } 66 | class OSExecuteException extends RuntimeException { 67 | private static final long serialVersionUID = -3254218368058055219L; 68 | 69 | public OSExecuteException(String msg) { 70 | super(msg); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/PipeStreamT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.IOException; 4 | import java.io.PipedInputStream; 5 | import java.io.PipedOutputStream; 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-7-30 21:58:18 25 | * 管道输入输出流的使用 26 | * 同一个JVM中,两个线程直接的字节流通信 27 | */ 28 | public class PipeStreamT { 29 | public static void main(String[] args) throws IOException { 30 | // 创建管道输出流 31 | final PipedOutputStream output = new PipedOutputStream(); 32 | // 创建管道输入流,并连接到管道输出流 33 | @SuppressWarnings("resource") 34 | final PipedInputStream input = new PipedInputStream(output); 35 | //final PipedInputStream input = new PipedInputStream(); 36 | //input.connect(output); // 等价于 37 | 38 | Thread outputThread = new Thread(new Runnable() { 39 | @Override 40 | public void run() { 41 | try { 42 | // 将指定的字节数组写入管道输出流 43 | output.write("Hello,PipedStream!".getBytes()); 44 | } catch (IOException e) {} 45 | } 46 | }); 47 | 48 | Thread inputThread = new Thread(new Runnable() { 49 | @Override 50 | public void run() { 51 | try { 52 | // 读取管道输入流中的下一个数据字节 53 | int data = input.read(); 54 | while( data != -1) { 55 | System.out.print((char) data); 56 | // 再次读取下一个字节 57 | data = input.read(); 58 | } 59 | } catch (IOException e){} 60 | } 61 | }); 62 | 63 | outputThread.start(); 64 | inputThread.start(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/RandomAccessFileT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | import java.io.IOException; 3 | import java.io.RandomAccessFile; 4 | /* 5 | * Copyright [2015] [Jeff Lee] 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-7-14 08:54:24 23 | * RandomAccessFile的使用 24 | */ 25 | public class RandomAccessFileT { 26 | public static void main(String[] args) throws IOException { 27 | // 获取文件,读写方式 28 | RandomAccessFile file = new RandomAccessFile("D:\\data\\file.txt","rw"); 29 | 30 | // 设置文件指针位置 31 | file.seek(6); 32 | // 文件中的当前偏移量 33 | System.out.println(file.getFilePointer()); 34 | 35 | // 读取文本的一行 36 | System.out.println((char)file.read());// int字节,转char显示 37 | 38 | // 写入字节数组 39 | file.write("Hello World".getBytes()); 40 | 41 | // 初始化文件指针位置 42 | file.seek(0); 43 | // 读取文本的一行 44 | System.out.println(file.readLine()); 45 | 46 | file.close(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/SInputStream.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * 所有字节输入流实现类的基类 7 | */ 8 | public abstract class SInputStream { 9 | 10 | // 缓存区字节数组最大值 11 | private static final int MAX_SKIP_BUFFER_SIZE = 2048; 12 | 13 | // 从输入流中读取数据的下一个字节,以int返回 14 | public abstract int read() throws IOException; 15 | 16 | // 从输入流中读取数据的一定数量字节,并存储在缓存数组b 17 | public int read(byte b[]) throws IOException { 18 | return read(b, 0, b.length); 19 | } 20 | 21 | // 从输入流中读取数据最多len个字节,并存储在缓存数组b 22 | public int read(byte b[], int off, int len) throws IOException { 23 | if (b == null) { 24 | throw new NullPointerException(); 25 | } else if (off < 0 || len < 0 || len > b.length - off) { 26 | throw new IndexOutOfBoundsException(); 27 | } else if (len == 0) { 28 | return 0; 29 | } 30 | 31 | int c = read(); 32 | if (c == -1) { 33 | return -1; 34 | } 35 | b[off] = (byte)c; 36 | 37 | int i = 1; 38 | try { 39 | for (; i < len ; i++) { 40 | c = read(); 41 | if (c == -1) { 42 | break; 43 | } 44 | b[off + i] = (byte)c; 45 | } 46 | } catch (IOException ee) { 47 | } 48 | return i; 49 | } 50 | 51 | // 跳过输入流中数据的n个字节 52 | public long skip(long n) throws IOException { 53 | 54 | long remaining = n; 55 | int nr; 56 | 57 | if (n <= 0) { 58 | return 0; 59 | } 60 | 61 | int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining); 62 | byte[] skipBuffer = new byte[size]; 63 | while (remaining > 0) { 64 | nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 65 | if (nr < 0) { 66 | break; 67 | } 68 | remaining -= nr; 69 | } 70 | 71 | return n - remaining; 72 | } 73 | 74 | // 返回下一个方法调用能不受阻塞地从此读取(或者跳过)的估计字节数 75 | public int available() throws IOException { 76 | return 0; 77 | } 78 | 79 | // 关闭此输入流,并释放与其关联的所有资源 80 | public void close() throws IOException {} 81 | 82 | // 在此输出流中标记当前位置 83 | public synchronized void mark(int readlimit) {} 84 | 85 | // 将此流重新定位到最后一次对此输入流调用 mark 方法时的位置。 86 | public synchronized void reset() throws IOException { 87 | throw new IOException("mark/reset not supported"); 88 | } 89 | 90 | // 测试此输入流是否支持 mark 和 reset 方法 91 | public boolean markSupported() { 92 | return false; 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/SOutputStream.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.Closeable; 4 | import java.io.Flushable; 5 | import java.io.IOException; 6 | 7 | /** 8 | * 所有字节输出流实现类的基类 9 | */ 10 | public abstract class SOutputStream implements Closeable, Flushable { 11 | 12 | // 将指定的字节写入输出流 13 | public abstract void write(int b) throws IOException; 14 | 15 | // 将指定的byte数组的字节全部写入输出流 16 | public void write(byte b[]) throws IOException { 17 | write(b, 0, b.length); 18 | } 19 | 20 | // 将指定的byte数组中从偏移量off开始的len个字节写入输出流 21 | public void write(byte b[], int off, int len) throws IOException { 22 | if (b == null) { 23 | throw new NullPointerException(); 24 | } else if ((off < 0) || (off > b.length) || (len < 0) || 25 | ((off + len) > b.length) || ((off + len) < 0)) { 26 | throw new IndexOutOfBoundsException(); 27 | } else if (len == 0) { 28 | return; 29 | } 30 | for (int i = 0 ; i < len ; i++) { 31 | write(b[off + i]); 32 | } 33 | } 34 | 35 | // 刷新输出流,并强制写出所有缓冲的输出字节 36 | public void flush() throws IOException { 37 | } 38 | 39 | // 关闭输出流,并释放与该流有关的所有资源 40 | public void close() throws IOException { 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/StoringAndRecoveringData.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedOutputStream; 5 | import java.io.DataInputStream; 6 | import java.io.DataOutputStream; 7 | import java.io.FileInputStream; 8 | import java.io.FileOutputStream; 9 | import java.io.IOException; 10 | 11 | /* 12 | * Copyright [2015] [Jeff Lee] 13 | * 14 | * Licensed under the Apache License, Version 2.0 (the "License"); 15 | * you may not use this file except in compliance with the License. 16 | * You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, software 21 | * distributed under the License is distributed on an "AS IS" BASIS, 22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | * See the License for the specific language governing permissions and 24 | * limitations under the License. 25 | */ 26 | 27 | /** 28 | * @author Jeff Lee 29 | * @since 2015-9-28 17:30:21 30 | * DataOutputStream和DataInputStream的使用案例 31 | */ 32 | public class StoringAndRecoveringData { 33 | 34 | @SuppressWarnings("resource") 35 | public static void main(String[] args) throws IOException { 36 | // 写入数据 37 | DataOutputStream outputStream = new DataOutputStream( 38 | new BufferedOutputStream(new FileOutputStream("data.txt"))); 39 | outputStream.writeDouble(3.1415926); 40 | outputStream.writeUTF("你好"); 41 | outputStream.writeInt(1); 42 | outputStream.close(); 43 | 44 | // 写出数据 45 | DataInputStream inputStream = new DataInputStream( 46 | new BufferedInputStream(new FileInputStream("data.txt"))); 47 | System.out.println(inputStream.readDouble()); 48 | System.out.println(inputStream.readUTF()); 49 | System.out.println(inputStream.readInt()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/SystemStreamT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.io.OutputStream; 6 | import java.io.PrintStream; 7 | /* 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | /** 24 | * @author Jeff Lee 25 | * @since 2015-7-31 11:04:26 26 | * System.out, System.err中IO的使用 27 | * 替换系统流,输出至文本 28 | */ 29 | public class SystemStreamT { 30 | public static void main(String[] args) throws IOException { 31 | // 创建文件输出流 32 | OutputStream out = new FileOutputStream("D:\\data\\console.txt"); 33 | // 创建新的文件输出打印流 34 | PrintStream print = new PrintStream(out); 35 | // 设置标准输出流 36 | System.setOut(print); 37 | // 设置标准错误输出流 38 | System.setErr(print); 39 | 40 | System.out.println("Hello,System.out"); 41 | System.err.println("Hello,System.err"); 42 | 43 | // 关闭流 44 | print.close(); 45 | out.close(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/UsingRandomAccessFile.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | 3 | import java.io.IOException; 4 | import java.io.RandomAccessFile; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-9-28 18:50:22 25 | * RandomAccessFile的使用案例 26 | */ 27 | public class UsingRandomAccessFile { 28 | // 文件名 29 | static String file = "rtest.bat"; 30 | 31 | static void display() throws IOException { 32 | // 创建随机访问类,只读模式 33 | RandomAccessFile rf = new RandomAccessFile(file, "r"); 34 | for (int i = 0; i < 7; i++) 35 | System.out.println("Value " + i + ": " + rf.readDouble());// 读取一个Double 36 | System.out.println(rf.readUTF());// 读取一个字符串 37 | rf.close(); 38 | } 39 | 40 | public static void main(String[] args) throws IOException { 41 | // 创建随机访问类,读写模式 42 | RandomAccessFile rf = new RandomAccessFile(file, "rw"); 43 | for (int i = 0; i < 7; i++) 44 | rf.writeDouble( i * 1.123);// 写入一个Double 45 | rf.writeUTF("文件结束");// 写入一个字符串 46 | rf.close(); 47 | 48 | display(); 49 | 50 | rf = new RandomAccessFile(file, "rw"); 51 | rf.seek(5 * 8);// 设置文件指针偏移量,设置到第5个双精度字节 52 | rf.writeDouble(47.003); 53 | rf.close(); 54 | 55 | display(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/byteoper/IntegerConvertT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.byteoper; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-6-19 21:26:09 22 | * Integer与byte数组转换 23 | */ 24 | public class IntegerConvertT { 25 | 26 | public static void main(String[] args){ 27 | // 将我的学号转换成字节码 28 | byte[] bytes = IntegerConvertT.int2Bytes(1206010035); 29 | System.out.println(bytes[0] + " " + bytes[1] + " " + bytes[2] + " " + bytes[3]); 30 | // 字节码就可以转换回学号 31 | System.out.println(IntegerConvertT.bytes2Int(bytes)); 32 | } 33 | 34 | /** 35 | * Int转字节数组 36 | */ 37 | public static byte[] int2Bytes(int inta){ 38 | // 32位Int可存于长度为4的字节数组 39 | byte[] bytes = new byte[4]; 40 | for (int i = 0; i < bytes.length; i++) 41 | bytes[i] = (byte)(int)((inta >> i * 8) & 0xff);// 移位和清零 42 | 43 | return bytes; 44 | } 45 | 46 | /** 47 | * 字节数组转Int 48 | */ 49 | public static int bytes2Int(byte[] bytes){ 50 | int inta = 0; 51 | for (int i = 0; i < bytes.length; i++) 52 | inta += (int)((bytes[i] & 0xff) << i * 8);// 移位和清零 53 | 54 | return inta; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/byteoper/IntegerOperT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.byteoper; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-6-19 21:25:57 21 | * Integer类的进制转换 22 | */ 23 | public class IntegerOperT { 24 | 25 | public static void main(String[] args) { 26 | System.out.println("17的十六进制: " + Integer.toHexString(17)); 27 | System.out.println("17的八进制: " + Integer.toOctalString(17)); 28 | System.out.println("17的二进制: " + Integer.toBinaryString(17)); 29 | 30 | System.out.println(Integer.valueOf("11", 16)); 31 | System.out.println(Integer.valueOf("21", 8)); 32 | System.out.println(Integer.valueOf("00010001", 2)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/byteoper/LongConvertT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.byteoper; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-6-19 21:26:04 21 | * Long与byte数组转换 22 | */ 23 | public class LongConvertT { 24 | 25 | /** 26 | * long 转 byte数组 27 | */ 28 | public static byte[] long2Bytes(long longa){ 29 | byte[] bytes = new byte[8]; 30 | for (int i = 0; i < bytes.length; i++) 31 | bytes[i] = (byte)(long)(((longa) >> i * 8) & 0xff); // 移位和清零 32 | 33 | return bytes; 34 | } 35 | 36 | /** 37 | * byte数组 转 long 38 | */ 39 | public static long bytes2Long(byte[] bytes){ 40 | long longa = 0; 41 | for (int i = 0; i < bytes.length; i++) 42 | longa += (long)((bytes[i] & 0xff) << i * 8); // 移位和清零 43 | 44 | return longa; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/byteoper/StringConvertT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.byteoper; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-6-19 21:27:41 21 | * String转换成byte数组 22 | */ 23 | public class StringConvertT { 24 | 25 | public static void main(String[] args){ 26 | String str = "HOME"; 27 | byte[] bytes = str.getBytes(); 28 | // 打印字节数组 29 | System.out.println("UTF-8编码'HOME'的字节数组为:"); 30 | for (int i = 0; i < bytes.length; i++) { 31 | System.out.println("\t" + bytes[i] + "|" + Integer.toBinaryString(bytes[i])); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/serializable/SerializableT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.serializable; 2 | 3 | 4 | //import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; 5 | // 6 | //import java.io.*; 7 | // 8 | ///** 9 | // * 描述:Java序列化和反序列化的小例子 10 | // * Created by 子木 on 2016/2/15. 11 | // */ 12 | //public class SerializableT { 13 | // public static void main(String[] args) throws IOException, ClassNotFoundException { 14 | // for (int i = 0;i < 10;i++) { 15 | // AObjcet aObjcet = new AObjcet(); 16 | // long beginTime = System.currentTimeMillis(); 17 | // 18 | // ByteOutputStream byteOutput = new ByteOutputStream(); 19 | // ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput); 20 | // objectOutput.writeObject(aObjcet); 21 | // objectOutput.close(); 22 | // byteOutput.close(); 23 | // byte[] bytes = byteOutput.toByteArray(); 24 | // System.out.println("Java序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); 25 | // System.out.println("Java序列化后的字节大小为:" + bytes.length); 26 | // 27 | // beginTime = System.currentTimeMillis(); 28 | // ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes); 29 | // ObjectInputStream objectInput = new ObjectInputStream(byteInput); 30 | // objectInput.readObject(); 31 | // objectInput.close(); 32 | // byteInput.close(); 33 | // System.out.println("Java反序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); 34 | // 35 | // } 36 | // } 37 | //} 38 | //class AObjcet implements Serializable { 39 | // private String a = "bysocket"; 40 | // private String b = "likes"; 41 | // private String c = "java"; 42 | // private String d = "world"; 43 | // 44 | // private int i = 100; 45 | // private int j = 10; 46 | // private long m = 100L; 47 | // 48 | // private boolean isA = true; 49 | // private boolean isB = false; 50 | // private boolean isC = false; 51 | // 52 | // private BObject aObject = new BObject(); 53 | // private BObject bObject = new BObject(); 54 | // private BObject cObject = new BObject(); 55 | // private BObject dObject = new BObject(); 56 | // 57 | //} 58 | //class BObject implements Serializable { 59 | // 60 | //} 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/io/zip/GZIPcompress.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io.zip; 2 | 3 | import java.io.BufferedOutputStream; 4 | import java.io.BufferedReader; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.FileReader; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | import java.util.zip.GZIPInputStream; 12 | import java.util.zip.GZIPOutputStream; 13 | 14 | /* 15 | * Copyright [2015] [Jeff Lee] 16 | * 17 | * Licensed under the Apache License, Version 2.0 (the "License"); 18 | * you may not use this file except in compliance with the License. 19 | * You may obtain a copy of the License at 20 | * 21 | * http://www.apache.org/licenses/LICENSE-2.0 22 | * 23 | * Unless required by applicable law or agreed to in writing, software 24 | * distributed under the License is distributed on an "AS IS" BASIS, 25 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 26 | * See the License for the specific language governing permissions and 27 | * limitations under the License. 28 | */ 29 | 30 | /** 31 | * @author Jeff Lee 32 | * @since 2015-10-17 13:59:25 33 | * GZIP简单使用 34 | */ 35 | public class GZIPcompress { 36 | public static void main(String[] args) throws IOException { 37 | // 用Reader读文件 38 | BufferedReader in = new BufferedReader(new InputStreamReader( 39 | new FileInputStream("data.gz" ), "UTF-8" )); 40 | // 使用缓冲输出流,输出压缩流文件 41 | BufferedOutputStream out = new BufferedOutputStream( 42 | new GZIPOutputStream(new FileOutputStream("data.gz"))); 43 | System.out.println("Writing File 压缩"); 44 | int c; 45 | while ((c = in.read()) > 0) 46 | out.write(String.valueOf((char)c).getBytes("UTF-8")); 47 | in.close(); 48 | out.close(); 49 | 50 | System.out.println("Reading File 解压"); 51 | // 用输入解压流读取文件 52 | BufferedReader in2 = new BufferedReader( 53 | new InputStreamReader( 54 | new GZIPInputStream(new FileInputStream("data.gz")),"UTF-8"));// encoding question 55 | String s; 56 | while ((s=in2.readLine()) != null) 57 | System.out.println(s); 58 | in2.close(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/lambda/LambdaListCompare.java: -------------------------------------------------------------------------------- 1 | package org.javacore.lambda; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | /** 23 | * List 比较器 24 | * 25 | * Created by bysocket on 16/7/12. 26 | */ 27 | public class LambdaListCompare { 28 | public static void main(String[] args) { 29 | List list = new ArrayList<>(); 30 | list.add(4); 31 | list.add(1); 32 | list.add(3); 33 | list.add(6); 34 | 35 | // list.sort(new Comparator() { 36 | // @Override 37 | // public int compare(Integer o1, Integer o2) { 38 | // return Integer.compare(o1, o2); 39 | // } 40 | // }); 41 | 42 | /** Lambda表达式格式: 43 | * (Type1 param1, Type2 param2, ..., TypeN paramN) -> { 44 | * statment1; 45 | * statment2; 46 | * ... 47 | * return statmentM; 48 | * } 49 | */ 50 | // list.sort(((o1, o2) -> { 51 | // return Integer.compare(o1, o2); 52 | // })); 53 | 54 | // 简写Lambda表达式 55 | list.sort((o1, o2) -> Integer.compare(o1, o2)); 56 | 57 | System.out.println(list.toString()); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/lambda/LambdaOperators.java: -------------------------------------------------------------------------------- 1 | package org.javacore.lambda; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.ArrayList; 20 | import java.util.Comparator; 21 | import java.util.List; 22 | 23 | /** 24 | * Lambda 操作符 25 | * 26 | * Created by bysocket on 16/7/13. 27 | */ 28 | public class LambdaOperators { 29 | public static void main(String[] args) { 30 | List list = new ArrayList<>(); 31 | list.add("aaa"); 32 | list.add("cccc"); 33 | list.add("b"); 34 | list.add("eeeee"); 35 | 36 | /** 37 | * :: 操作符格式 => 三种情况 38 | * 对象::实例方法 39 | * 类::静态方法 40 | * 类::实例方法 对于前两种情况,方法引用就是对参数执行该方法。比如下面两种方法 41 | */ 42 | // 按字符串大小排序忽略大小写 43 | list.sort(String::compareToIgnoreCase); 44 | // 打印 list 元素 45 | list.forEach(System.out::println); 46 | 47 | System.out.println("======按字符大小排序======"); 48 | list.sort(Comparator.comparing(String::length)); 49 | list.forEach(System.out::println); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/lambda/LambdaRunnable.java: -------------------------------------------------------------------------------- 1 | package org.javacore.lambda; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * Lambda - 启动线程 21 | * 22 | * Created by bysocket on 16/7/13. 23 | */ 24 | public class LambdaRunnable { 25 | static int b = 10; 26 | 27 | public static void main(String[] args) { 28 | // 启动线程 29 | // Thread thread = new Thread(new Runnable() { 30 | // @Override 31 | // public void run() { 32 | // b++; 33 | // System.out.println(b); 34 | // } 35 | // }); 36 | 37 | // Lambda - 启动线程 38 | Thread thread = new Thread(() -> { 39 | b++; 40 | System.out.println(b); 41 | }); 42 | thread.start(); 43 | System.out.println("Done!"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/AvailableCharSets.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.charset.Charset; 4 | import java.util.Iterator; 5 | import java.util.SortedMap; 6 | 7 | /* 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | /** 24 | * @author Jeff Lee 25 | * @since 2015-10-11 19:51:10 26 | * 可用的CharSet打印 27 | */ 28 | public class AvailableCharSets { 29 | public static void main(String[] args) { 30 | // charset对象的有序映射 31 | SortedMap charSets = 32 | Charset.availableCharsets(); 33 | // 获取key的迭代器 34 | Iterator iterator = charSets.keySet().iterator(); 35 | while (iterator.hasNext()) { 36 | String csName = iterator.next(); 37 | System.out.print(csName); 38 | // 获取别名的Charset集合的迭代器 39 | Iterator aliases = 40 | charSets.get(csName).aliases().iterator(); 41 | if (aliases.hasNext()) 42 | System.out.print(": "); 43 | while (aliases.hasNext()) { 44 | System.out.print(aliases.next()); 45 | if (aliases.hasNext()) 46 | System.out.print(","); 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/ChannelCopy.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.nio.ByteBuffer; 8 | import java.nio.channels.FileChannel; 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-10-9 17:38:08 28 | * FileChannel的文件复制案例 29 | */ 30 | public class ChannelCopy { 31 | // 读取的文件 32 | private static final String sourceFile = 33 | "src" + File.separator + 34 | "org" + File.separator + 35 | "javacore" + File.separator + 36 | "nio" + File.separator + 37 | "ChannelCopy.java"; 38 | // 输出的文件 39 | private static final String targetFile = "data.txt"; 40 | 41 | private static final int BSIZE = 1024; // 1K字节 42 | 43 | @SuppressWarnings("resource") 44 | public static void main(String[] args) throws IOException { 45 | // 创建用于读写的Channel 46 | FileChannel 47 | in = new FileInputStream(sourceFile).getChannel(), 48 | out = new FileOutputStream(targetFile).getChannel(); 49 | 50 | // 分配ByteBuffer的大小 1K 51 | ByteBuffer buffer = ByteBuffer.allocate(BSIZE); 52 | // 将字节序列从此通道读入给定的缓冲区,分块读,直至读到文件末端 53 | while (in.read(buffer) != -1) {// -1,表示读到文件末端 54 | // 反转缓冲区,为写入或读取做好准备 55 | buffer.flip(); 56 | // 将含有字节序列的缓冲区写入文件通道 57 | out.write(buffer); 58 | // 清空缓冲区 59 | buffer.clear(); 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/Endians.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.ByteOrder; 5 | import java.util.Arrays; 6 | 7 | /* 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | /** 24 | * @author Jeff Lee 25 | * @since 2015-10-13 20:40:00 26 | * ByteBuffer中字节存储次序 27 | */ 28 | public class Endians { 29 | public static void main(String[] args) { 30 | // 创建12个字节的字节缓冲区 31 | ByteBuffer bb = ByteBuffer.wrap(new byte[12]); 32 | // 存入字符串 33 | bb.asCharBuffer().put("abdcef"); 34 | System.out.println(Arrays.toString(bb.array())); 35 | 36 | // 反转缓冲区 37 | bb.rewind(); 38 | // 设置字节存储次序 39 | bb.order(ByteOrder.BIG_ENDIAN); 40 | bb.asCharBuffer().put("abcdef"); 41 | System.out.println(Arrays.toString(bb.array())); 42 | 43 | // 反转缓冲区 44 | bb.rewind(); 45 | // 设置字节存储次序 46 | bb.order(ByteOrder.LITTLE_ENDIAN); 47 | bb.asCharBuffer().put("abcdef"); 48 | System.out.println(Arrays.toString(bb.array())); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/FileChannelT.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.RandomAccessFile; 7 | import java.nio.ByteBuffer; 8 | import java.nio.channels.FileChannel; 9 | 10 | /* 11 | * Copyright [2015] [Jeff Lee] 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | */ 25 | 26 | /** 27 | * @author Jeff Lee 28 | * @since 2015-7-23 17:50:18 29 | * FileChannel读写文件案例 30 | */ 31 | public class FileChannelT { 32 | 33 | @SuppressWarnings("resource") 34 | public static void main(String[] args) throws IOException { 35 | // NIO包路径 36 | String dir = "src" + File.separator + 37 | "org" + File.separator + 38 | "javacore" + File.separator + 39 | "nio"; 40 | // 获取FileChannelT.java文件,读写方式 41 | RandomAccessFile inFile = new RandomAccessFile(dir + File.separator + 42 | "FileChannelT.java","rw"); 43 | // 创建输出文件流 44 | FileOutputStream outFileStream = new FileOutputStream("D:\\FileChannelT2.java"); 45 | // 创建输入文件通道 46 | FileChannel inChannel = inFile.getChannel(); 47 | // 创建输出文件通道 48 | FileChannel outChannel = outFileStream.getChannel(); 49 | // 分配一个1024字节的字节缓存区 50 | ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024); // 比allocate();效率高 51 | 52 | // 测试时间 53 | long startTime = System.currentTimeMillis(); 54 | 55 | // 读文件,存文件 56 | while (true) { 57 | // 将字节序列从此通道读入给定的缓冲区 58 | int eof = inChannel.read(byteBuffer); 59 | // 读到文件末尾退出 60 | if (eof == -1) 61 | break; 62 | // 反转缓冲区 63 | byteBuffer.flip(); 64 | // 将字节序列从给定的缓冲区写入此通道 65 | outChannel.write(byteBuffer); 66 | // 清空缓存区 67 | byteBuffer.clear(); 68 | } 69 | inChannel.close(); 70 | outChannel.close(); 71 | 72 | System.out.println("耗时:" + (System.currentTimeMillis() - startTime)); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/FileChannelTransferTo.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.nio.channels.FileChannel; 8 | 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-10-9 17:43:27 28 | * FileChannel的transferTo/transferFrom案例 29 | */ 30 | public class FileChannelTransferTo { 31 | // 读取的文件 32 | private static final String sourceFile = 33 | "src" + File.separator + 34 | "org" + File.separator + 35 | "javacore" + File.separator + 36 | "nio" + File.separator + 37 | "FileChannelTransferTo.java"; 38 | // 输出的文件 39 | private static final String targetFile = "data.txt"; 40 | 41 | @SuppressWarnings("resource") 42 | public static void main(String[] args) throws IOException { 43 | // 创建用于读写的Channel 44 | FileChannel 45 | in = new FileInputStream(sourceFile).getChannel(), 46 | out = new FileOutputStream(targetFile).getChannel(); 47 | // 将in通道的字节传输给out可写入字节通道 48 | in.transferTo(0, in.size(),out); 49 | // or 50 | // 将字节从给定的可读取字节通道传输到此通道的文件中。 51 | // out.transferFrom(in, 0, in.size()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/FileLocking.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.nio.channels.FileLock; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-10-15 19:31:34 28 | * 文件加锁 29 | */ 30 | public class FileLocking { 31 | public static void main(String[] args) throws IOException, InterruptedException { 32 | // 获取输出流 33 | FileOutputStream fos = new FileOutputStream("data.txt"); 34 | // 从输出流中获取文件加锁对象,并锁定File 35 | FileLock fl = fos.getChannel().lock(); 36 | if (fl != null) { 37 | System.out.println("Locked File"); 38 | TimeUnit.MICROSECONDS.sleep(100); 39 | // 释放文件锁定 40 | fl.release(); 41 | System.out.println("Release Lock"); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/GetChannel.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.RandomAccessFile; 7 | import java.nio.ByteBuffer; 8 | import java.nio.channels.FileChannel; 9 | 10 | /* 11 | * Copyright [2015] [Jeff Lee] 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | */ 25 | 26 | /** 27 | * @author Jeff Lee 28 | * @since 2015-10-8 17:33:19 29 | * 从流中获取FileChannel的案例 30 | */ 31 | public class GetChannel { 32 | private static final int BSIZE = 1024; // 1K字节 33 | 34 | @SuppressWarnings("resource") 35 | public static void main(String[] args) throws IOException { 36 | ////// 37 | // 写入文件 38 | ////// 39 | // 从文件输出流获取FileChannel 40 | FileChannel fc = new FileOutputStream("data.txt").getChannel(); 41 | // 将含有字节序列的缓冲区写入文件通道 42 | fc.write(ByteBuffer.wrap("Some Text".getBytes()));// 将已存在的字节数组包装到ByteBuffer 43 | // 关闭通道 44 | fc.close(); 45 | 46 | ////// 47 | // 从文件尾部写入 48 | ////// 49 | // 从RandomAccessFile获取FileChannel文件 50 | fc = new RandomAccessFile("data.txt", "rw").getChannel(); 51 | // 文件指针指向文件尾部 52 | fc.position(fc.size()); 53 | // 将含有字节序列的缓冲区写入文件通道 54 | fc.write(ByteBuffer.wrap(" Some more".getBytes())); 55 | // 关闭通道 56 | fc.close(); 57 | 58 | ////// 59 | // 读取文件 60 | ////// 61 | // 从文件输出流获取FileChannel文件 62 | fc = new FileInputStream("data.txt").getChannel(); 63 | // 分配ByteBuffer的大小 1K 64 | ByteBuffer buffer = ByteBuffer.allocate(BSIZE); 65 | // 将字节序列从此通道读入给定的缓冲区。 66 | fc.read(buffer); 67 | // 反转缓冲区,为写入或读取做好准备 68 | buffer.flip(); 69 | // 打印 70 | while (buffer.hasRemaining()) { 71 | System.out.print((char)buffer.get()); 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/GetData.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-10-12 18:53:10 24 | * ByteBuffer操作类型数据的案例 25 | */ 26 | public class GetData { 27 | private static final int BSIZE = 1024; // 1字节 28 | public static void main(String[] args) { 29 | // 创建字节缓冲区 30 | ByteBuffer bb = ByteBuffer.allocate(BSIZE); 31 | int i = 0; 32 | while (i++ < bb.limit())// 缓冲区的限制 33 | if (bb.get() != 0)// 读取当前位置字节,如果字节不等于0 34 | System.out.println("该字节不为0"); 35 | // 读取到最后一个跳出限制while,i为BSIZE大1。 36 | System.out.println("i = " + i); 37 | 38 | // 重绕此缓冲区 39 | bb.rewind(); 40 | // 写入Hello 41 | bb.asCharBuffer().put("Hello"); 42 | // 从缓冲区读取char,并输出 43 | char c; 44 | while ((c = bb.getChar()) != 0) 45 | System.out.print(c + " "); 46 | System.out.println(); 47 | 48 | // 写入Short类型数据 49 | bb.asShortBuffer().put((short) 47142); 50 | System.out.println(bb.getShort()); 51 | // 重绕此缓冲区 52 | bb.rewind(); 53 | 54 | // 写入Long类型数据 55 | bb.asLongBuffer().put((long)99471142); 56 | System.out.println(bb.getLong()); 57 | // 重绕此缓冲区 58 | bb.rewind(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/IntBufferDemo.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.IntBuffer; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-10-12 18:53:01 25 | * 通过IntBuffer操作ByteBuffer的int型数据 26 | */ 27 | public class IntBufferDemo { 28 | private static final int BSIZE = 1024;// 1字节 29 | public static void main(String[] args) { 30 | // 创建1字节大小的字节缓冲区 31 | ByteBuffer bb = ByteBuffer.allocate(BSIZE); 32 | // int视图缓冲区 33 | IntBuffer ib = bb.asIntBuffer(); 34 | // 存储一个数组 35 | ib.put(new int[]{1, 2, 3, 4, 5, 6}); 36 | // 通过访问ByteBuff字节缓冲区,获取某个位置的值 37 | System.out.println(ib.get(3)); 38 | // 存储一个int数据 39 | ib.put(3, 44); 40 | // 反转缓冲区 41 | ib.flip(); 42 | // 如果当前位置还有元素 43 | while (ib.hasRemaining()) { 44 | // 获取当前位置的元素 45 | int i = ib.get(); 46 | System.out.println(i); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/LargeMappedFiles.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.io.FileNotFoundException; 20 | import java.io.IOException; 21 | import java.io.RandomAccessFile; 22 | import java.nio.MappedByteBuffer; 23 | import java.nio.channels.FileChannel; 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-10-14 16:01:14 28 | * 内存映射文件的使用 29 | */ 30 | public class LargeMappedFiles { 31 | static int length = 0x8FFFFFF; // 128 MB 32 | 33 | public static void main(String[] args) throws IOException { 34 | // 将此通道的文件区域直接映射到内存映射区域中。 35 | MappedByteBuffer out = new RandomAccessFile("data.txt","rw").getChannel() 36 | .map(FileChannel.MapMode.READ_WRITE, 0, length); 37 | // 写入128MB的字符串 38 | for (int i = 0;i < length; i++) 39 | out.put((byte)'x'); 40 | System.out.println("Finished writing"); 41 | // 打印其中6个字符 42 | for (int i = length/2; i < length/2 + 6; i++) 43 | System.out.print((char)out.get(i)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/LockingMappedFiles.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | import java.io.RandomAccessFile; 6 | import java.nio.ByteBuffer; 7 | import java.nio.MappedByteBuffer; 8 | import java.nio.channels.FileChannel; 9 | import java.nio.channels.FileLock; 10 | 11 | /* 12 | * Copyright [2015] [Jeff Lee] 13 | * 14 | * Licensed under the Apache License, Version 2.0 (the "License"); 15 | * you may not use this file except in compliance with the License. 16 | * You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, software 21 | * distributed under the License is distributed on an "AS IS" BASIS, 22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | * See the License for the specific language governing permissions and 24 | * limitations under the License. 25 | */ 26 | 27 | /** 28 | * @author Jeff Lee 29 | * @since 2015-10-17 15:17:04 30 | * 映射文件的使用 31 | */ 32 | public class LockingMappedFiles { 33 | static final int LENGTH = 0x8FFFFFF; // 128 MB 34 | static FileChannel fc; 35 | 36 | public static void main(String[] args) throws IOException { 37 | fc = new RandomAccessFile("data.txt" , "rw").getChannel(); 38 | MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 39 | 0 , LENGTH); 40 | for (int i = 0;i < LENGTH; i++) 41 | out.put((byte)'x'); 42 | new LockAndModify(out,0,0 + LENGTH/3); 43 | new LockAndModify(out,LENGTH/2,LENGTH/2 + LENGTH/4); 44 | } 45 | 46 | // 线程 47 | private static class LockAndModify extends Thread { 48 | private ByteBuffer buffer; 49 | private int start,end; 50 | 51 | LockAndModify(ByteBuffer mbb, int start, int end) { 52 | this.start = start; 53 | this.end = end; 54 | mbb.limit(end); 55 | mbb.position(start); 56 | buffer = mbb.slice(); 57 | start(); 58 | } 59 | 60 | public void run() { 61 | try { 62 | // 从FileChannel获取文件加锁对象,并加锁 63 | FileLock fl = fc.lock(start,end,false); 64 | System.out.println("Locked: " + start + " to " + end); 65 | // 写入数据 66 | while (buffer.position() < buffer.limit() - 1) 67 | buffer.put((byte)(buffer.get() + 1)); 68 | fl.release(); 69 | System.out.println("Released: " + start + " to " + end); 70 | } catch (IOException e) { 71 | throw new RuntimeException(e); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/UsingBuffers.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.CharBuffer; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-10-14 15:48:12 25 | * 利用buffer实现交换相邻字符 26 | */ 27 | public class UsingBuffers { 28 | 29 | private static void symmetricScaramble(CharBuffer buffer) { 30 | while (buffer.hasRemaining()) { 31 | // 将mark设为position 32 | buffer.mark(); 33 | char c1 = buffer.get(); 34 | char c2 = buffer.get(); 35 | // 重置为以前标记的位置 36 | buffer.reset(); 37 | buffer.put(c2).put(c1); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | char[] data = "UsingBuffers".toCharArray(); 43 | // 一个字符两个字节 44 | ByteBuffer bb = ByteBuffer.allocate(data.length * 2); 45 | CharBuffer cb = bb.asCharBuffer(); 46 | cb.put(data); 47 | // 重绕此缓冲区 48 | System.out.println(cb.rewind()); 49 | symmetricScaramble(cb); 50 | // 重绕此缓冲区 51 | System.out.println(cb.rewind()); 52 | symmetricScaramble(cb); 53 | System.out.println(cb.rewind()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/nio/ViewBuffers.java: -------------------------------------------------------------------------------- 1 | package org.javacore.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.CharBuffer; 5 | import java.nio.DoubleBuffer; 6 | import java.nio.FloatBuffer; 7 | import java.nio.IntBuffer; 8 | import java.nio.LongBuffer; 9 | import java.nio.ShortBuffer; 10 | 11 | /* 12 | * Copyright [2015] [Jeff Lee] 13 | * 14 | * Licensed under the Apache License, Version 2.0 (the "License"); 15 | * you may not use this file except in compliance with the License. 16 | * You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, software 21 | * distributed under the License is distributed on an "AS IS" BASIS, 22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | * See the License for the specific language governing permissions and 24 | * limitations under the License. 25 | */ 26 | 27 | /** 28 | * @author Jeff Lee 29 | * @since 2015-10-13 20:40:35 30 | * 不同视图下的缓冲区 31 | */ 32 | public class ViewBuffers { 33 | public static void main(String[] args) { 34 | ByteBuffer bb = ByteBuffer.wrap(new byte[]{0,0,0,0,0,0,0,'a'}); 35 | bb.rewind(); 36 | System.out.print("Byte Buffer "); 37 | while (bb.hasRemaining()) 38 | System.out.print(bb.position() + " -> " + bb.get() + ", "); 39 | System.out.println(); 40 | 41 | CharBuffer cb = ((ByteBuffer)bb.rewind()).asCharBuffer(); 42 | System.out.print("Char Buffer "); 43 | while (cb.hasRemaining()) 44 | System.out.print(cb.position() + " -> " + cb.get() + ", "); 45 | System.out.println(); 46 | 47 | ShortBuffer sb = ((ByteBuffer)bb.rewind()).asShortBuffer(); 48 | System.out.print("Short Buffer "); 49 | while (sb.hasRemaining()) 50 | System.out.print(sb.position() + " -> " + sb.get() + ", "); 51 | System.out.println(); 52 | 53 | IntBuffer ib = ((ByteBuffer)bb.rewind()).asIntBuffer(); 54 | System.out.print("Int Buffer "); 55 | while (ib.hasRemaining()) 56 | System.out.print(ib.position() + " -> " + ib.get()); 57 | System.out.println(); 58 | 59 | FloatBuffer fb = ((ByteBuffer)bb.rewind()).asFloatBuffer(); 60 | System.out.print("Float Buffer "); 61 | while (fb.hasRemaining()) 62 | System.out.print(fb.position() + " -> " + fb.get() + ", "); 63 | System.out.println(); 64 | 65 | LongBuffer lb = ((ByteBuffer)bb.rewind()).asLongBuffer(); 66 | System.out.print("Long Buffer "); 67 | while (lb.hasRemaining()) 68 | System.out.print(lb.position() + " -> " + lb.get() + ", "); 69 | System.out.println(); 70 | 71 | DoubleBuffer db = ((ByteBuffer)bb.rewind()).asDoubleBuffer(); 72 | System.out.print("Double Buffer "); 73 | while (db.hasRemaining()) 74 | System.out.print(db.position() + " -> " + db.get() + ", "); 75 | System.out.println(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/reflection/ArrayCopy.java: -------------------------------------------------------------------------------- 1 | package org.javacore.reflection; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Arrays; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-11-9 10:45:19 25 | * 反射扩容对象数组 26 | */ 27 | public class ArrayCopy { 28 | public static void main(String[] args) { 29 | int[] a = {1,2,3}; 30 | a = (int[]) goodCopyOf(a,10); 31 | System.out.println(Arrays.toString(a)); 32 | 33 | String[] str = {"a","b","c"}; 34 | str = (String[]) goodCopyOf(str,10); 35 | System.out.println(Arrays.toString(str)); 36 | } 37 | 38 | public static Object goodCopyOf(Object a,int newLength){ 39 | // 获取Class对象 40 | Class cl = a.getClass(); 41 | // 如果不是数组对象,则返回null; 42 | if (!cl.isArray()) return null; 43 | // 获取数组组件对象 44 | Class componentType = cl.getComponentType(); 45 | int length = Array.getLength(a); 46 | Object newArray = Array.newInstance(componentType,newLength); 47 | // 复制数组 48 | System.arraycopy(a,0,newArray,0,Math.min(length,newLength)); 49 | return newArray; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/reflection/EmployeeClass.java: -------------------------------------------------------------------------------- 1 | package org.javacore.reflection; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-11-9 10:45:19 22 | * 反射在继承中的案例 23 | */ 24 | class Employee { 25 | private String name; 26 | public Employee(String name){ 27 | this.name = name; 28 | } 29 | 30 | public String getName(){ 31 | return name; 32 | } 33 | } 34 | class Manager extends Employee { 35 | public Manager(String name) { 36 | super(name); 37 | } 38 | } 39 | public class EmployeeClass { 40 | public static void main(String[] args) { 41 | Employee employee = new Employee("Jeff"); 42 | Employee manager = new Manager("Boss"); 43 | System.out.println(employee.getClass().getName() + " " + employee.getName()); 44 | System.out.println(manager.getClass().getName() + " " + manager.getName()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/reflection/ObjectAnalyzer.java: -------------------------------------------------------------------------------- 1 | package org.javacore.reflection; 2 | 3 | import java.lang.reflect.AccessibleObject; 4 | import java.lang.reflect.Array; 5 | import java.lang.reflect.Field; 6 | import java.lang.reflect.Modifier; 7 | import java.util.ArrayList; 8 | 9 | /* 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-11-9 10:45:19 28 | * 反射对象分析工具 @{link test/org.javacore.reflection.ObjectAnalyzerTest} 29 | */ 30 | public class ObjectAnalyzer { 31 | private ArrayList visited = new ArrayList<>(); 32 | 33 | public String toString(Object obj){ 34 | if (obj == null) return "null"; 35 | if (visited.contains(obj)) return "..."; 36 | visited.add(obj); 37 | 38 | // 获取Class对象 39 | Class cl = obj.getClass(); 40 | if (cl == String.class) return (String)obj; 41 | // 如果对象是一个数组类 42 | if (cl.isArray()){ 43 | // 获取数组组件 44 | String r = cl.getComponentType() + "[]{"; 45 | for (int i = 0; i < Array.getLength(obj); i++) { 46 | if (i > 0) r += ","; 47 | Object val = Array.get(obj,i); 48 | // 是否是一个基本类型 49 | if (cl.getComponentType().isPrimitive()) 50 | r += val; 51 | else r += toString(val); 52 | } 53 | return r + "}"; 54 | } 55 | 56 | String r =cl.getName(); 57 | do { 58 | r += "["; 59 | Field[] fields = cl.getDeclaredFields(); 60 | AccessibleObject.setAccessible(fields,true); 61 | for (Field f : fields){ 62 | if (!Modifier.isStatic(f.getModifiers())){ 63 | r += f.getName() + "="; 64 | try { 65 | Class t = f.getType(); 66 | Object val = f.get(obj); 67 | if (t.isPrimitive()) 68 | r += val; 69 | else 70 | r +=toString(val); 71 | } catch (Exception e){ 72 | e.printStackTrace(); 73 | } 74 | } 75 | } 76 | r += "]"; 77 | cl = cl.getSuperclass(); 78 | } while (cl != null); 79 | 80 | return r; 81 | } 82 | 83 | 84 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/reflection/User.java: -------------------------------------------------------------------------------- 1 | package org.javacore.reflection; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-9-8 09:35:14 21 | * 反射构造器使用的bean 22 | */ 23 | public class User { 24 | private int id; 25 | private String name; 26 | 27 | // 无参构造器(默认构造器) 28 | public User() { 29 | } 30 | 31 | public User(int id) { 32 | this.id = id; 33 | } 34 | 35 | public User(int id, String name) { 36 | this.id = id; 37 | this.name = name; 38 | } 39 | 40 | public int getId() { 41 | return id; 42 | } 43 | 44 | public void setId(int id) { 45 | this.id = id; 46 | } 47 | 48 | public String getName() { 49 | return name; 50 | } 51 | 52 | public void setName(String name) { 53 | this.name = name; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "User [id=" + id + ", name=" + name + "]"; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/reflection/UserConstructorReflect.java: -------------------------------------------------------------------------------- 1 | package org.javacore.reflection; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.InvocationTargetException; 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-9-8 09:35:35 24 | * 利用反射通过构造器创建一个实例 25 | */ 26 | public class UserConstructorReflect { 27 | public static void main(String[] args) throws NoSuchMethodException, 28 | SecurityException, InstantiationException, 29 | IllegalAccessException, IllegalArgumentException, 30 | InvocationTargetException { 31 | // 获取User类型 32 | Class userClass = User.class; 33 | // 获取默认构造器 34 | Constructor constructor = userClass.getConstructor(); 35 | // 获取带int参数的构造器 36 | Constructor intConstructor = userClass.getConstructor(int.class); 37 | // 获取带int和String参数的构造器 38 | Constructor bothConstructor = userClass.getConstructor(int.class,String.class); 39 | 40 | // 使用反射,获取新的User对象 41 | User u1 = (User) constructor.newInstance(); 42 | User u2 = (User) intConstructor.newInstance(1); 43 | User u3 = (User) bothConstructor.newInstance(2,"BYSocket"); 44 | 45 | System.out.println(u1.toString()); 46 | System.out.println(u2.toString()); 47 | System.out.println(u3.toString()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/rtti/ClassInitialization.java: -------------------------------------------------------------------------------- 1 | package org.javacore.rtti; 2 | 3 | import java.util.Random; 4 | 5 | /* 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | /** 21 | * @author Jeff Lee 22 | * @since 2015-11-2 16:43:41 23 | * Class初始化案例 24 | */ 25 | class Initable { 26 | static final int staticFinal = 47; 27 | static final int staticFinal2 = 28 | ClassInitialization.random.nextInt(1000); 29 | static { 30 | System.out.println("Initializing Initable"); 31 | } 32 | } 33 | 34 | class Initable2 { 35 | static int staticNonFinal = 147; 36 | static { 37 | System.out.println("Initializing Initable2"); 38 | } 39 | } 40 | 41 | class Initable3 { 42 | static int staticNonFinal = 74; 43 | static { 44 | System.out.println("Initializing Initable3"); 45 | } 46 | } 47 | 48 | public class ClassInitialization { 49 | public static Random random = new Random(47); 50 | 51 | public static void main(String[] args) throws ClassNotFoundException { 52 | // 类中有编译期常量 static Final,则暂时不需要初始化 53 | Class initable = Initable.class; 54 | System.out.println("After creating Initable ref"); 55 | System.out.println(Initable.staticFinal); 56 | // 调用非编译期常量,强制进行类Initable初始化 57 | System.out.println(Initable.staticFinal2); 58 | 59 | // 先进行初始化 60 | System.out.println(Initable2.staticNonFinal); 61 | 62 | // 无编译期常量,直接初始化 63 | Class initable3 = Class.forName("org.javacore.rtti.Initable3"); 64 | System.out.println("After creating Initable ref"); 65 | System.out.println(Initable3.staticNonFinal); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/rtti/ShowMethods.java: -------------------------------------------------------------------------------- 1 | package org.javacore.rtti; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.Method; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @author Jeff Lee 23 | * @since 2015-11-2 16:43:41 24 | * 获取Class方法案例 25 | */ 26 | public class ShowMethods { 27 | public static void main(String[] args) { 28 | try { 29 | Class c = Class.forName("org.javacore.rtti.ShowMethods"); 30 | Method[] methods = c.getMethods(); 31 | Constructor[] constructors = c.getConstructors(); 32 | for (Method m : methods) 33 | System.out.println(m.toGenericString()); 34 | for (Constructor constructor : constructors) 35 | System.out.println(constructor.toGenericString()); 36 | } catch (ClassNotFoundException e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/scheduler/SchedulerExecutorTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.scheduler; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.util.concurrent.Executors; 18 | import java.util.concurrent.ScheduledExecutorService; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | /** 22 | * ScheduledExecutorService的使用 23 | * @author BYSocket 24 | * @since 2016-01-10 14:20:00 25 | */ 26 | public class SchedulerExecutorTest implements 27 | Runnable { 28 | private final String jobName; 29 | 30 | public SchedulerExecutorTest(String jobName) { 31 | this.jobName = jobName; 32 | } 33 | 34 | @Override 35 | public void run() { 36 | System.out.println("running => " + jobName); 37 | } 38 | 39 | public static void main(String[] args) { 40 | ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); 41 | // 一秒 42 | executor.scheduleAtFixedRate(new SchedulerExecutorTest("job1"), 1, 1, TimeUnit.SECONDS); 43 | // 两秒 44 | executor.scheduleWithFixedDelay(new SchedulerExecutorTest("job2"),1,2,TimeUnit.SECONDS); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/scheduler/TimerTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.scheduler; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import java.util.Timer; 19 | import java.util.TimerTask; 20 | 21 | /** 22 | * Timer的使用 23 | * @author BYSocket 24 | * @since 2016-01-09 22:19:00 25 | */ 26 | public class TimerTest extends TimerTask{ 27 | 28 | private final String jobName; 29 | 30 | public TimerTest(String jobName) { 31 | this.jobName = jobName; 32 | } 33 | 34 | @Override 35 | public void run() { 36 | System.out.println("run the task => " + jobName); 37 | } 38 | 39 | public static void main(String[] args) { 40 | // 一种工具,线程用其安排以后在后台线程中执行的任务 41 | Timer timer = new Timer(); 42 | timer.schedule(new TimerTest("Job 1") , 1000 , 1000); // 一秒 43 | timer.schedule(new TimerTest("Job 2") , 2000 , 2000); // 两秒 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/CollectStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.stream.Collectors; 22 | 23 | /** 24 | * 25 | * Created by bysocket on 16/7/14. 26 | */ 27 | public class CollectStreamTest { 28 | public static void main(String[] args) { 29 | List list = Arrays.asList(1,2,3,4); 30 | Double result = list.stream().collect(Collectors.averagingDouble(d->d*2)); 31 | System.out.println(result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/CollectionStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import java.util.stream.Collectors; 22 | import java.util.stream.Stream; 23 | 24 | /** 25 | * Stream API 集合的流式操作 26 | * 27 | * Created by bysocket on 16/7/13. 28 | */ 29 | public class CollectionStreamTest { 30 | public static void main(String[] args) { 31 | List list = new ArrayList<>(); 32 | list.add("aa"); 33 | list.add("cccc"); 34 | list.add("bbb"); 35 | 36 | /** 37 | * Stream的使用: 38 | * 创建/获取流 -> 中间操作(过滤、转换等) -> 终止操作( 聚合、收集结果) 39 | */ 40 | list.stream().forEach(System.out::println); 41 | System.out.println(); 42 | 43 | /** 44 | * 过滤 45 | * collect语法 {@link StreamCollectTest} 46 | */ 47 | List list0 = list.stream().filter(str -> str.startsWith("cc")).collect(Collectors.toList()); 48 | List list1 = list.stream().filter(str -> str.startsWith("aa")).collect(Collectors.toList()); 49 | 50 | list0.stream().forEach(System.out::println); 51 | list1.stream().forEach(System.out::println); 52 | System.out.println(); 53 | 54 | /** 55 | * 转换 56 | */ 57 | List list2 = list.stream().map(str -> str.replace("c","*")).collect(Collectors.toList()); 58 | 59 | list2.stream().forEach(System.out::println); 60 | System.out.println(); 61 | 62 | /** 63 | * 提取 64 | * 从skip开始至limit位置为止 65 | */ 66 | List list3 = list.stream().skip(0).limit(1).collect(Collectors.toList()); 67 | 68 | list3.stream().forEach(System.out::println); 69 | System.out.println(); 70 | 71 | /** 72 | * 组合 73 | */ 74 | List list4 = Stream.concat(list.stream(),list.stream()).collect(Collectors.toList()); 75 | 76 | list4.stream().forEach(System.out::println); 77 | System.out.println(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/CollectionStreamTest01.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | /** 23 | * Stream API 集合的流式操作 24 | *

25 | * Created by bysocket on 16/7/13. 26 | */ 27 | public class CollectionStreamTest01 { 28 | public static void main(String[] args) { 29 | List strList = Arrays.asList("a1", "a2", "c3", "c6", "c4"); 30 | 31 | strList 32 | .stream() 33 | .filter(str -> str.startsWith("c")) 34 | .map(String::toUpperCase) 35 | .sorted() 36 | .forEach(System.out::println); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/ConcatStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.stream.Collectors; 22 | import java.util.stream.Stream; 23 | 24 | /** 25 | * 组合 - 流 26 | * 27 | * Created by bysocket on 16/7/14. 28 | */ 29 | public class ConcatStreamTest { 30 | public static void main(String[] args) { 31 | List list1 = Arrays.asList("a","b","c"); 32 | List list2 = Arrays.asList("d","e","f"); 33 | 34 | // 组合list1和list2的流 35 | List result = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList()); 36 | result.stream().forEach(System.out::println); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/CountFilterStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.stream.Collectors; 22 | 23 | /** 24 | * 过滤 25 | * 流的元素数量 26 | * 27 | * Created by bysocket on 16/7/14. 28 | */ 29 | public class CountFilterStreamTest { 30 | public static void main(String[] args) { 31 | List list1 = Arrays.asList("a","b","ac"); 32 | 33 | // filter 过滤 34 | List result = list1.stream().filter(str -> str.startsWith("a")).collect(Collectors.toList()); 35 | result.stream().forEach(System.out::println); 36 | System.out.println(); 37 | 38 | // count 流的元素数量 39 | long l = list1.stream().filter(str -> str.startsWith("a")).count(); 40 | System.out.println("list1 字符从a开始的数量:" + l); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/CreateStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * 创建流 21 | * 22 | * Created by bysocket on 16/7/18. 23 | */ 24 | public class CreateStreamTest { 25 | public static void main(String[] args) { 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/DistinctStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.stream.Collectors; 22 | 23 | /** 24 | * 去重 25 | * 26 | * Created by bysocket on 16/7/14. 27 | */ 28 | public class DistinctStreamTest { 29 | public static void main(String[] args) { 30 | List list1 = Arrays.asList("a","b","b","b","ac"); 31 | 32 | // 去重 33 | List result = list1.stream().distinct().collect(Collectors.toList()); 34 | result.stream().forEach(str -> System.out.print(str + " -> ")); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/stream/SortedStreamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.stream; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | /** 23 | * 排序 24 | * 25 | * Created by bysocket on 16/7/14. 26 | */ 27 | public class SortedStreamTest { 28 | public static void main(String[] args) { 29 | List list1 = Arrays.asList("a","e","b","ac"); 30 | // 排序 31 | list1.stream().sorted().forEach(str -> System.out.print(str + " -> ")); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/BasicThreads.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-11-2 17:06:48 22 | * 线程简单使用-启动LiftOff线程{@link LiftOff} 23 | */ 24 | public class BasicThreads { 25 | public static void main(String[] args) { 26 | // 创建新的线程 27 | Thread t = new Thread(new LiftOff()); 28 | // 执行线程 29 | t.start(); 30 | System.out.println("Waiting for LiftOff"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/CachedThreadPool.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-11-2 17:21:04 25 | * 线程池CachedThreadPool的简单使用-启动LiftOff线程{@link LiftOff} 26 | */ 27 | public class CachedThreadPool { 28 | public static void main(String[] args) { 29 | // 创建新线程的线程池 30 | ExecutorService exec = Executors.newCachedThreadPool(); 31 | for (int i = 0 ; i < 5; i++) 32 | exec.execute(new LiftOff()); // 由线程池Ececutor决定执行给定的线程。 33 | // 顺序关闭,执行以前提交的线程,不接受新的线程。 34 | exec.shutdown(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/CallableDemo.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.ArrayList; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | /** 10 | * Created by BYSocket on 2015/11/2. 11 | * 12 | * Copyright [2015] [Jeff Lee] 13 | * 14 | * Licensed under the Apache License, Version 2.0 (the "License"); 15 | * you may not use this file except in compliance with the License. 16 | * You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, software 21 | * distributed under the License is distributed on an "AS IS" BASIS, 22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | * See the License for the specific language governing permissions and 24 | * limitations under the License. 25 | */ 26 | 27 | /** 28 | * @author Jeff Lee 29 | * @since 2015-11-2 18:58:36 30 | * Callable接口的使用 --- 实现带返回值的任务 31 | */ 32 | 33 | // Callable实现类task,指定其类型参数 34 | class TaskWithResult implements Callable { 35 | 36 | private int id; 37 | public TaskWithResult(int id) { 38 | this.id = id; 39 | } 40 | 41 | @Override 42 | public String call() throws Exception { 43 | return "result of TaskWithResult " + id; 44 | } 45 | } 46 | 47 | public class CallableDemo { 48 | public static void main(String[] args) { 49 | // 创建一个新的线程池 50 | ExecutorService exec = Executors.newCachedThreadPool(); 51 | // Callable实现类task的返回结果集 52 | ArrayList> results = new ArrayList<>(); 53 | for (int i = 0; i < 5 ; i++) 54 | results.add(exec.submit(new TaskWithResult(i)));// 使用submit来启动Tasks 55 | 56 | // 异步计算的结果 57 | for (Future fs : results) 58 | try { 59 | // get阻塞,直至获取结果 60 | System.out.println(fs.get()); 61 | } catch (InterruptedException e) { 62 | System.out.println(e); 63 | e.printStackTrace(); 64 | } catch (ExecutionException e) { 65 | System.out.println(e); 66 | e.printStackTrace(); 67 | } finally { 68 | exec.shutdown(); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/DaemonFromFactory.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * Created by BYSocket on 2015/11/2. 9 | * 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-11-3 18:17:58 28 | * 后台线程工厂类的使用 29 | */ 30 | public class DaemonFromFactory implements Runnable { 31 | @Override 32 | public void run() { 33 | try { 34 | while (true){ 35 | TimeUnit.MICROSECONDS.sleep(100); 36 | System.out.println(Thread.currentThread() + " " + this); 37 | } 38 | } catch (InterruptedException e) { 39 | System.out.println("sleep() interrupted"); 40 | } 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | // 使用提供的线程工厂类,创建线程池 45 | ExecutorService exec = 46 | Executors.newCachedThreadPool(new DaemonThreadFactory()); 47 | for (int i = 0 ; i < 10 ; i++) 48 | exec.execute(new DaemonFromFactory());// 此Runnable实现类,经过线程工厂创建 49 | // 关闭线程池 50 | exec.shutdown(); 51 | System.out.println("任务已经全部启动"); 52 | TimeUnit.MICROSECONDS.sleep(500); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/DaemonThreadFactory.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ThreadFactory; 4 | 5 | /** 6 | * Created by BYSocket on 2015/11/2. 7 | * 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | /** 24 | * @author Jeff Lee 25 | * @since 2015-11-3 18:17:49 26 | * 线程工厂类 - 将线程设置为后台线程 27 | */ 28 | public class DaemonThreadFactory implements ThreadFactory { 29 | 30 | @Override 31 | public Thread newThread(Runnable r) { 32 | Thread t = new Thread(r); 33 | t.setDaemon(true); 34 | return t; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/DaemonsDontRunFinally.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by BYSocket on 2015/11/2. 7 | * 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | /** 24 | * @author Jeff Lee 25 | * @since 2015-11-3 18:17:58 26 | * 后台线程遇到Finally 27 | */ 28 | class ADaemon implements Runnable { 29 | 30 | @Override 31 | public void run() { 32 | try { 33 | System.out.println("启动ADaemon"); 34 | TimeUnit.SECONDS.sleep(1); 35 | } catch (InterruptedException e ){ 36 | System.out.println("InterruptedException"); 37 | } finally { 38 | // 因为main是非后台线程,main线程结束。ADaemon后台线程也就结束。因此可能没到finally就结束了。 39 | System.out.println("finally 运行吗?"); 40 | } 41 | } 42 | } 43 | public class DaemonsDontRunFinally { 44 | public static void main(String[] args) { 45 | Thread t = new Thread(new ADaemon()); 46 | // 设置线程为后台线程 47 | t.setDaemon(true); 48 | t.start(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/FixedThreadPool.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | /* 7 | * Copyright [2015] [Jeff Lee] 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-11-2 17:06:48 25 | * 线程池FixedThreadPool的简单使用-启动LiftOff线程{@link LiftOff} 26 | */ 27 | public class FixedThreadPool { 28 | public static void main(String[] args) { 29 | // 创建固定线程为5的线程池 30 | ExecutorService exec = Executors.newFixedThreadPool(5); 31 | for (int i = 0; i < 5 ;i++) 32 | exec.execute(new LiftOff());// 由线程池Ececutor决定执行给定的线程。 33 | // 顺序关闭,执行以前提交的线程,不接受新的线程。 34 | exec.shutdown(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/LiftOff.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-11-2 16:56:43 22 | * Runnable接口的实现类LiftOff 23 | */ 24 | public class LiftOff implements Runnable{ 25 | 26 | protected int countDown = 10; 27 | private static int taskCount = 0; 28 | private final int id = taskCount++; 29 | 30 | public LiftOff(){} 31 | public LiftOff(int countDown){ 32 | this.countDown = countDown; 33 | } 34 | 35 | public String status(){ 36 | return "#" + id + "(" + 37 | (countDown >0 ? countDown : "LiftOff!") + "), "; 38 | } 39 | @Override 40 | public void run() { 41 | while (countDown-- > 0){ 42 | System.out.println(status()); 43 | // 暂停当前正在执行线程,并执行其他线程。 44 | Thread.yield(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/MoreBasicThreads.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-11-2 17:09:33 22 | * 线程简单使用-启动多个LiftOff线程{@link LiftOff} 23 | */ 24 | public class MoreBasicThreads { 25 | public static void main(String[] args) { 26 | for (int i = 0; i < 5 ; i++) 27 | new Thread(new LiftOff()).start(); 28 | System.out.println("Waiting for LiftOff"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/MyRunnable.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-7-4 16:14:47 21 | * Runnable接口的简单使用 22 | * 测试 --> {@link MyRunnableTest} 23 | */ 24 | public class MyRunnable implements Runnable{ 25 | 26 | @Override 27 | public void run() { 28 | System.out.println("MyRunnable --> run()"); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/MyThread.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /* 4 | * Copyright [2015] [Jeff Lee] 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /** 20 | * @author Jeff Lee 21 | * @since 2015-7-4 16:14:51 22 | * Thread的简单使用 23 | * 测试 --> {@link MyThreadTest} 24 | */ 25 | public class MyThread extends Thread{ 26 | 27 | @Override 28 | public void run() { 29 | System.out.println("MyThread --> run()"); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/ProcessBuilderTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.io.IOException; 18 | import java.util.Scanner; 19 | 20 | /** 21 | * Java进程调用CMD 22 | * VM options => -Dfile.encoding="GBK" 23 | * @author BYSocket 24 | * @since 2016-01-18 16:08:00 25 | */ 26 | public class ProcessBuilderTest { 27 | public static void main(String[] args) throws IOException { 28 | ProcessBuilder pb = new ProcessBuilder("cmd","/c","ipconfig/all"); 29 | Process p = pb.start(); 30 | 31 | Scanner scanner = new Scanner(p.getInputStream()); 32 | while (scanner.hasNext()) 33 | System.out.println(scanner.next()); 34 | scanner.close(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/SimpleDaemons.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by BYSocket on 2015/11/2. 7 | * 8 | * Copyright [2015] [Jeff Lee] 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | /** 23 | * @author Jeff Lee 24 | * @since 2015-11-3 18:09:06 25 | * Daemon后台线程的简单使用 26 | */ 27 | public class SimpleDaemons implements Runnable{ 28 | @Override 29 | public void run() { 30 | try { 31 | while (true){ 32 | TimeUnit.MICROSECONDS.sleep(1000); 33 | System.out.println(Thread.currentThread() + " " + this); 34 | } 35 | } catch (InterruptedException e) { 36 | System.out.println("sleep() interrupted"); 37 | } 38 | } 39 | 40 | // main是非后台线程 41 | public static void main(String[] args) throws InterruptedException { 42 | for (int i = 0 ; i < 10 ; i++){ 43 | // 创建一个新线程 44 | Thread daemon = new Thread(new SimpleDaemons()); 45 | // 设置为后台线程 46 | daemon.setDaemon(true); 47 | daemon.start(); 48 | } 49 | System.out.println("所有任务已启动"); 50 | // 如果main结束,那么同时会杀死所有后台线程,多次运行你会发现,可能打印的后台线程数不定 51 | TimeUnit.MICROSECONDS.sleep(175); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/SimplePriorities.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /** 4 | * Created by BYSocket on 2015/11/2. 5 | * 6 | * Copyright [2015] [Jeff Lee] 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | import java.util.concurrent.ExecutorService; 22 | import java.util.concurrent.Executors; 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-11-3 09:05:03 27 | * 线程优先级的使用 28 | */ 29 | public class SimplePriorities implements Runnable { 30 | private int countDown = 5; 31 | private volatile double d; 32 | private int priority; 33 | 34 | public SimplePriorities(int priority){ 35 | this.priority = priority; 36 | } 37 | 38 | public String toString(){ 39 | // 获取当前执行的线程对象的引用 40 | return Thread.currentThread() + ": " + countDown; 41 | } 42 | 43 | @Override 44 | public void run() { 45 | // 获取当前执行的线程对象的引用,并设置其优先级。 46 | Thread.currentThread().setPriority(priority); 47 | 48 | while (true){ 49 | for (int i = 1; i < 100000; i++){ 50 | d += (Math.PI + Math.E) / (double) i; 51 | if (i % 1000 == 0) 52 | Thread.yield(); 53 | } 54 | System.out.println(this); 55 | if (--countDown == 0) return; 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | // 创建新的线程池 61 | ExecutorService exec = Executors.newCachedThreadPool(); 62 | for (int i = 0; i < 5 ;i++) 63 | exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));// 由线程池决定执行线程,并设置优先级最低 64 | exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));// 由线程池决定执行线程,并设置优先级最高 65 | // 顺序关闭,执行以前提交的线程,不接受新的线程 66 | exec.shutdown(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/SingleThreadExecutor.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | /** 7 | * Created by BYSocket on 2015/11/2. 8 | * 9 | * Copyright [2015] [Jeff Lee] 10 | * 11 | * Licensed under the Apache License, Version 2.0 (the "License"); 12 | * you may not use this file except in compliance with the License. 13 | * You may obtain a copy of the License at 14 | * 15 | * http://www.apache.org/licenses/LICENSE-2.0 16 | * 17 | * Unless required by applicable law or agreed to in writing, software 18 | * distributed under the License is distributed on an "AS IS" BASIS, 19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | * See the License for the specific language governing permissions and 21 | * limitations under the License. 22 | */ 23 | 24 | /** 25 | * @author Jeff Lee 26 | * @since 2015-11-2 18:58:36 27 | * SingleThreadExecutor的使用-启动LiftOff线程{@link LiftOff} 28 | */ 29 | public class SingleThreadExecutor { 30 | public static void main(String[] args) { 31 | // 创建使用单个worker线程的线程池Executor 32 | ExecutorService exec = Executors.newSingleThreadExecutor(); 33 | for (int i = 0; i < 5; i++) 34 | exec.execute(new LiftOff());// 由Executor决定执行给定的线程 35 | // 顺序关闭,执行已提交的线程,不准添加新的线程 36 | exec.shutdown(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/SleepRunThread.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; /* 2 | * Copyright [2015] [Jeff Lee] 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * Thread中start和run的区别 19 | * @author BYSocket 20 | * @since 2016-01-18 15:55:00 21 | */ 22 | public class SleepRunThread { 23 | public static void main(String[] args) { 24 | System.out.println("当前线程ID => " + Thread.currentThread().getId()); 25 | 26 | SRThread t1 = new SRThread("t1"); 27 | t1.start(); 28 | SRThread t2 = new SRThread("t2"); 29 | t2.run(); 30 | } 31 | } 32 | class SRThread extends Thread { 33 | private String name; 34 | 35 | public SRThread(String name) { 36 | this.name = name; 37 | } 38 | 39 | @Override 40 | public void run() { 41 | System.out.println("name:" + name +", 线程ID => " + Thread.currentThread().getId()); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/SleepingTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * Created by BYSocket on 2015/11/2. 9 | * 10 | * Copyright [2015] [Jeff Lee] 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ 24 | 25 | /** 26 | * @author Jeff Lee 27 | * @since 2015-11-3 09:04:16 28 | * 休眠线程sleep的使用 29 | */ 30 | public class SleepingTask extends LiftOff { 31 | @Override 32 | public void run(){ 33 | while(countDown-- > 0){ 34 | try { 35 | System.out.println(status()); 36 | // 老版本调用:Thread.sleep(1000); 37 | TimeUnit.MICROSECONDS.sleep(100); 38 | } catch (InterruptedException e) { 39 | e.printStackTrace(); 40 | } 41 | } 42 | } 43 | 44 | public static void main(String[] args) { 45 | // 创建新的线程池 46 | ExecutorService exec = Executors.newCachedThreadPool(); 47 | for (int i = 0; i < 5;i++) 48 | exec.execute(new SleepingTask());// 由线程池决定执行线程 49 | // 顺序关闭,执行以前提交的线程,不接受新的线程 50 | exec.shutdown(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/ThreadInfo.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | 8 | /** 9 | * 描述:线程优先级案例 10 | * Created by bysocket on 16/2/24. 11 | */ 12 | public class ThreadInfo { 13 | public static void main(String[] args) { 14 | Thread threads[] = new Thread[10]; 15 | Thread.State status[] = new Thread.State[10]; 16 | for (int i = 0; i < 10; i++) { 17 | threads[i] = new Thread(new Calculator(i)); 18 | if ((i % 2) == 0) { 19 | threads[i].setPriority(Thread.MAX_PRIORITY); 20 | } else { 21 | threads[i].setPriority(Thread.MIN_PRIORITY); 22 | } 23 | // threads[i].setName(""); 24 | } 25 | 26 | try { 27 | // 将线程的信息写入log文件 28 | FileWriter fw = new FileWriter(".\\log.txt"); 29 | PrintWriter pw = new PrintWriter(fw); 30 | 31 | for (int i = 0; i <10 ;i++) { 32 | pw.println("Main: Status of Thread " + i + " : " 33 | + threads[i].getState()); 34 | status[i] = threads[i].getState(); 35 | } 36 | 37 | // 启动线程 38 | for (int i = 0; i < 10 ;i++) 39 | threads[i].start(); 40 | 41 | boolean finish = false; 42 | while (!finish) { 43 | for(int i = 0;i < 10 ;i++) { 44 | if (threads[i].getState() != status[i]) { 45 | writeThreadInfo(pw,threads[i],status[i]); 46 | status[i] = threads[i].getState(); 47 | } 48 | } 49 | finish = true; 50 | for (int i = 0;i < 10 ;i++) { 51 | finish = finish && (threads[i].getState() == Thread.State.TERMINATED);//中断 52 | } 53 | } 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | 59 | private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State status) { 60 | pw.printf("Main: Id %d - $s\n",thread.getId(),thread.getName()); 61 | pw.printf("Main: Priority: %d\n",thread.getPriority()); 62 | pw.printf("Main: OldState: %s\n",status); 63 | pw.printf("Main: New State: %s\n",thread.getState()); 64 | pw.printf("*****************************************\n"); 65 | } 66 | } 67 | class Calculator implements Runnable { 68 | 69 | private int number; 70 | 71 | public Calculator(int number) { 72 | this.number = number; 73 | } 74 | 75 | @Override 76 | public void run() { 77 | for (int i = 0;i <=10; i++) { 78 | System.out.printf("%s: %d * %d = %d\n", 79 | Thread.currentThread().getName(), 80 | number, i, i * number); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/ThreadInterrupt.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | 3 | /** 4 | * Created by bysocket on 16/2/24. 5 | */ 6 | public class ThreadInterrupt { 7 | public static void main(String[] args) throws InterruptedException { 8 | Thread inThread = new Thread(new InterrupThread()); 9 | inThread.start(); 10 | Thread.sleep(1000); 11 | inThread.interrupt(); 12 | } 13 | } 14 | class InterrupThread implements Runnable { 15 | 16 | private int num = 1; 17 | @Override 18 | public void run() { 19 | while (true) 20 | System.out.println("true ----> " + num++); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/daemon/CleanerTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.daemon; 2 | 3 | import java.util.Date; 4 | import java.util.Deque; 5 | 6 | /** 7 | * 描述:管理这个队列,如果事件超过10秒钟,就会被移除 8 | * Created by bysocket on 16/3/4. 9 | */ 10 | public class CleanerTask extends Thread{ 11 | private Deque deque; 12 | 13 | public CleanerTask(Deque deque) { 14 | this.deque = deque; 15 | setDaemon(true); 16 | } 17 | 18 | @Override 19 | public void run() { 20 | while (true) { 21 | Date date = new Date(); 22 | clean(date); 23 | } 24 | } 25 | 26 | /** 27 | * 删除该时间前10s内创建的事件对象 28 | * @param date 29 | */ 30 | private void clean(Date date) { 31 | long difference = 0; 32 | boolean delete; 33 | if (deque.size() == 0) { 34 | return; 35 | } 36 | delete = false; 37 | 38 | do { 39 | Event e = deque.getLast(); 40 | difference = date.getTime() - e.getDate().getTime(); 41 | if (difference > 10000) { 42 | System.out.printf("Cleaner: %s \n",e.getEvent()); 43 | deque.removeLast(); 44 | delete = true; 45 | } 46 | } while (difference > 10000); 47 | 48 | if (delete) { 49 | System.out.printf("Cleaner: Size of the queue: %d\n",deque.size()); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/daemon/DaemonTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.daemon; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | /** 7 | * 1. 知道3个WriteTask线程休眠后,CleanerTask才执行 8 | * 2. 从结果中,可以看出队列维持在一定数量当中 9 | * Created by bysocket on 16/3/4. 10 | */ 11 | public class DaemonTest { 12 | public static void main(String[] args) { 13 | Deque deque = new ArrayDeque<>(); 14 | WriterTask writerTask = new WriterTask(deque); 15 | for (int i = 0; i < 3 ; i++) { 16 | Thread thread = new Thread(writerTask); 17 | thread.start(); 18 | } 19 | 20 | CleanerTask cleanerTask = new CleanerTask(deque); 21 | cleanerTask.start(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/daemon/Event.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.daemon; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * 描述:事件类 7 | * Created by bysocket on 16/3/4. 8 | */ 9 | public class Event { 10 | private Date date; 11 | private String event; 12 | 13 | public Date getDate() { 14 | return date; 15 | } 16 | 17 | public void setDate(Date date) { 18 | this.date = date; 19 | } 20 | 21 | public String getEvent() { 22 | return event; 23 | } 24 | 25 | public void setEvent(String event) { 26 | this.event = event; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/daemon/WriterTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.daemon; 2 | 3 | import java.util.Date; 4 | import java.util.Deque; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * 描述:写事件到一个队列 9 | * Created by bysocket on 16/3/4. 10 | */ 11 | public class WriterTask implements Runnable { 12 | private Deque deque; 13 | 14 | public WriterTask(Deque deque) { 15 | this.deque = deque; 16 | } 17 | 18 | @Override 19 | public void run() { 20 | for (int i = 1; i < 100; i++) { 21 | Event event = new Event(); 22 | event.setDate(new Date()); 23 | event.setEvent(String.format("The thread %s has generated an event",Thread.currentThread().getId())); 24 | deque.addFirst(event); 25 | 26 | try { 27 | TimeUnit.SECONDS.sleep(1); 28 | } catch (InterruptedException e) { 29 | e.printStackTrace(); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/join/DSLoader.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.join; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by bysocket on 16/3/3. 7 | */ 8 | public class DSLoader implements Runnable { 9 | @Override 10 | public void run() { 11 | System.out.println("begining the DSLoader"); 12 | try { 13 | TimeUnit.SECONDS.sleep(4); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | System.out.println("DSLoader has finished"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/join/JoinTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.join; 2 | 3 | /** 4 | * Created by bysocket on 16/3/3. 5 | */ 6 | public class JoinTest { 7 | public static void main(String[] args) throws InterruptedException { 8 | Thread t1 = new Thread(new DSLoader()); 9 | Thread t2 = new Thread(new NetLoader()); 10 | 11 | t1.start(); 12 | t2.start(); 13 | 14 | //可以注释其中一个加深理解 15 | t1.join(); 16 | //t2.join(); 17 | 18 | System.out.println("ending all"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/join/NetLoader.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.join; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by bysocket on 16/3/3. 7 | */ 8 | public class NetLoader implements Runnable { 9 | @Override 10 | public void run() { 11 | System.out.println("begining the NetLoader"); 12 | try { 13 | TimeUnit.SECONDS.sleep(6); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | System.out.println("NetLoader has finished"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/threadlocal/SafeTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.threadlocal; 2 | 3 | import java.util.Date; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | /** 7 | * 描述:看类里面说明 8 | * Created by bysocket on 16/3/8. 9 | */ 10 | public class SafeTask implements Runnable{ 11 | /** 12 | * ThreadLocal对象不会被所有线程共享 13 | * --> 线程局部变量 <-- 14 | */ 15 | private static ThreadLocal startDate = new ThreadLocal(){ 16 | /** 17 | * 隐式实现初始化对象 18 | * @return 19 | */ 20 | @Override 21 | protected Date initialValue() { 22 | return new Date(); 23 | } 24 | }; 25 | 26 | @Override 27 | public void run() { 28 | System.out.printf("Starting Thread:%s : %s\n",Thread.currentThread().getId(),startDate.get()); 29 | try { 30 | TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10)); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | System.out.printf("Finish Thread:%s : %s\n",Thread.currentThread().getId(),startDate.get()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/threadlocal/SafeTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.threadlocal; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * 描述:可以看到线程每个有不同的启动时间,但是结束时间也会不相同. 7 | * Created by bysocket on 16/3/8. 8 | */ 9 | public class SafeTest { 10 | public static void main(String[] args) { 11 | SafeTask task = new SafeTask(); 12 | for (int i = 0 ; i < 10; i++) { 13 | Thread thread = new Thread(task); 14 | thread.start(); 15 | 16 | try { 17 | TimeUnit.SECONDS.sleep(2); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/threadlocal/UnsafeTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.threadlocal; 2 | 3 | import java.util.Date; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | /** 7 | * 描述:私有变量会被所有线程共享 8 | * Created by bysocket on 16/3/8. 9 | */ 10 | public class UnsafeTask implements Runnable{ 11 | private Date startDate; 12 | 13 | @Override 14 | public void run() { 15 | startDate = new Date(); 16 | System.out.printf("Starting Thread:%s : %s\n",Thread.currentThread().getId(),startDate); 17 | try { 18 | TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10)); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | System.out.printf("Finish Thread:%s : %s\n",Thread.currentThread().getId(),startDate); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/threadlocal/UnsafeTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.threadlocal; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * 描述:可以看到线程每个有不同的启动时间,但是结束时间会有相同. 7 | * Created by bysocket on 16/3/8. 8 | */ 9 | public class UnsafeTest { 10 | public static void main(String[] args) { 11 | UnsafeTask task = new UnsafeTask(); 12 | for (int i = 0 ; i < 10; i++) { 13 | Thread thread = new Thread(task); 14 | thread.start(); 15 | 16 | try { 17 | TimeUnit.SECONDS.sleep(2); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/uncaughtexp/ExceptionHadler.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.uncaughtexp; 2 | 3 | import java.lang.Thread.UncaughtExceptionHandler; 4 | 5 | /** 6 | * 描述:处理运行时异常的类 7 | * Created by bysocket on 16/3/4. 8 | */ 9 | public class ExceptionHadler implements UncaughtExceptionHandler{ 10 | @Override 11 | public void uncaughtException(Thread t, Throwable e) { 12 | System.out.printf("An exception has been captured\n"); 13 | System.out.printf("Thread: %s\n",t.getId()); 14 | System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage()); 15 | System.out.printf("Stack Trace: \n"); 16 | e.printStackTrace(System.out); 17 | System.out.printf("Thread status: %s\n",t.getState()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/uncaughtexp/UncaughtTask.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.uncaughtexp; 2 | 3 | /** 4 | * 描述:抛出运行时异常的线程类 5 | * Created by bysocket on 16/3/4. 6 | */ 7 | public class UncaughtTask implements Runnable { 8 | @Override 9 | public void run() { 10 | int numero = Integer.parseInt("TTTT"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/javacore/thread/uncaughtexp/UncaughtTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread.uncaughtexp; 2 | 3 | /** 4 | * 描述:实现异常类Test 5 | * Created by bysocket on 16/3/4. 6 | */ 7 | public class UncaughtTest { 8 | public static void main(String[] args) { 9 | UncaughtTask uncaughtTask = new UncaughtTask(); 10 | Thread thread = new Thread(uncaughtTask); 11 | thread.setUncaughtExceptionHandler(new ExceptionHadler()); 12 | thread.start(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/jee/rpc/EchoService.java: -------------------------------------------------------------------------------- 1 | package org.jee.rpc; 2 | 3 | /** 4 | * 描述:服务Echo接口类 5 | * Created by bysocket on 16/2/28. 6 | */ 7 | public interface EchoService { 8 | String echo(String ping); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/jee/rpc/EchoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.jee.rpc; 2 | 3 | /** 4 | * 描述:服务Echo实现类 5 | * Created by bysocket on 16/2/28. 6 | */ 7 | public class EchoServiceImpl implements EchoService { 8 | @Override 9 | public String echo(String ping) { 10 | return ping != null ? ping + " --> I am ok." : "I am ok."; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/jee/rpc/RpcImporter.java: -------------------------------------------------------------------------------- 1 | package org.jee.rpc; 2 | 3 | import java.io.ObjectInputStream; 4 | import java.io.ObjectOutputStream; 5 | import java.lang.reflect.InvocationHandler; 6 | import java.lang.reflect.Method; 7 | import java.lang.reflect.Proxy; 8 | import java.net.InetSocketAddress; 9 | import java.net.Socket; 10 | 11 | /** 12 | * 描述:Rpc本地服务代理类 13 | * 1. 将本地接口调用转化为JDK的动态调用,在动态调用中实现接口的远程调用 14 | * 2. 创建Socket客户端,根据制定地址连接远程服务提供者 15 | * 3. 将远程服务调用所需的接口类,方法名,参数列表等编码后发送给服务提供者 16 | * 4. 同步阻塞等待服务端返回应答,获取应答后返回 17 | * Created by bysocket on 16/2/29. 18 | */ 19 | public class RpcImporter { 20 | public S importer(final Class serviceClass, final InetSocketAddress address) { 21 | // JDK动态代理,实现接口的远程调用 22 | return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), 23 | new Class[]{serviceClass.getInterfaces()[0]}, 24 | new InvocationHandler() { 25 | 26 | @Override 27 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 28 | Socket socket = null; 29 | ObjectOutputStream output = null; 30 | ObjectInputStream input = null; 31 | 32 | try { 33 | // 连接远程服务提供者 34 | socket = new Socket(); 35 | socket.connect(address); 36 | 37 | // 对象输出流 38 | output = new ObjectOutputStream(socket.getOutputStream()); 39 | output.writeUTF(serviceClass.getName()); 40 | output.writeUTF(method.getName()); 41 | output.writeObject(method.getParameterTypes()); 42 | output.writeObject(args); 43 | 44 | input = new ObjectInputStream(socket.getInputStream()); 45 | return input.readObject(); 46 | } finally { 47 | if (socket != null) { 48 | socket.close(); 49 | } 50 | if (output != null) { 51 | output.close(); 52 | } 53 | if (input != null) { 54 | input.close(); 55 | } 56 | } 57 | } 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/jee/rpc/RpcTest.java: -------------------------------------------------------------------------------- 1 | package org.jee.rpc; 2 | 3 | import java.io.IOException; 4 | import java.net.InetSocketAddress; 5 | 6 | /** 7 | * 描述:RPC测试代码类 8 | * Created by bysocket on 16/2/29. 9 | */ 10 | public class RpcTest { 11 | public static void main(String[] args) { 12 | // 启动服务提供者 13 | new Thread(new Runnable() { 14 | @Override 15 | public void run() { 16 | try { 17 | RpcExporter.exporter("localhost",8088); 18 | } catch (IOException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | }).start(); 23 | 24 | // 创建服务本地代理 25 | RpcImporter importer = new RpcImporter<>(); 26 | 27 | // 从服务本地代理获取服务对象类 28 | EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8088)); 29 | System.out.println(echo.echo("Are you OK?")); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/resources/collections/绘图1.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanwanpp/java-core-learning-example/3ed170bf7164461f80451a12e0c14f6cccfa1217/src/main/resources/collections/绘图1.vsdx -------------------------------------------------------------------------------- /src/main/resources/io/file/file.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanwanpp/java-core-learning-example/3ed170bf7164461f80451a12e0c14f6cccfa1217/src/main/resources/io/file/file.vsdx -------------------------------------------------------------------------------- /src/main/resources/io/file/file01.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanwanpp/java-core-learning-example/3ed170bf7164461f80451a12e0c14f6cccfa1217/src/main/resources/io/file/file01.vsdx -------------------------------------------------------------------------------- /src/main/resources/io/file/filenameFilter.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanwanpp/java-core-learning-example/3ed170bf7164461f80451a12e0c14f6cccfa1217/src/main/resources/io/file/filenameFilter.vsdx -------------------------------------------------------------------------------- /src/main/resources/io/iostream/iostream.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanwanpp/java-core-learning-example/3ed170bf7164461f80451a12e0c14f6cccfa1217/src/main/resources/io/iostream/iostream.vsdx -------------------------------------------------------------------------------- /src/test/java/org/javacore/io/DirectoryTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.io; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-7-13 10:06:56 21 | * {@link Directory}的测试类 22 | */ 23 | public class DirectoryTest { 24 | public static void main(String[] args) { 25 | // 打印当前目录和文件 26 | System.out.println(Directory.walk(".")); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/param/Param.java: -------------------------------------------------------------------------------- 1 | package org.javacore.param; 2 | 3 | /** 4 | * Created by bysocket on 16/7/18. 5 | */ 6 | public class Param { 7 | Integer id; 8 | 9 | String name; 10 | 11 | Integer age; 12 | 13 | String sex; 14 | 15 | Integer isBeautiful; 16 | 17 | public Integer getId() { 18 | return id; 19 | } 20 | 21 | public void setId(Integer id) { 22 | this.id = id; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | public Integer getAge() { 34 | return age; 35 | } 36 | 37 | public void setAge(Integer age) { 38 | this.age = age; 39 | } 40 | 41 | public String getSex() { 42 | return sex; 43 | } 44 | 45 | public void setSex(String sex) { 46 | this.sex = sex; 47 | } 48 | 49 | public Integer getIsBeautiful() { 50 | return isBeautiful; 51 | } 52 | 53 | public void setIsBeautiful(Integer isBeautiful) { 54 | this.isBeautiful = isBeautiful; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/param/ParamService.java: -------------------------------------------------------------------------------- 1 | package org.javacore.param; 2 | 3 | /** 4 | * Created by bysocket on 16/7/18. 5 | */ 6 | public class ParamService { 7 | 8 | public void test01(Param param) { 9 | Integer id = param.getId(); 10 | String sex = param.getSex(); 11 | String name = param.getName(); 12 | Integer age = param.getAge(); 13 | Integer isBeautiful = param.getIsBeautiful(); 14 | 15 | 16 | } 17 | 18 | public void test02(Integer id,String sex,String name,Integer age,Integer isBeautiful) { 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/param/ParamTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.param; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * Created by bysocket on 16/7/18. 7 | */ 8 | public class ParamTest { 9 | 10 | public static void main(String[] args) { 11 | ParamService p = new ParamService(); 12 | 13 | Date start = new Date(); 14 | for (int i = 1 ; i < 1000000; i++) { 15 | p.test02(1,"2","3",4,5); 16 | } 17 | Date end = new Date(); 18 | System.out.println("ParamService.test02() : " + (end.getTime() - start.getTime()) ); 19 | Date start2 = new Date(); 20 | for (int i = 1 ; i < 100000; i++) { 21 | Param param = new Param(); 22 | param.setId(1); 23 | param.setAge(2); 24 | param.setIsBeautiful(1); 25 | param.setName("2"); 26 | param.setSex("2"); 27 | p.test01(param); 28 | } 29 | Date end2 = new Date(); 30 | System.out.println("ParamService.test01() : " + (end2.getTime() - start2.getTime()) ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/thread/MyRunnableTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-7-4 16:15:38 21 | * Thread的简单实用测试 {@link MyRunnable} 22 | */ 23 | public class MyRunnableTest { 24 | public static void main(String[] args) { 25 | // 创建线程 26 | Thread thread = new Thread(new MyRunnable()); 27 | // 启动线程 28 | thread.start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/thread/MyThreadTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.thread; 2 | /* 3 | * Copyright [2015] [Jeff Lee] 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * @author Jeff Lee 20 | * @since 2015-7-4 16:15:38 21 | * Thread的简单实用测试 {@link MyThread} 22 | */ 23 | public class MyThreadTest { 24 | public static void main(String[] args) { 25 | // 创建线程 26 | MyThread mThread = new MyThread(); 27 | // 启动线程 28 | mThread.start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/DurationTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.fail; 7 | 8 | public class DurationTest { 9 | @Test 10 | public void testCombineTimeUtil() throws Exception { 11 | Assert.assertEquals(Duration.days(1).toMilliseconds(), 24 * 3600 * 1000); 12 | Assert.assertEquals(24 * 3600 * 1000 * 3, Duration.days(3).toMilliseconds()); 13 | Assert.assertEquals(7 * 24 * 3600 * 1000 / 1000, Duration.days(7).toSeconds()); 14 | } 15 | 16 | @Test 17 | public void testValidDurationStrings() throws Exception { 18 | Assert.assertEquals(Duration.of("5ns"), Duration.nanoseconds(5)); 19 | Assert.assertEquals(Duration.of("5microsecond"), Duration.microseconds(5)); 20 | Assert.assertEquals(Duration.of("5milliseconds"), Duration.millis(5)); 21 | Assert.assertEquals(Duration.of("5 seconds"), Duration.seconds(5)); 22 | Assert.assertEquals(Duration.of("5 minutes"), Duration.mins(5)); 23 | Assert.assertEquals(Duration.of("5 hours"), Duration.hours(5)); 24 | Assert.assertEquals(Duration.of("5 days"), Duration.days(5)); 25 | Assert.assertEquals(Duration.of("inf"), Duration.inf()); 26 | Assert.assertEquals(Duration.of("infinite"), Duration.inf()); 27 | Assert.assertEquals(Duration.of("∞"), Duration.infinite()); 28 | 29 | // Interesting value but legal nevertheless 30 | Assert.assertEquals(Duration.of("0s"), Duration.seconds(0)); 31 | } 32 | 33 | private void testInvalidDurationString(String duration) { 34 | try { 35 | Duration.of(duration); 36 | fail("Duration string '" + duration + "' should not parse correctly."); 37 | } catch (IllegalArgumentException iae) { 38 | // Expected 39 | } 40 | } 41 | 42 | @Test 43 | public void testInvalidDurationStrings() { 44 | testInvalidDurationString("foobar"); 45 | testInvalidDurationString("ms3"); 46 | testInvalidDurationString("34 lightyears"); 47 | testInvalidDurationString("34 seconds a day"); 48 | testInvalidDurationString("5 days a week"); 49 | testInvalidDurationString(""); 50 | testInvalidDurationString("2"); 51 | testInvalidDurationString("ns"); 52 | } 53 | 54 | @Test 55 | public void testReplaceOldTimeUtils() { 56 | final int HOUR = 1000 * 60 * 60; 57 | long randomTimestamp = (long) (Math.random() * 400000000L) + 100000; 58 | Assert.assertEquals(randomTimestamp / HOUR, Duration.millis(randomTimestamp).toHours()); 59 | Assert.assertEquals(randomTimestamp / 1000, Duration.millis(randomTimestamp).toSeconds()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/InstantTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import java.time.Instant; 4 | 5 | /** 6 | * 瞬间类 Instant 7 | * 8 | * Created by bysocket on 16/7/12. 9 | */ 10 | public class InstantTest { 11 | public static void main(String[] args) { 12 | // 获取现在的时间 13 | Instant now = Instant.now(); 14 | System.out.println(now); 15 | 16 | // 1000000000 年 12月 31日 17 | Instant max = Instant.MAX; 18 | System.out.println(max); 19 | 20 | // 10亿年前 21 | Instant min = Instant.MIN; 22 | System.out.println(min); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/LocalDateTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import java.time.LocalDate; 4 | 5 | /** 6 | * Created by bysocket on 16/8/23. 7 | */ 8 | public class LocalDateTest { 9 | public static void main(String[] args) { 10 | // 今天的日期 11 | LocalDate localDate = LocalDate.now(); 12 | 13 | System.out.println("今天:" + localDate); 14 | 15 | // 年 16 | System.out.println("年:" + localDate.getYear()); 17 | // 月 18 | System.out.println("月:" + localDate.getMonth()); 19 | System.out.println("月:" + localDate.getMonth()); 20 | // 星期 21 | System.out.println("今天是星期" + localDate.getDayOfWeek()); 22 | 23 | // 距离 24 | // 年 25 | System.out.println("今天是今年的第" + localDate.getDayOfYear() + "天"); 26 | // 月 27 | System.out.println("今天是这个月的第" + localDate.getDayOfMonth() + "天"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/LocalDateTest1.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import java.time.LocalDate; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | /** 7 | * Created by bysocket on 16/8/23. 8 | */ 9 | public class LocalDateTest1 { 10 | public static void main(String[] args) throws InterruptedException { 11 | LocalDate start = LocalDate.now(); 12 | TimeUnit.SECONDS.sleep(3); 13 | LocalDate end = LocalDate.now(); 14 | 15 | System.out.println(start.isAfter(end)); 16 | System.out.println(start.isBefore(end)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/LocalDateTest2.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import java.time.LocalDate; 4 | 5 | /** 6 | * 计算BYSocket的生日是今年的第几天 7 | * 8 | * Created by bysocket on 16/8/23. 9 | */ 10 | public class LocalDateTest2 { 11 | public static void main(String[] args) { 12 | LocalDate birthdayDate = LocalDate.of(2016,5,2); 13 | System.out.println("BYSocket的生日是今年的第" + birthdayDate.getDayOfYear() + "天"); 14 | // 明年的生日 15 | System.out.println(birthdayDate.plusYears(1)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/PlayDuration.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import java.time.Duration; 4 | import java.time.Instant; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * 持续时间类 Duration 9 | * 10 | * Created by bysocket on 16/8/23. 11 | */ 12 | public class PlayDuration { 13 | public static void main(String[] args) throws InterruptedException { 14 | Instant start = Instant.now(); 15 | TimeUnit.SECONDS.sleep(3); 16 | Instant end = Instant.now(); 17 | 18 | // 获取持续时间 19 | Duration timeElapsed = Duration.between(start,end); 20 | System.out.println(timeElapsed.toMillis());// 毫秒 21 | System.out.println(timeElapsed.toNanos());// 纳 22 | 23 | Instant start1 = Instant.now(); 24 | TimeUnit.SECONDS.sleep(2); 25 | Instant end1 = Instant.now(); 26 | 27 | // 获取持续时间 28 | Duration timeElapsed1 = Duration.between(start1,end1); 29 | 30 | // 添加操作 31 | Duration all = timeElapsed.plus(timeElapsed1); 32 | System.out.println(all.toMillis());// 毫秒 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/javacore/time/TimeUtilTest.java: -------------------------------------------------------------------------------- 1 | package org.javacore.time; 2 | 3 | import org.junit.FixMethodOrder; 4 | import org.junit.Test; 5 | import org.junit.runners.MethodSorters; 6 | 7 | import java.time.LocalDateTime; 8 | 9 | import static org.javacore.time.TimeUtil.TimeFormat.LONG_DATE_PATTERN_DOUBLE_SLASH; 10 | import static org.javacore.time.TimeUtil.TimeFormat.LONG_DATE_PATTERN_SLASH; 11 | import static org.junit.Assert.assertEquals; 12 | 13 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 14 | public class TimeUtilTest { 15 | 16 | @Test 17 | public void testParseSpecificTimeStringByUsingDefaultPattern() throws Exception { 18 | LocalDateTime expectedDateTime = LocalDateTime.of(2014, 11, 11, 10, 11, 11); 19 | LocalDateTime parsedTime = TimeUtil.parseTime("2014-11-11 10:11:11"); 20 | assertEquals(expectedDateTime, parsedTime); 21 | } 22 | 23 | @Test 24 | public void testParseSpecificTimeStringUsingTimeFormat() throws Exception { 25 | LocalDateTime expectedDateTime = LocalDateTime.of(2014, 11, 11, 10, 11, 11); 26 | LocalDateTime parsedTime = TimeUtil.parseTime("2014/11/11 10:11:11", LONG_DATE_PATTERN_SLASH); 27 | assertEquals(expectedDateTime, parsedTime); 28 | } 29 | 30 | @Test 31 | public void testParseLocalDateTimeByUsingDefaultFormatter() throws Exception { 32 | LocalDateTime time = LocalDateTime.of(2014, 11, 11, 10, 11, 11); 33 | assertEquals(TimeUtil.parseTime(time), "2014-11-11 10:11:11"); 34 | } 35 | 36 | @Test 37 | public void testParseLocalDateTimeByUsingTimeFormat() throws Exception { 38 | LocalDateTime time = LocalDateTime.of(2014, 11, 11, 10, 11, 11); 39 | assertEquals(TimeUtil.parseTime(time, LONG_DATE_PATTERN_DOUBLE_SLASH), "2014\\11\\11 10:11:11"); 40 | } 41 | } 42 | --------------------------------------------------------------------------------