├── .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