* 原则:重写一个对象的 equals方法时,必须同时重写 hashCode方法
* 两个对象 equals,两个对象必须拥有相同的 hashcode.
*
* 扩展:hashcode算法
*
* @return
*/
public int hashCode() {
return firstName.hashCode();
}
public int compareTo(Object o) {
Name n = (Name) o;
int lastCmp = lastName.compareTo(n.lastName);
return lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName);
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/BasicGeneric.java
================================================
package com.basic.chapter0600;
import java.util.*;
/**
* Java 泛型底层:
* https://www.cnblogs.com/liang1101/p/6407871.html
*
* @author MarkShen
* @since 20191221
*/
public class BasicGeneric {
public static void main(String[] args) {
/**
* 泛型起因:
* JDK1.4以前类型不明确
* 装入集合的类型被当作Object被对待,从而失去自己实际的类型
* 从集合中取出时往往需要转型,效率低,容易产生错误
* 解决方法:
* 在定义集合的时候,同时定义集合中元素的类型
* 可在定义Collection的时候指定
* 也可在循环时用Iterator指定
*
* 好处:
* 增强程序的可读性和稳定性
*/
// 有序可以重复
List c = new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
for (int i = 0; i < c.size(); i++) {
String s = c.get(i);
System.out.println(s);
}
c.add(1, "insert");
System.out.println();
for (String s : c) {
System.out.println(s);
}
Collection c2 = new HashSet();
c2.add("aaa");
c2.add("bbb");
c2.add("ccc");
for (Iterator it = c2.iterator(); it.hasNext(); ) {
String s = it.next();
System.out.println(s);
}
}
}
class MyName implements Comparable {
int age;
public int compareTo(MyName mn) {
if (this.age > mn.age) return 1;
else if (this.age < mn.age) return -1;
else return 0;
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/CollectionsTest.java
================================================
package com.basic.chapter0600;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* 工具类测试 Collections
*
* @author MarkShen
* @since 20191217
*/
public class CollectionsTest {
public static void main(String[] args) {
List strs = new LinkedList<>();
for (int i = 0; i < 10; i++) {
strs.add("a" + i);
}
System.out.println(strs);
Collections.shuffle(strs);
System.out.println(strs);
Collections.reverse(strs);
System.out.println(strs);
Collections.sort(strs);
System.out.println(strs);
System.out.println(Collections.binarySearch(strs, "a5"));
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/DataStructureSelection.java
================================================
package com.basic.chapter0600;
/**
* 数据结构选择
*/
public class DataStructureSelection {
public static void main(String[] args) {
// 读快写慢 ArrayList 基于数组实现
// 写快读慢 LinkedList 基于链表实现
// 介于两者中间 Hash
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/EnhancedFor.java
================================================
package com.basic.chapter0600;
import java.util.*;
public class EnhancedFor {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i : arr) {
System.out.println(i);
}
Collection c = new ArrayList();
c.add(new String("aaa"));
c.add(new String("bbb"));
c.add(new String("ccc"));
for (Object o : c) {
System.out.println(o);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/IteratorTest.java
================================================
package com.basic.chapter0600;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Iterator 测试
*
* @author MarkShen
* @since 20191210
*/
public class IteratorTest {
public static void main(String[] args) {
// List 有序,可以重复
List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
for (Iterator it = list.iterator(); it.hasNext(); ) {
if ("d".equals(it.next())) {
it.remove();
// list.remove("d"); // 会抛出 java.util.ConcurrentModificationException 异常
}
}
for (String str : list) {
System.out.println(str);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/SetTest.java
================================================
package com.basic.chapter0600;
import java.util.HashSet;
import java.util.Set;
/**
* Set:无序,不可重复
*
* @author MarkShen
* @since 20191210
*/
public class SetTest {
public static void main(String[] args) {
Set set = new HashSet<>();
set.add("a");
set.add("a");
set.add("b");
for (String str : set) {
System.out.println(str);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/TestArgsWords.java
================================================
package com.basic.chapter0600;
import java.util.*;
/**
* 参数中每个单词出现的次数
* auto-boxing
* auto-unboxing
*
* @author MarkShen
* @since 20191221
*/
public class TestArgsWords {
// private static final Integer ONE = new Integer(1);
private static final int ONE = 1;
public static void main(String args[]) {
Map m = new HashMap();
for (int i = 0; i < args.length; i++) {
//Integer freq = (Integer) m.get(args[i]);
int freq = (Integer) m.get(args[i]) == null ? 0 : (Integer) m.get(args[i]);
//m.put(args[i],(freq == null? ONE : new Integer(freq.intValue() + 1)));
m.put(args[i], freq == 0 ? ONE : freq + 1);
}
System.out.println(m.size() + " distinct words detected:");
System.out.println(m);
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/TestArgsWords2.java
================================================
package com.basic.chapter0600;
import java.util.*;
public class TestArgsWords2 {
private static final int ONE = 1;
public static void main(String args[]) {
Map m = new HashMap();
for (int i = 0; i < args.length; i++) {
if (!m.containsKey(args[i])) {
m.put(args[i], ONE);
} else {
int freq = m.get(args[i]);
m.put(args[i], freq + 1);
}
}
System.out.println(m.size() + " distinct words detected:");
System.out.println(m);
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator> it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry entry : m.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/TestMap.java
================================================
package com.basic.chapter0600;
import java.util.*;
/**
* key-value
* Auto boxing unboxing
* Java 自动打包,解包对性能的影响
* https://www.cnblogs.com/kakaku/articles/1320191.html
*
* @author MarkShen
* @since 20191211
*/
public class TestMap {
public static void main(String args[]) {
Map m1 = new HashMap();
Map m2 = new TreeMap();
//m1.put("one",new Integer(1));
m1.put("one", 1);
//m1.put("two",new Integer(2));
m1.put("two", 2);
//m1.put("three",new Integer(3));
m1.put("three", 3);
//m2.put("A",new Integer(1));
m2.put("A", 1);
//m2.put("B",new Integer(2));
m2.put("B", 2);
System.out.println(m1.size());
System.out.println(m1.containsKey("one"));
System.out.println
//(m2.containsValue(new Integer(1)));
(m2.containsValue(1));
if (m1.containsKey("two")) {
//int i = ((Integer)m1.get("two")).intValue();
int i = (Integer) m1.get("two");
System.out.println(i);
}
Map m3 = new HashMap(m1);
m3.putAll(m2);
System.out.println(m3);
}
}
================================================
FILE: src/main/java/com/basic/chapter0600/TestMap2.java
================================================
package com.basic.chapter0600;
import java.util.*;
/**
* 两个类如果equals,那么他们之间的hashcode必须一样
*
* 多读Map接口对应的API, JavaDoc
*/
public class TestMap2 {
public static void main(String args[]) {
Map m1 = new HashMap();
m1.put("one", 1);
m1.put("two", 2);
m1.put("three", 3);
System.out.println(m1.size());
System.out.println(m1.containsKey("one"));
if (m1.containsKey("two")) {
// int i = ((Integer)m1.get("two")).intValue();
int i = m1.get("two");
System.out.println(i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/FileCopy.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
int b = 0;
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("d:/share/java/HelloWorld.java");
out = new FileWriter("d:/share/java/io/HW.java");
while ((b = in.read()) != -1) {
out.write(b);
}
out.close();
in.close();
} catch (FileNotFoundException e2) {
e2.printStackTrace();
System.exit(-1);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
System.out.println("success");
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/HelloWorld.java
================================================
package com.basic.chapter0700;
/**
* java.io.*;
* io包裝的类
* 流的分类:
* 方向(站在程序的角度):输入流,输出流
* 处理数据单位:字节(1 byte)流,字符(2 bytes)流
* 功能:节点流,处理流
*
* 一定要多差Java API
*
* @author MarkShen
* @since 20191221
*/
public class HelloWorld {
static int j = 9;
public static void main(String[] asdfasf) {
System.out.println("HW");
System.out.println(123);
System.out.println(j);
int i = 8;
}
public static void m() {
}
}
class TT {
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestBufferStream1.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestBufferStream1 {
public static void main(String[] args) {
try {
FileInputStream fis =
new FileInputStream("d:\\share\\java\\HelloWorld.java");
BufferedInputStream bis =
new BufferedInputStream(fis);
int c = 0;
System.out.println(bis.read());
System.out.println(bis.read());
bis.mark(100);
for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
System.out.print((char) c + " ");
}
System.out.println();
bis.reset();
for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
System.out.print((char) c + " ");
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestBufferStream2.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestBufferStream2 {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\share\\java\\dat2.txt"));
BufferedReader br = new BufferedReader(new FileReader("d:\\share\\java\\dat2.txt"));
String s = null;
for (int i = 1; i <= 100; i++) {
s = String.valueOf(Math.random());
bw.write(s);
bw.newLine();
}
bw.flush();
while ((s = br.readLine()) != null) {
System.out.println(s);
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestDataStream.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestDataStream {
public static void main(String[] args) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeDouble(Math.random());
dos.writeBoolean(true);
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
System.out.println(bais.available());
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
dos.close();
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestFileInputStream.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestFileInputStream {
public static void main(String[] args) {
int b = 0;
FileInputStream in = null;
try {
in = new FileInputStream("d:\\share\\java\\io\\TestFileInputStream.java");
} catch (FileNotFoundException e) {
System.out.println("找不到指定的文件");
System.exit(-1);
}
try {
long num = 0;
while ((b = in.read()) != -1) {
System.out.print((char) b);
num++;
}
in.close();
System.out.println();
System.out.println("共读取了 " + num + " 个字节");
} catch (IOException e1) {
System.out.println("文件读取错误");
System.exit(-1);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestFileOutputStream.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestFileOutputStream {
public static void main(String[] args) {
int b = 0;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("d:/share/java/HelloWorld.java");
out = new FileOutputStream("d:/share/java/io/HW.java");
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
} catch (FileNotFoundException e2) {
System.out.println("找不到指定文件");
System.exit(-1);
} catch (IOException e1) {
System.out.println("文件复制错误");
System.exit(-1);
}
System.out.println("文件已复制");
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestFileReader.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestFileReader {
public static void main(String[] args) {
FileReader fr = null;
int c = 0;
try {
fr = new FileReader("d:\\share\\java\\io\\TestFileReader.java");
int ln = 0;
while ((c = fr.read()) != -1) {
//char ch = (char) fr.read();
System.out.print((char) c);
//if (++ln >= 100) { System.out.println(); ln = 0;}
}
fr.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定文件");
} catch (IOException e) {
System.out.println("文件读取错误");
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestFileWriter.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestFileWriter {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("d:\\bak\\unicode.dat");
for (int c = 0; c <= 50000; c++) {
fw.write(c);
}
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
System.out.println("文件写入错误");
System.exit(-1);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestFileWriter2.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestFileWriter2 {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("d:/java/io/TestFileWriter2.java");
FileWriter fw = new FileWriter("d:/java/io/TestFileWriter2.bak");
int b;
while ((b = fr.read()) != -1) {
fw.write(b);
}
fr.close();
fw.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestObjectIO.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestObjectIO {
public static void main(String args[]) throws Exception {
T t = new T();
t.k = 8;
FileOutputStream fos = new FileOutputStream("d:/share/java/io/testobjectio.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(t);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("d:/share/java/io/testobjectio.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
T tReaded = (T) ois.readObject();
System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);
}
}
class T implements Serializable {
int i = 10;
int j = 9;
double d = 2.3;
transient int k = 15;
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestPrintStream1.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestPrintStream1 {
public static void main(String[] args) {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream("d:\\bak\\log.dat");
ps = new PrintStream(fos);
} catch (IOException e) {
e.printStackTrace();
}
if (ps != null) {
System.setOut(ps);
}
int ln = 0;
for (char c = 0; c <= 60000; c++) {
System.out.print(c + " ");
if (ln++ >= 100) {
System.out.println();
ln = 0;
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestPrintStream2.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestPrintStream2 {
public static void main(String[] args) {
String filename = args[0];
if (filename != null) {
list(filename, System.out);
}
}
public static void list(String f, PrintStream fs) {
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
fs.println(s);
}
br.close();
} catch (IOException e) {
fs.println(e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestPrintStream3.java
================================================
package com.basic.chapter0700;
import java.util.*;
import java.io.*;
public class TestPrintStream3 {
public static void main(String[] args) {
String s = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
FileWriter fw = new FileWriter("d:\\bak\\logfile.log", true); //Log4J
PrintWriter log = new PrintWriter(fw);
while ((s = br.readLine()) != null) {
if (s.equalsIgnoreCase("exit")) break;
System.out.println(s.toUpperCase());
log.println("-----");
log.println(s.toUpperCase());
log.flush();
}
log.println("===" + new Date() + "===");
log.flush();
log.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestTransForm1.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestTransForm1 {
public static void main(String[] args) {
try {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\bak\\char.txt"));
osw.write("mircosoftibmsunapplehp");
System.out.println(osw.getEncoding());
osw.close();
osw = new OutputStreamWriter(new FileOutputStream("d:\\bak\\char.txt", true), "ISO8859_1"); // latin-1
osw.write("mircosoftibmsunapplehp");
System.out.println(osw.getEncoding());
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0700/TestTransForm2.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TestTransForm2 {
public static void main(String args[]) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = null;
try {
s = br.readLine();
while (s != null) {
if (s.equalsIgnoreCase("exit")) break;
System.out.println(s.toUpperCase());
s = br.readLine();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} // 阻塞
================================================
FILE: src/main/java/com/basic/chapter0700/TreeDir.java
================================================
package com.basic.chapter0700;
import java.io.*;
public class TreeDir {
public static void main(String[] args) {
listF(new File("d:/test"), 0);
}
public static void listF(File f, int level) {
String preStr = "";
for (int i = 0; i < level; i++) preStr += " ";
System.out.println(preStr + f.getName());
if (f.isDirectory()) {
File[] files = f.listFiles();
for (File cf : files) listF(cf, level + 1);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/111.txt
================================================
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
================================================
FILE: src/main/java/com/basic/chapter0800/ProducerConsumer.java
================================================
package com.basic.chapter0800;
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
}
}
class WoTou {
int id;
WoTou(int id) {
this.id = id;
}
public String toString() {
return "WoTou : " + id;
}
}
class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[6];
public synchronized void push(WoTou wt) {
while(index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll(); // 叫醒所有在该对象上的线程
arrWT[index] = wt;
index ++;
}
public synchronized WoTou pop() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return arrWT[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了:" + wt);
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/ProducerConsumer2.java
================================================
package com.basic.chapter0800;
public class ProducerConsumer2 {
public static void main(String args[]) {
SyncStack2 stack = new SyncStack2();
Runnable p = new Producer2(stack);
Runnable c = new Consumer2(stack);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class SyncStack2 {
private int index = 0;
private char[] data = new char[6];
public synchronized void push(char c) {
if (index == data.length) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
this.notify();
data[index] = c;
index++;
}
public synchronized char pop() {
if (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
this.notify();
index--;
return data[index];
}
}
class Producer2 implements Runnable {
SyncStack2 stack;
public Producer2(SyncStack2 s) {
stack = s;
}
public void run() {
for (int i = 0; i < 20; i++) {
char c = (char) (Math.random() * 26 + 'A');
stack.push(c);
System.out.println("produced: " + c);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
}
}
class Consumer2 implements Runnable {
SyncStack2 stack;
public Consumer2(SyncStack2 s) {
stack = s;
}
public void run() {
for (int i = 0; i < 20; i++) {
char c = stack.pop();
System.out.println("consumed: " + c);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/RecursiveFile.java
================================================
package com.basic.chapter0800;
public class RecursiveFile {
public static void main(String[] args) {
}
public static void f() {
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/T.java
================================================
package com.basic.chapter0800;
public class T {
public static void main(String[] args) {
m1();
}
public static void m1() {
m2();
m3();
}
public static void m2() {
}
public static void m3() {
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TT.java
================================================
package com.basic.chapter0800;
public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception {
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/Test.java
================================================
package com.basic.chapter0800;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("111.txt");
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 1; i <= 25; i++) {
bw.write(i + " ");
if (i % 5 == 0) bw.newLine();
}
bw.flush();
bw.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestDeadLock.java
================================================
package com.basic.chapter0800;
public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println("flag=" + flag);
if(flag == 1) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1");
}
}
}
if(flag == 0) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestInterrupt.java
================================================
package com.basic.chapter0800;
import java.util.*;
public class TestInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
thread.interrupt();
}
}
class MyThread extends Thread {
boolean flag = true;
public void run() {
while (flag) {
System.out.println("===" + new Date() + "===");
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
/*
public void run() {
while (true) {
String temp = new Date().toString();
String t = temp.substring(11, temp.indexOf('C'));
t = t.trim();
String[] time = t.split(":");
if (time.length == 3) {
System.out.println(time[0] + time[1] + time[2]);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
return;
}
}
}
}
*/
================================================
FILE: src/main/java/com/basic/chapter0800/TestJoin.java
================================================
package com.basic.chapter0800;
public class TestJoin {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("abcde");
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
}
for (int i = 1; i <= 10; i++) {
System.out.println("i am main thread");
}
}
}
class MyThread2 extends Thread {
MyThread2(String s) {
super(s);
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("i am " + getName());
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestPriority.java
================================================
package com.basic.chapter0800;
public class TestPriority {
public static void main(String[] args) {
Thread t1 = new Thread(new T1());
Thread t2 = new Thread(new T2());
t1.setPriority(Thread.NORM_PRIORITY + 3);
t1.start();
t2.start();
}
}
class T1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("T1: " + i);
}
}
}
class T2 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("------T2: " + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestSync.java
================================================
package com.basic.chapter0800;
public class TestSync implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}
class Timer {
private static int num = 0;
public synchronized void add(String name) {
// synchronized (this) {
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(name + ", " + num);
// }
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread1.java
================================================
package com.basic.chapter0800;
public class TestThread1 {
public static void main(String args[]) {
Runner1 r = new Runner1();
r.start();
//r.run();
//Thread t = new Thread(r);
//t.start();
for (int i = 0; i < 100; i++) {
System.out.println("Main Thread:------" + i);
}
}
}
//class Runner1 implements Runnable {
class Runner1 extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("Runner1 :" + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread2.java
================================================
package com.basic.chapter0800;
public class TestThread2 {
public static void main(String args[]) {
Runner2 r = new Runner2();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
class Runner2 implements Runnable {
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("No. " + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread3.java
================================================
package com.basic.chapter0800;
public class TestThread3 {
public static void main(String args[]) {
Runner3 r = new Runner3();
Thread t = new Thread(r);
t.start();
}
}
class Runner3 implements Runnable {
public void run() {
for (int i = 0; i < 30; i++) {
if (i % 10 == 0 && i != 0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
System.out.println("No. " + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread4.java
================================================
package com.basic.chapter0800;
public class TestThread4 {
public static void main(String args[]) {
Runner4 r = new Runner4();
Thread t = new Thread(r);
t.start();
for (int i = 0; i < 100000; i++) {
if (i % 10000 == 0 & i > 0)
System.out.println("in thread main i=" + i);
}
System.out.println("Thread main is over");
r.shutDown();
//t.stop();
}
}
class Runner4 implements Runnable {
private boolean flag = true;
public void run() {
int i = 0;
while (flag == true) {
System.out.print(" " + i++);
}
}
public void shutDown() {
flag = false;
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread5.java
================================================
package com.basic.chapter0800;
public class TestThread5 {
public static void main(String args[]){
Runner5 r = new Runner5();
Thread t = new Thread(r);
t.start();
try{
t.join();
}catch(InterruptedException e){
}
for(int i=0;i<50;i++){
System.out.println("main thread:" + i);
}
}
}
class Runner5 implements Runnable {
public void run() {
for(int i=0;i<50;i++) {
System.out.println("SubThread: " + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestThread6.java
================================================
package com.basic.chapter0800;
public class TestThread6 {
public static void main(String args[]) {
Thread t = new Runner6();
t.start();
for (int i = 0; i < 50; i++) {
System.out.println("MainThread: " + i);
}
}
}
class Runner6 extends Thread {
public void run() {
System.out.println(Thread.currentThread().isAlive());
for (int i = 0; i < 50; i++) {
System.out.println("SubThread: " + i);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0800/TestYield.java
================================================
package com.basic.chapter0800;
public class TestYield {
public static void main(String[] args) {
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start();
t2.start();
}
}
class MyThread3 extends Thread {
MyThread3(String s) {
super(s);
}
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(getName() + ": " + i);
if (i % 10 == 0) {
yield();
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chapter0901TestUDPClient.java
================================================
package com.basic.chapter0900;
import java.net.*;
public class Chapter0901TestUDPClient {
public static void main(String args[]) throws Exception {
byte[] buf = "Hello".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chapter0901TestUDPServer.java
================================================
package com.basic.chapter0900;
import java.net.*;
public class Chapter0901TestUDPServer {
public static void main(String args[]) throws Exception {
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while (true) {
ds.receive(dp);
System.out.println(new String(buf, 0, dp.getLength()));
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat03/ChatClient.java
================================================
package com.basic.chapter0900.Chat.Chat03;
import java.io.*;
import java.net.*;
public class ChatClient {
Socket s = null;
public ChatClient() throws Exception {
s = new Socket("127.0.0.1", 8888);
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat03/ChatServer.java
================================================
package com.basic.chapter0900.Chat.Chat03;
import java.net.*;
import java.util.*;
import java.io.*;
public class ChatServer {
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
}
}
class ClientConn implements Runnable {
Socket s = null;
public ClientConn(Socket s) {
this.s = s;
(new Thread(this)).start();
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
System.out.println(str);
str = dis.readUTF();
}
s.close();
cClient.remove(this);
} catch (IOException e) {
System.out.println("client quit");
try {
if (s != null)
s.close();
cClient.remove(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat05/ChatClient.java
================================================
package com.basic.chapter0900.Chat.Chat05;
import java.io.*;
import java.net.*;
public class ChatClient {
Socket s = null;
public ChatClient() throws Exception {
s = new Socket("127.0.0.1", 8888);
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null) return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
System.out.println(str);
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat05/ChatServer.java
================================================
package com.basic.chapter0900.Chat.Chat05;
import java.net.*;
import java.util.*;
import java.io.*;
public class ChatServer {
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
}
}
class ClientConn implements Runnable {
Socket s = null;
public ClientConn(Socket s) {
this.s = s;
(new Thread(this)).start();
}
public void send(String str) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
System.out.println(str);
for (Iterator it = cClient.iterator(); it.hasNext(); ) {
ClientConn cc = (ClientConn) it.next();
if (this != cc) {
cc.send(str);
}
}
str = dis.readUTF();
//send(str);
}
s.close();
cClient.remove(this);
} catch (IOException e) {
System.out.println("client quit");
try {
if (s != null)
s.close();
cClient.remove(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat07/ChatClient.java
================================================
package com.basic.chapter0900.Chat.Chat07;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient extends Frame {
TextArea ta = new TextArea();
TextField tf = new TextField();
public void launchFrame() throws Exception {
this.add(ta, BorderLayout.CENTER);
this.add(tf, BorderLayout.SOUTH);
tf.addActionListener((ActionEvent ae) -> {
try {
String sSend = tf.getText();
if (sSend.trim().length() == 0) return;
ChatClient.this.send(sSend);
tf.setText("");
ta.append(sSend + "\n");
} catch (Exception e) {
e.printStackTrace();
}
});
setBounds(300, 300, 300, 400);
setVisible(true);
tf.requestFocus();
}
Socket s = null;
public ChatClient() throws Exception {
s = new Socket("127.0.0.1", 8888);
launchFrame();
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null) return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
// System.out.println(str);
ChatClient.this.ta.append(str + "\n");
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat07/ChatServer.java
================================================
package com.basic.chapter0900.Chat.Chat07;
import java.net.*;
import java.util.*;
import java.io.*;
public class ChatServer {
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
}
}
class ClientConn implements Runnable {
Socket s = null;
public ClientConn(Socket s) {
this.s = s;
(new Thread(this)).start();
}
public void send(String str) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
System.out.println(str);
for (Iterator it = cClient.iterator(); it.hasNext(); ) {
ClientConn cc = (ClientConn) it.next();
if (this != cc) {
cc.send(str);
}
}
str = dis.readUTF();
//send(str);
}
s.close();
cClient.remove(this);
} catch (IOException e) {
System.out.println("client quit");
try {
if (s != null)
s.close();
cClient.remove(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat10/ChatClient.java
================================================
package com.basic.chapter0900.Chat.Chat10;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient extends Frame {
TextArea ta = new TextArea();
TextField tf = new TextField();
public void launchFrame() throws Exception {
this.add(ta, BorderLayout.CENTER);
this.add(tf, BorderLayout.SOUTH);
tf.addActionListener((ActionEvent ae) -> {
try {
String sSend = tf.getText();
if (sSend.trim().length() == 0) return;
ChatClient.this.send(sSend);
tf.setText("");
ta.append(sSend + "\n");
} catch (Exception e) {
e.printStackTrace();
}
});
this.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setBounds(300, 300, 300, 400);
setVisible(true);
tf.requestFocus();
}
Socket s = null;
public ChatClient() throws Exception {
s = new Socket("127.0.0.1", 8888);
launchFrame();
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null) return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
//System.out.println(str);
ChatClient.this.ta.append(str + "\n");
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/Chat/Chat10/ChatServer.java
================================================
package com.basic.chapter0900.Chat.Chat10;
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ChatServer extends Frame {
TextArea ta = new TextArea();
public void launchFrame() {
add(ta, BorderLayout.CENTER);
setBounds(0, 0, 200, 300);
this.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
launchFrame();
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
}
}
class ClientConn implements Runnable {
Socket s = null;
public ClientConn(Socket s) {
this.s = s;
(new Thread(this)).start();
}
public void send(String str) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void dispose() {
try {
if (s != null) s.close();
cClient.remove(this);
ta.append("A client out! \n");
ta.append("CLIENT-COUNT: " + cClient.size() + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
System.out.println(str);
for (Iterator it = cClient.iterator(); it.hasNext(); ) {
ClientConn cc = (ClientConn) it.next();
if (this != cc) {
cc.send(str);
}
}
str = dis.readUTF();
//send(str);
}
this.dispose();
} catch (Exception e) {
System.out.println("client quit");
this.dispose();
}
}
}
public static void main(String[] args) throws Exception {
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TCPClient.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 6666);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Thread.sleep(30000);
dos.writeUTF("hello server!");
dos.flush();
dos.close();
s.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TCPServer.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
while(true) {
Socket s = ss.accept();
System.out.println("a client connect!");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TalkClient.java
================================================
package com.basic.chapter0900;
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try {
Socket socket = new Socket("127.0.0.1", 4700);
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
PrintWriter os = new PrintWriter(socket.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String readline;
readline = sin.readLine();
while (!readline.equals("bye")) {
os.println(readline);
os.flush();
System.out.println("Client:" + readline);
System.out.println("Server:" + is.readLine());
readline = sin.readLine();
}
os.close();
is.close();
socket.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TalkServer.java
================================================
package com.basic.chapter0900;
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer {
public static void main(String args[]) {
try {
ServerSocket server = null;
try {
server = new ServerSocket(4700);
} catch (Exception e) {
System.out.println("can not listen to:" + e);
}
Socket socket = null;
try {
socket = server.accept();
} catch (Exception e) {
System.out.println("Error:" + e);
}
String line;
BufferedReader is = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:" + is.readLine());
line = sin.readLine();
while (!line.equals("bye")) {
os.println(line);
os.flush();
System.out.println("Server:" + line);
System.out.println("Client:" + is.readLine());
line = sin.readLine();
}
is.close();
os.close();
socket.close();
server.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestClient.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TestClient {
public static void main(String args[]) {
try {
Socket s1 = new Socket("127.0.0.1", 8888);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s1.close();
} catch (ConnectException connExc) {
connExc.printStackTrace();
System.err.println("throw connection exception...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestServer.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TestServer {
public static void main(String args[]) {
try {
ServerSocket s = new ServerSocket(8888);
while (true) {
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello," + s1.getInetAddress() +
"port#" + s1.getPort() + " bye-bye!");
dos.close();
s1.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("异常信息:" + e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestSockClient.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TestSockClient {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try {
Socket socket = new Socket("localhost", 5888);
is = socket.getInputStream();
os = socket.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hey");
String s = null;
if ((s = dis.readUTF()) != null) ;
System.out.println(s);
dos.close();
dis.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestSockServer.java
================================================
package com.basic.chapter0900;
import java.io.*;
import java.net.*;
public class TestSockServer {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
ServerSocket ss = new ServerSocket(5888);
Socket socket = ss.accept();
in = socket.getInputStream();
out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
String s = null;
if ((s = dis.readUTF()) != null) {
System.out.println(s);
System.out.println("from: " + socket.getInetAddress());
System.out.println("Port: " + socket.getPort());
}
dos.writeUTF("你好,世界!");
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestUDPClient.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TestUDPClient {
public static void main(String args[]) throws Exception {
long n = 10000L;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(n);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
DatagramPacket dp = new DatagramPacket(buf, buf.length,
new InetSocketAddress("127.0.0.1", 5678)
);
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/TestUDPServer.java
================================================
package com.basic.chapter0900;
import java.net.*;
import java.io.*;
public class TestUDPServer {
public static void main(String args[]) throws Exception {
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while (true) {
ds.receive(dp);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readLong());
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/zerocopy/traditonal/TraditionalClient.java
================================================
package com.basic.chapter0900.zerocopy.traditonal;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class TraditionalClient {
public static void main(String[] args) {
int port = 2000;
String server = "localhost";
Socket socket = null;
String lineToBeSent;
DataOutputStream output = null;
FileInputStream inputStream = null;
int ERROR = 1;
// connect to server
try {
socket = new Socket(server, port);
System.out.println("Connected with server " + socket.getInetAddress() + ":" + socket.getPort());
} catch (UnknownHostException e) {
System.out.println(e);
System.exit(ERROR);
} catch (IOException e) {
System.out.println(e);
System.exit(ERROR);
}
try {
String fname = "D:\\soft\\julia-1.4.2-win64.exe";
inputStream = new FileInputStream(fname);
output = new DataOutputStream(socket.getOutputStream());
long start = System.currentTimeMillis();
byte[] b = new byte[4096];
long read = 0, total = 0;
while ((read = inputStream.read(b)) >= 0) {
total = total + read;
output.write(b);
}
System.out.println("bytes send--" + total + " and totaltime--" + (System.currentTimeMillis() - start));
} catch (IOException e) {
System.out.println(e);
}
try {
output.close();
socket.close();
inputStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/zerocopy/traditonal/TraditionalServer.java
================================================
package com.basic.chapter0900.zerocopy.traditonal;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TraditionalServer {
public static void main(String args[]) {
int port = 2000;
ServerSocket server_socket;
DataInputStream input;
try {
server_socket = new ServerSocket(port);
System.out.println("Server waiting for client on port " + server_socket.getLocalPort());
// server infinite loop
while (true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
input = new DataInputStream(socket.getInputStream());
// print received data
try {
byte[] byteArray = new byte[4096];
while (true) {
int nread = input.read(byteArray, 0, 4096);
if (0 == nread)
break;
}
} catch (IOException e) {
System.out.println(e);
}
// connection closed by client
try {
socket.close();
System.out.println("Connection closed by client");
} catch (IOException e) {
System.out.println(e);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/zerocopy/transfer/TransferToClient.java
================================================
package com.basic.chapter0900.zerocopy.transfer;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
public class TransferToClient {
public static void main(String[] args) throws IOException {
TransferToClient sfc = new TransferToClient();
sfc.testSendfile();
}
public void testSendfile() throws IOException {
String host = "localhost";
int port = 9026;
SocketAddress sad = new InetSocketAddress(host, port);
SocketChannel sc = SocketChannel.open();
sc.connect(sad);
sc.configureBlocking(true);
String fname = "D:\\soft\\julia-1.4.2-win64.exe";
long fsize = 183678375L, sendzise = 4094;
// FileProposerExample.stuffFile(fname, fsize);
FileChannel fc = new FileInputStream(fname).getChannel();
long start = System.currentTimeMillis();
long nsent = 0, curnset = 0;
curnset = fc.transferTo(0, fsize, sc);
System.out.println(
"total bytes transferred--" + curnset + " and time taken in MS--" + (System.currentTimeMillis() - start));
fc.close();
}
}
================================================
FILE: src/main/java/com/basic/chapter0900/zerocopy/transfer/TransferToServer.java
================================================
package com.basic.chapter0900.zerocopy.transfer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class TransferToServer {
ServerSocketChannel listener = null;
protected void mySetup() {
InetSocketAddress listenAddr = new InetSocketAddress(9026);
try {
listener = ServerSocketChannel.open();
ServerSocket ss = listener.socket();
ss.setReuseAddress(true);
ss.bind(listenAddr);
System.out.println("Listening on port : " + listenAddr.toString());
} catch (IOException e) {
System.out.println("Failed to bind, is port : " + listenAddr.toString() + " already in use ? Error Msg : "
+ e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
TransferToServer dns = new TransferToServer();
dns.mySetup();
dns.readData();
}
private void readData() {
ByteBuffer dst = ByteBuffer.allocate(4096);
try {
while (true) {
SocketChannel conn = listener.accept();
System.out.println("Accepted : " + conn);
conn.configureBlocking(true);
int nread = 0;
while (nread != -1) {
try {
nread = conn.read(dst);
} catch (IOException e) {
e.printStackTrace();
conn.socket().close();
nread = -1;
}
dst.rewind();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/AWTDrawing.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class AWTDrawing {
private Frame f = new Frame(" Hello Out There!");
private Panel p = new Panel();
public void launchFrame() {
f.add(p);
f.setSize( 170,170);
f.setBackground( Color.blue);
f.setVisible( true);
p.setForeground(Color.red);
Graphics g = p.getGraphics();
g.drawArc(30,40,50,60,70,80);
g.fillArc(30,40,50,60,70,80);
}
public static void main( String args[]) {
AWTDrawing guiWindow = new AWTDrawing();
guiWindow.launchFrame();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/AWTDrawing2.java
================================================
package com.basic.chapter1000;
import java.awt.*;
class SubPanel extends Panel{
public void paint(Graphics g){
g.drawString("this is a drawing test!",20,20);
g.drawLine(30,60,100,120);
g.draw3DRect(60,50,70,30,false);
}
}
public class AWTDrawing2 {
private Frame f = new Frame(" Hello Out There!");
private SubPanel p = new SubPanel();
public void launchFrame() {
f.add(p);
f.setSize(170,170);
f.setBackground( new Color(89,145,145));
f.setVisible( true);
}
public static void main( String args[]) {
AWTDrawing2 guiWindow = new AWTDrawing2();
guiWindow.launchFrame();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/CenterPanel.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class CenterPanel {
public static void main(String args[]) {
new MyFrame3(300, 300, 400, 300, Color.BLUE);
}
}
class MyFrame3 extends Frame {
private Panel p;
MyFrame3(int x, int y, int w, int h, Color c) {
super("FrameWithPanel");
setLayout(null);
setBounds(x, y, w, h);
setBackground(c);
p = new Panel(null);
p.setBounds(w / 4, h / 4, w / 2, h / 2);
p.setBackground(Color.YELLOW);
add(p);
setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/MyMouseAdapter.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class MyMouseAdapter {
public static void main(String args[]) {
new MyFrame("drawing...");
}
}
class MyFrame extends Frame {
ArrayList points = null;
MyFrame(String s) {
super(s);
points = new ArrayList();
setLayout(null);
setBounds(300, 300, 400, 300);
this.setBackground(new Color(204, 204, 255));
setVisible(true);
this.addMouseListener(new Monitor());
}
public void paint(Graphics g) {
Iterator i = points.iterator();
while (i.hasNext()) {
Point p = (Point) i.next();
g.setColor(Color.BLUE);
g.fillOval(p.x, p.y, 10, 10);
}
}
public void addPoint(Point p) {
points.add(p);
}
}
class Monitor extends MouseAdapter {
public void mousePressed(MouseEvent e) {
MyFrame f = (MyFrame) e.getSource();
f.addPoint(new Point(e.getX(), e.getY()));
f.repaint();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/MyMouseAdapterGeneric.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class MyMouseAdapterGeneric {
public static void main(String args[]) {
new MyFrame992("drawing...");
}
}
class MyFrame992 extends Frame {
ArrayList points = null;
MyFrame992(String s) {
super(s);
points = new ArrayList();
setLayout(null);
setBounds(300, 300, 400, 300);
this.setBackground(new Color(204, 204, 255));
setVisible(true);
this.addMouseListener(new Monitor2());
}
public void paint(Graphics g) {
Iterator i = points.iterator();
while (i.hasNext()) {
Point p = i.next();
g.setColor(Color.BLUE);
g.fillOval(p.x, p.y, 10, 10);
}
}
public void addPoint(Point p) {
points.add(p);
}
}
class Monitor2 extends MouseAdapter {
public void mousePressed(MouseEvent e) {
MyFrame992 f = (MyFrame992) e.getSource();
f.addPoint(new Point(e.getX(), e.getY()));
f.repaint();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/NestedContainer.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class NestedContainer {
public static void main(String args[]) {
Frame f = new Frame("NestedContainer");
Button b0 = new Button("display Area");
Panel p = new Panel();
p.setLayout(new GridLayout(2, 2));
Button b1 = new Button("1");
Button b2 = new Button("2");
Button b3 = new Button("3");
Button b4 = new Button("4");
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
f.add(b0, "North");
f.add(p, "Center");
f.pack();
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TFActionEvent.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TFActionEvent {
/**
* @param args
*/
public static void main(String[] args) {
new TFFrame();
}
}
class TFFrame extends Frame {
TFFrame() {
TextField tf = new TextField();
add(tf);
tf.addActionListener(new TFActionListener());
pack();
setVisible(true);
}
}
class TFActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
TextField tf = (TextField) e.getSource();
System.out.println(tf.getText());
//tf.setText("");
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TFMath.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String[] args) {
new TFFrame3().launchFrame();
}
}
class TFFrame3 extends Frame {
TextField num1, num2, num3;
public void launchFrame() {
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(15);
Label lblPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor());
setLayout(new FlowLayout());
add(num1);
add(lblPlus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
private class MyMonitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText("" + (n1 + n2));
}
}
}
//class MyMonitor implements ActionListener {
//TextField num1, num2, num3;
/*
public MyMonitor(TextField num1, TextField num2, TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
*/
/*
TFFrame tf = null;
public MyMonitor(TFFrame tf) {
this.tf = tf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(tf.num1.getText());
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText("" + (n1+n2));
}
}
*/
================================================
FILE: src/main/java/com/basic/chapter1000/TFMathTest.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TFMathTest extends Frame {
TextField num1;
TextField num2;
TextField sum;
/**
* @param args
*/
public static void main(String[] args) {
new TFMathTest().launchFrame();
}
public void launchFrame() {
num1 = new TextField();
num2 = new TextField();
sum = new TextField();
num1.setColumns(10);
num2.setColumns(10);
sum.setColumns(15);
setLayout(new FlowLayout());
//setSize(500, 30);
Label lblPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyListener2(this));
add(num1);
add(lblPlus);
add(num2);
add(btnEqual);
add(sum);
pack();
setVisible(true);
}
}
class MyListener2 implements ActionListener {
private TFMathTest tfmt;
public MyListener2(TFMathTest tfmt) {
this.tfmt = tfmt;
}
public void actionPerformed(ActionEvent e) {
String s1 = tfmt.num1.getText();
String s2 = tfmt.num2.getText();
int i1 = Integer.parseInt(s1);
int i2 = Integer.parseInt(s2);
tfmt.sum.setText(String.valueOf(i1 + i2));
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TFMathTest2.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TFMathTest2 extends Frame {
TextField num1;
TextField num2;
TextField sum;
/**
* @param args
*/
public static void main(String[] args) {
new TFMathTest2().launchFrame();
}
public void launchFrame() {
num1 = new TextField();
num2 = new TextField();
sum = new TextField();
num1.setColumns(10);
num2.setColumns(10);
sum.setColumns(15);
setLayout(new FlowLayout());
//setSize(500, 30);
Label lblPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyListener(this));
add(num1);
add(lblPlus);
add(num2);
add(btnEqual);
add(sum);
pack();
setVisible(true);
}
}
class MyListener implements ActionListener {
//private TFMathTest2 tfmt;
private TextField num1, num2, sum;
public MyListener(TFMathTest2 tfmt) {
//this.tfmt = tfmt;
/*
this.num1 = tfmt.num1;
this.num2 = tfmt.num2;
this.sum = tfmt.sum;
*/
this(tfmt.num1, tfmt.num2, tfmt.sum);
}
public MyListener(TextField num1, TextField num2, TextField sum) {
this.num1 = num1;
this.num2 = num2;
this.sum = sum;
}
public void actionPerformed(ActionEvent e) {
String s1 = num1.getText();
String s2 = num2.getText();
int i1 = Integer.parseInt(s1);
int i2 = Integer.parseInt(s2);
sum.setText(String.valueOf(i1 + i2));
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TFPassword.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TFPassword {
/**
* @param args
*/
public static void main(String[] args) {
new TFFrame2();
}
}
class TFFrame2 extends Frame {
TFFrame2() {
TextField tf = new TextField();
add(tf);
tf.addActionListener(new TFActionListener2());
tf.setEchoChar('*');
pack();
setVisible(true);
}
}
class TFActionListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
TextField tf = (TextField) e.getSource();
System.out.println(tf.getText());
tf.setText("");
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TenButtons.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TenButtons {
public static void main(String args[]) {
Frame f = new Frame("Java Frame");
f.setLayout(new GridLayout(2, 1));
f.setLocation(300, 400);
f.setSize(300, 200);
f.setBackground(new Color(204, 204, 255));
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new BorderLayout());
Panel p11 = new Panel(new GridLayout(2, 1));
Panel p21 = new Panel(new GridLayout(2, 2));
p1.add(new Button("BUTTON"), BorderLayout.WEST);
p1.add(new Button("BUTTON"), BorderLayout.EAST);
p11.add(new Button("BUTTON"));
p11.add(new Button("BUTTON"));
p1.add(p11, BorderLayout.CENTER);
p2.add(new Button("BUTTON"), BorderLayout.WEST);
p2.add(new Button("BUTTON"), BorderLayout.EAST);
for (int i = 1; i <= 4; i++) {
p21.add(new Button("BUTTON"));
}
p2.add(p21, BorderLayout.CENTER);
f.add(p1);
f.add(p2);
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/Test.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class Test {
public static void main(String args[]) {
Frame f = new Frame("Java Gui");
f.setLayout(null);
Button b = new Button("Button1");
f.add(b);
b.setLocation(47, 70);
b.setSize(60, 25);
f.setSize(150, 150);
f.setBackground(new Color(90, 145, 145, 200));
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestActionEvent.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent {
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b = new Button("Press Me!");
Monitor3 bh = new Monitor3();
b.addActionListener(bh);
f.add(b, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
class Monitor3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed");
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestActionEvent2.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent2 {
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b1 = new Button("Start");
Button b2 = new Button("Stop");
Monitor6 bh = new Monitor6();
b1.addActionListener(bh);
b2.addActionListener(bh);
b2.setActionCommand("game over");
f.add(b1, "North");
f.add(b2, "Center");
f.pack();
f.setVisible(true);
}
}
class Monitor6 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed," +
"the relative info is:\n " + e.getActionCommand());
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestAnonymous.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestAnonymous {
Frame f = new Frame("Test Anonymous");
TextField tf = new TextField(30);
public TestAnonymous() {
f.add(new Label("Mouse"), "North");
f.add(tf, "South");
f.addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
String s = "(" + e.getX() + "," + e.getY() + ")";
tf.setText(s);
}
public void mouseMoved(MouseEvent e) {
}
}
);
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String args[]) {
TestAnonymous t = new TestAnonymous();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestAnonymous2.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestAnonymous2 {
Frame f = new Frame("Test");
TextField tf = new TextField(10);
Button b1 = new Button("Start");
public TestAnonymous2() {
f.add(b1, "North");
f.add(tf, "South");
b1.addActionListener(new ActionListener() {
private int i;
public void actionPerformed(ActionEvent e) {
tf.setText(e.getActionCommand() + ++i);
}
});
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
new TestAnonymous2();
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestBorderLayout.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestBorderLayout {
public static void main(String args[]) {
Frame f;
f = new Frame("Border Layout");
Button bn = new Button("BN");
Button bs = new Button("BS");
Button bw = new Button("BW");
Button be = new Button("BE");
Button bc = new Button("BC");
f.add(bn, "North");
f.add(bs, "South");
f.add(bw, "West");
f.add(be, "East");
f.add(bc, "Center");
/*
f.add(bn, BorderLayout.NORTH);
f.add(bs, BorderLayout.SOUTH);
f.add(bw, BorderLayout.WEST);
f.add(be, BorderLayout.EAST);
f.add(bc, BorderLayout.CENTER);
*/
f.setSize(200, 200);
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestFlowLayout.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestFlowLayout {
public static void main(String args[]) {
Frame f = new Frame("Flow Layout");
Button button1 = new Button("Ok");
Button button2 = new Button("Open");
Button button3 = new Button("Close");
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(button1);
f.add(button2);
f.add(button3);
f.setSize(100, 100);
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestFlowLayout2.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestFlowLayout2 {
public static void main(String args[]) {
Frame f = new Frame("Java Frame");
FlowLayout l = new FlowLayout(FlowLayout.CENTER, 20, 40);
f.setLayout(l);
f.setLocation(300, 400);
f.setSize(300, 200);
f.setBackground(new Color(204, 204, 255));
for (int i = 1; i <= 7; i++) {
f.add(new Button("BUTTON"));
}
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestFrame.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestFrame {
public static void main( String args[]) {
Frame f = new Frame("My First Test");
f.setLocation(300, 300);
f.setSize( 170,100);
f.setBackground( Color.blue);
f.setResizable(false);
f.setVisible( true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestFrameWithPanel.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestFrameWithPanel {
public static void main(String args[]) {
Frame f = new Frame("MyTest Frame");
Panel pan = new Panel();
f.setSize(200, 200);
f.setBackground(Color.blue);
f.setLayout(null);
pan.setSize(100, 100);
pan.setBackground(Color.green);
f.add(pan);
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestGridLayout.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestGridLayout {
public static void main(String args[]) {
Frame f = new Frame("GridLayout Example");
Button b1 = new Button("b1");
Button b2 = new Button("b2");
Button b3 = new Button("b3");
Button b4 = new Button("b4");
Button b5 = new Button("b5");
Button b6 = new Button("b6");
f.setLayout(new GridLayout(3, 2));
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.pack();
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestInner.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestInner {
Frame f = new Frame("Mouse");
TextField tf = new TextField(30);
public TestInner() {
f.add(new Label("Mouse"), "North");
f.add(tf, "South");
f.setBackground(new Color(120, 175, 175));
f.addMouseMotionListener(new InnerMonitor());
f.addMouseListener(new InnerMonitor());
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String args[]) {
TestInner t = new TestInner();
}
private class InnerMonitor implements MouseMotionListener, MouseListener {
public void mouseDragged(MouseEvent e) {
String s = "(" + e.getX() + "," + e.getY() + ")";
tf.setText(s);
}
public void mouseEntered(MouseEvent e) {
String s = "Start";
tf.setText(s);
}
public void mouseExited(MouseEvent e) {
String s = "end";
tf.setText(s);
}
public void mouseMoved(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}//end of Inner class
}//end of Outer class
================================================
FILE: src/main/java/com/basic/chapter1000/TestKey.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestKey {
public static void main(String[] args) {
new KeyFrame().launchFrame();
}
}
class KeyFrame extends Frame {
public void launchFrame() {
setSize(200, 200);
setLocation(300, 300);
addKeyListener(new MyKeyMonitor());
setVisible(true);
}
class MyKeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
System.out.println("UP");
}
}
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestMouseMotion.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TestMouseMotion {
public static void main(String args[]) {
new MyFrame88("drawing...");
}
}
class MyFrame88 extends Frame {
ArrayList points = null;
MyFrame88(String s) {
super(s);
points = new ArrayList();
setLayout(null);
setBounds(300, 300, 400, 300);
this.setBackground(new Color(204, 204, 255));
setVisible(true);
this.addMouseMotionListener(new Monitor5());
}
public void paint(Graphics g) {
Iterator i = points.iterator();
while (i.hasNext()) {
Point p = (Point) i.next();
g.setColor(Color.BLUE);
g.fillOval(p.x, p.y, 10, 10);
}
}
public void addPoint(Point p) {
points.add(p);
}
}
class Monitor5 extends MouseMotionAdapter {
private int num = 0;
public void mouseMoved(MouseEvent e) {
MyFrame88 f = (MyFrame88) e.getSource();
f.addPoint(new Point(e.getX(), e.getY()));
if (num++ >= 5) {
f.repaint();
num = 0;
}
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestMouseMotionGeneric.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TestMouseMotionGeneric {
public static void main(String args[]) {
new MyFrame888("drawing...");
}
}
class MyFrame888 extends Frame {
ArrayList points = null;
MyFrame888(String s) {
super(s);
points = new ArrayList();
setLayout(null);
setBounds(300, 300, 400, 300);
this.setBackground(new Color(204, 204, 255));
setVisible(true);
this.addMouseMotionListener(new Monitor4());
}
public void paint(Graphics g) {
Iterator i = points.iterator();
while (i.hasNext()) {
Point p = i.next();
g.setColor(Color.BLUE);
g.fillOval(p.x, p.y, 10, 10);
}
}
public void addPoint(Point p) {
points.add(p);
}
}
class Monitor4 extends MouseMotionAdapter {
private int num = 0;
public void mouseMoved(MouseEvent e) {
MyFrame888 f = (MyFrame888) e.getSource();
f.addPoint(new Point(e.getX(), e.getY()));
if (num++ >= 5) {
f.repaint();
num = 0;
}
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestMultiFrame.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestMultiFrame {
public static void main(String args[]) {
MyFrame4 f1 =
new MyFrame4(100, 100, 200, 200, Color.BLUE);
MyFrame4 f2 =
new MyFrame4(300, 100, 200, 200, Color.YELLOW);
MyFrame4 f3 =
new MyFrame4(100, 300, 200, 200, Color.GREEN);
MyFrame4 f4 =
new MyFrame4(300, 300, 200, 200, Color.MAGENTA);
}
}
class MyFrame4 extends Frame {
static int id = 0;
MyFrame4(int x, int y, int w, int h, Color color) {
super("MyFrame4 " + (++id));
setBackground(color);
setLayout(null);
setBounds(x, y, w, h);
setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestMultiPanel.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestMultiPanel {
public static void main(String args[]) {
new MyFrame2("MyFrameWithPanel", 300, 300, 400, 300);
}
}
class MyFrame2 extends Frame {
private Panel p1, p2, p3, p4;
MyFrame2(String s, int x, int y, int w, int h) {
super(s);
setLayout(null);
p1 = new Panel(null);
p2 = new Panel(null);
p3 = new Panel(null);
p4 = new Panel(null);
p1.setBounds(0, 0, w / 2, h / 2);
p2.setBounds(0, h / 2, w / 2, h / 2);
p3.setBounds(w / 2, 0, w / 2, h / 2);
p4.setBounds(w / 2, h / 2, w / 2, h / 2);
p1.setBackground(Color.BLUE);
p2.setBackground(Color.GREEN);
p3.setBackground(Color.YELLOW);
p4.setBackground(Color.MAGENTA);
add(p1);
add(p2);
add(p3);
add(p4);
setBounds(x, y, w, h);
setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestPaint.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestPaint {
public static void main(String[] args) {
new PaintFrame().launchFrame();
}
}
class PaintFrame extends Frame {
public void launchFrame() {
setBounds(200, 200, 640, 480);
setVisible(true);
}
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.red);
g.fillOval(50, 50, 30, 30);
g.setColor(Color.green);
g.fillRect(80, 80, 40, 40);
g.setColor(c);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestPanel.java
================================================
package com.basic.chapter1000;
import java.awt.*;
public class TestPanel {
public static void main(String args[]) {
Frame f = new Frame("Java Frame with Panel");
Panel p = new Panel(null);
f.setLayout(null);
f.setBounds(300, 300, 500, 500);
f.setBackground(new Color(0, 0, 102));
p.setBounds(50, 50, 400, 400);
p.setBackground(new Color(204, 204, 255));
f.add(p);
f.setVisible(true);
}
}
================================================
FILE: src/main/java/com/basic/chapter1000/TestWindowClose.java
================================================
package com.basic.chapter1000;
import java.awt.*;
import java.awt.event.*;
public class TestWindowClose {
public static void main(String args[]) {
new MyFrame55("MyFrame");
}
}
class MyFrame55 extends Frame {
MyFrame55(String s) {
super(s);
setLayout(null);
setBounds(300, 300, 400, 300);
this.setBackground(new Color(204, 204, 255));
setVisible(true);
//this.addWindowListener(new MyWindowMonitor());
this.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(-1);
}
});
}
/*
class MyWindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
}
*/
}
================================================
FILE: src/main/java/com/basic/chapter1100/TestReflect.java
================================================
package com.basic.chapter1100;
import java.lang.reflect.*;
/**
* 反射
*
* @author MarkShen
* @since 20191130
*/
public class TestReflect {
public static void main(String[] args) throws Exception {
//m1();
//m2();
//m3("java.lang.Thread");
//m4();
//m5();
//m6();
//String s = "java.lang.String"; //从文件里读出来的
//new s()
//m7();
//m8();
//m9();
m10();
}
private static void m1() {
String s = new String();
Class c = s.getClass();
System.out.println(c);
Class su = c.getSuperclass();
System.out.println(su);
System.out.println(su.getSuperclass());
}
private static void m2() {
Class c = String.class;
System.out.println(c);
}
private static void m3(String className) {
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
System.out.println("this class doesn't exist!");
}
}
private static void m4() {
int m = String.class.getModifiers();
System.out.println(Modifier.isPublic(m));
System.out.println(Modifier.isFinal(m));
System.out.println(Modifier.isStatic(m));
}
private static void m5() {
for(Class c : String.class.getInterfaces()) {
System.out.println(c);
}
System.out.println(java.lang.Comparable.class.isInterface());
}
private static void m6() {
Field[] fs = System.class.getFields();
for(Field f : fs) {
System.out.println(f);
}
}
private static void m7() throws Exception {
Constructor[] cs = String.class.getConstructors();
for(Constructor c : cs) {
System.out.println(c);
for(Class paraClass : c.getParameterTypes()) {
System.out.print(paraClass + " ");
}
System.out.println();
}
String.class.newInstance();
}
private static void m8() throws Exception {
Class[] argClasses = new Class[] {int.class, int.class};
Object[] args = new Object[] {new Integer(12), new Integer(24)};
Constructor c = java.awt.Point.class.getConstructor(argClasses);
Object o = c.newInstance(args);
System.out.println(o);
}
private static void m9() throws Exception {
Class[] argClasses = new Class[] {String.class};
Object[] args = new Object[] {new String("world!")};
Method m = java.lang.String.class.getMethod("concat", argClasses);
String result = (String)m.invoke(new String("hello"), args);
System.out.println(result);
}
private static void m10() throws Exception {
/*
Class cls = Class.forName("java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String)Array.get(arr, 5);
System.out.println(s);
*/
//例中创建了一个 5 x 10 x 15 的整型数组,并为处于 [3][5][10] 的元素赋了值为 37。
//注意,多维数组实际上就是数组的数组,例如,第一个 Array.get 之后,
//arrobj 是一个 10 x 15 的数组。进而取得其中的一个元素,即长度为 15 的数组,
//并使用 Array.setInt 为它的第 10 个元素赋值。
int dims[] = new int[]{5, 10, 15};
Object arr = Array.newInstance(Integer.TYPE, dims);
Object arrobj = Array.get(arr, 3);
Class cls = arrobj.getClass().getComponentType();
System.out.println(cls);
arrobj = Array.get(arrobj, 5);
Array.setInt(arrobj, 10, 37);
int arrcast[][][] = (int[][][]) arr;
System.out.println(arrcast[3][5][10]);
}
}
================================================
FILE: src/main/java/com/basic/chapter1200/QQClient.java
================================================
package com.basic.chapter1200;
public class QQClient {
}
================================================
FILE: src/main/java/com/basic/chapter1200/QQServer.java
================================================
package com.basic.chapter1200;
public class QQServer {
}
================================================
FILE: src/main/java/com/geo/GeoLite2-City.mmdb
================================================
[File too large to display: 58.4 MB]
================================================
FILE: src/main/java/com/geo/GeoTest.java
================================================
package com.geo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.net.InetAddress;
/**
* 根据ip地址获取ip地址所在地
* https://github.com/maxmind/GeoIP2-java
*
* @author MarkShen
* @since 20191204
*/
public class GeoTest {
static String IP = "182.61.200.6";
/**
* 指定数据库路径
*/
static String DATABASE_PATH = System.getProperty("user.dir") + "/src/main/java/com/geo/GeoLite2-City.mmdb";
public static void main(String[] args) throws Exception {
// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File(DATABASE_PATH);
// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName(IP);
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 44.9733
System.out.println(location.getLongitude()); // -93.2323
}
}
================================================
FILE: src/main/java/com/java10/NewFeatures.java
================================================
/**
*
*/
package com.java10;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/javase/10-relnote-issues-4108729.html
* @see https://openjdk.org/projects/jdk/10/
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 10 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java11/NewFeatures.java
================================================
/**
*
*/
package com.java11;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/javase/11-relnotes-5012447.html
* @see https://openjdk.org/projects/jdk/11/
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 11 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java12/NewFeatures.java
================================================
/**
*
*/
package com.java12;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/javase/12-relnote-issues-5211422.html
* @see https://openjdk.org/projects/jdk/12/
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 12 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java13/NewFeatures.java
================================================
/**
*
*/
package com.java13;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/13-relnote-issues-5460548.html
* @see https://openjdk.org/projects/jdk/13/
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 13 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java14/Java14NewFeatures.java
================================================
package com.java14;
/**
* @author MarkShen1992
* @see https://www.oracle.com/technetwork/java/javase/14all-relnotes-5809668.html
* @see https://www.codejava.net/java-se/java-14-new-features
* @see https://openjdk.org/projects/jdk/14/
*/
public class Java14NewFeatures {
public static void main(String[] args) {
}
}
================================================
FILE: src/main/java/com/java15/NewFeatures.java
================================================
package com.java15;
/**
* jdk15 new feature
*
* https://openjdk.java.net/projects/jdk/15/
* https://javaalmanac.io/jdk/15/
* https://www.youtube.com/watch?v=uTNjeM0G9Nk
* https://openjdk.org/projects/jdk/15/
*/
public class NewFeatures {
public static void main(String[] args) {
System.out.println("jdk 15 new features.");
}
}
================================================
FILE: src/main/java/com/java16/Java16NewFeatures.java
================================================
package com.java16;
/**
* // Java 16 new features
* // 1) https://openjdk.java.net/projects/jdk/16/
* // 2) https://mkyong.com/java/what-is-new-in-java-16/
* @author MarkShen
*/
public class Java16NewFeatures {
public static void main(String[] args) {
}
}
================================================
FILE: src/main/java/com/java17/Java17NewFeatures.java
================================================
package com.java17;
/**
* https://www.baeldung.com/java-17-new-features https://mkyong.com/java/what-is-new-in-java-17/
* https://www.geeksforgeeks.org/jdk-17-new-features-in-java-17/
* @see https://openjdk.org/projects/jdk/17/
*
* @author MarkShen
*/
public class Java17NewFeatures {
public static void main(String[] args) {
System.out.println("Java 17 new Features.");
}
}
================================================
FILE: src/main/java/com/java18/Java18Features.java
================================================
package com.java18;
/**
* Java 18 features
* https://openjdk.org/projects/jdk/18/
* https://www.developer.com/java/java-18-features/
*/
public class Java18Features {
public static void main(String[] args) {
}
}
================================================
FILE: src/main/java/com/java19/Java19Features.java
================================================
package com.java19;
/**
* Java 19 features
* https://openjdk.org/projects/jdk/19/
* https://www.infoworld.com/article/3653331/jdk-19-the-new-features-in-java-19.html
*/
public class Java19Features {
public static void main(String[] args) {
}
}
================================================
FILE: src/main/java/com/java5/NewFeatures.java
================================================
/**
*
*/
package com.java5;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author MarkShen
*
*/
public class NewFeatures {
public static void print(int ...is) {
for (int num : is) {
System.out.println(num);
}
}
public static void main(String[] args) {
// Enhanced For loop
List numbers = new ArrayList();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Iterator numbersIterator = null;
for (numbersIterator = numbers.iterator(); numbersIterator.hasNext();) {
System.out.println(numbersIterator.next());;
}
for (Object o : numbers) {
System.out.println(o);
}
// VariableArguments
print(new int[] {1,2,4});
// Static Imports
// Enumerations(Typesafe Enums)
// 自动装箱与自动拆箱(Autoboxing/Unboxing)
// 引入泛型(Generics)
// 元数据(注解) (Metadata Annotations)
// 引入Instrumentation
}
}
================================================
FILE: src/main/java/com/java6/NewFeatures.java
================================================
/**
*
*/
package com.java6;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/javase/features-141434.html
* @see https://www.oracle.com/technical-resources/articles/javase/beta2.html
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 6 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java7/NewFeatures.java
================================================
/**
*
*/
package com.java7;
/**
* @author MarkShen
* https://openjdk.org/projects/jdk7/features/
* @see https://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 7 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/java8/Demo0100_LambdaRunnable.java
================================================
package com.java8;
/**
* @author MarkShen
*/
public class Demo0100_LambdaRunnable {
public static void main(String[] args) {
// 用lambda表达式实现Runnable
// Java 8之前:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8, too much code for too little to do");
}
}).start();
//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
// 这个例子向我们展示了Java 8 lambda表达式的语法。你可以使用lambda写出如下代码
// (params) -> expression
// (params) -> statement
// (params) -> { statements }
// 如果你的方法不对参数进行修改、重写,只是在控制台打印点东西的话
// () -> System.out.println("Hello Lambda Expressions");
// 如果你的方法接收两个参数
// (int even, int odd) -> even + odd
}
}
================================================
FILE: src/main/java/com/java8/Demo0200_LambdaIterator.java
================================================
package com.java8;
import java.util.Arrays;
import java.util.List;
/**
* @author MarkShen
*/
public class Demo0200_LambdaIterator {
public static void main(String[] args) {
// Java 8之前:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature : features) {
System.out.println(feature);
}
System.out.println("---------------------------------");
// Java 8之后:
features.forEach(n -> System.out.println(n));
// 使用Java 8的方法引用更方便,方法引用由::双冒号操作符标示,
// 看起来像C++的作用域解析运算符
System.out.println("---------------------------------");
features.forEach(System.out::println);
}
}
================================================
FILE: src/main/java/com/java8/Demo0300_LambdaPredicate.java
================================================
package com.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* @author MarkShen
*/
public class Demo0300_LambdaPredicate {
public static void main(String[] args) {
List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
System.out.println("Languages which starts with J :");
// filter(languages, (str)->str.startsWith("J"));
System.out.println("Languages which ends with a ");
// filter(languages, (str)->str.endsWith("a"));
System.out.println("Print all languages :");
filter(languages, (str)->true);
System.out.println("Print no language : ");
filter(languages, (str)->false);
System.out.println("Print language whose length greater than 4:");
// filter(languages, (str)->str.length() > 4);
// 甚至可以用and()、or()和xor()逻辑函数来合并Predicate,
// 例如要找到所有以J开始,长度为四个字母的名字,你可以合并两个Predicate并传入
Predicate startsWithJ = (n) -> n.startsWith("J");
Predicate fourLetterLong = (n) -> n.length() == 4;
languages.stream()
.filter(startsWithJ.and(fourLetterLong))
.forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));
}
/**
* filter
*
* @param names
* @param condition
*/
public static void filter(List names, Predicate condition) {
for (String name : names) {
if (condition.test(name)) {
System.out.println(name + " ");
}
}
}
// 更好的办法
public static void betterFilter(List names, Predicate condition) {
names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
System.out.println(name + " ");
});
}
}
================================================
FILE: src/main/java/com/java8/Demo0400_LambdaMapReduce.java
================================================
package com.java8;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author MarkShen
*/
public class Demo0400_LambdaMapReduce {
public static void main(String[] args) {
// 不使用lambda表达式为每个订单加上12%的税
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
for (Integer cost : costBeforeTax) {
double price = cost + .12*cost;
System.out.println(price);
}
// 使用lambda表达式
costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(System.out::println);
// 为每个订单加上12%的税
// 老方法:
double total = 0;
for (Integer cost : costBeforeTax) {
double price = cost + .12*cost;
total = total + price;
}
System.out.println("Total : " + total);
// 新方法:
double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill);
// 创建一个字符串列表,每个字符串长度大于2
List strList = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
List filtered = strList.stream().filter(x -> x.length()> 2).collect(Collectors.toList());
System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);
// 将字符串换成大写并用逗号链接起来
List G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
System.out.println(G7Countries);
// 用所有不同的数字创建一个正方形列表
List numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates : %s %n", numbers, distinct);
//获取数字的个数、最小值、最大值、总和以及平均值
List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());
}
}
================================================
FILE: src/main/java/com/java8/Demo0500_LambdaSimpleDemo.java
================================================
package com.java8;
/**
* @author MarkShen
*/
public class Demo0500_LambdaSimpleDemo {
public static void main(String[] args) {
// 1. 不需要参数,返回值为 5
// () -> 5
// 2. 接收一个参数(数字类型),返回其2倍的值
// x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
// (x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
// (int x, int y) -> x + y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
// (String s) -> System.out.print(s)
Demo0500_LambdaSimpleDemo tester = new Demo0500_LambdaSimpleDemo();
// 类型声明
MathOperation addition = (int a, int b) -> a + b;
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = (int a, int b) -> {
return a * b;
};
// 没有大括号及返回语句
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
// 不用括号
GreetingService greetService1 = message -> System.out.println("Hello " + message);
// 用括号
GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
greetService1.sayMessage("Runoob");
greetService2.sayMessage("Google");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}
================================================
FILE: src/main/java/com/java8/Demo0600_Stream.java
================================================
package com.java8;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* Stream 01
* @author MarkShen
*/
public class Demo0600_Stream {
public static void main(String[] args) {
/**
+--------------------+ +------+ +------+ +---+ +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+ +------+ +------+ +---+ +-------+
*/
List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(e -> !e.isEmpty()).collect(Collectors.toList());
filtered.forEach(System.out::println);
System.out.println();
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
System.out.println();
List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
List squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
squaresList.forEach(System.out::println);
List strs = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
long count = strs.stream().filter(s -> s.isEmpty()).count();
System.out.println(count);
System.out.println();
Random rdm = new Random();
rdm.ints().limit(10).sorted().forEach(System.out::println);
System.out.println();
List parallelStrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long countNum = parallelStrings.parallelStream().filter(s -> s.isEmpty()).count();
System.out.println(countNum);
System.out.println();
List ss = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filteredList = ss.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
System.out.println("筛选列表: " + filteredList);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
System.out.println();
List numberList = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numberList.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
}
}
================================================
FILE: src/main/java/com/java8/Demo0700_Stream.java
================================================
package com.java8;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Stream 02
* @author MarkShen
* https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
*/
public class Demo0700_Stream {
public static void main(String[] args) {
/**
* how to build stream
*/
// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List list = Arrays.asList(strArray);
stream = list.stream();
/**
* number stream build
*/
IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);
/**
* other data structure from stream
*/
String[] strArr = {"a", "b", "c"};
// 1. Array, List, Set, Stack, String
String[] sArr = Arrays.stream(strArr).toArray(String[]::new);
List list1 = Arrays.stream(strArr).collect(Collectors.toList());
List list2 = Arrays.stream(strArr).collect(Collectors.toCollection(ArrayList::new));
Set set1 = Arrays.stream(strArr).collect(Collectors.toSet());
Stack stack1 = Arrays.stream(strArr).collect(Collectors.toCollection(Stack::new));
String str = Arrays.stream(strArr).collect(Collectors.joining(", "));
// convert all elements to upper case
List myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(e -> e.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Stream> inputStream = Stream.of(
Arrays.asList(1),
Arrays.asList(2, 3),
Arrays.asList(4, 5, 6)
);
Stream outputStream = inputStream.
flatMap((childList) -> childList.stream());
outputStream.forEach(System.out::println);
System.out.println();
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());
System.out.println();
Stream.of("one", "two", "three", "four")
.findFirst().ifPresent(System.out::println);
System.out.println();
// 字符串连接,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
// 求和,sumValue = 10, 有起始值
int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
// 求和,sumValue = 10, 无起始值
sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
// 过滤,字符串连接,concat = "ace"
concat = Stream.of("a", "B", "c", "D", "e", "F").
filter(x -> x.compareTo("Z") > 0).
reduce("", String::concat);
System.out.println();
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
.limit(3)
.skip(2)
.collect(Collectors.toList()).forEach(System.out::println);
System.out.println();
List people = new ArrayList<>();
for (int i = 0; i < 10; i ++) {
people.add(new Person(i, "name" + i));
}
people.add(new Person(10, "name0"));
// 根据 name 属性降序输出
people.stream()
.sorted(Comparator.comparing(Person::getName).reversed())
.collect(Collectors.toList())
.forEach(System.out::println);
Map> result = people.stream()
.collect(Collectors.groupingBy(Person::getName));
System.out.println(result);
long c = people.stream().filter(x -> x.getId() > 5).count();
System.out.println(c);
long resultNum = people.stream().map(Person::getName).distinct().count();
System.out.println(resultNum);
Optional min = people.stream().min(Comparator.comparing(Person::getId));
System.out.println(min.get());
Optional max = people.stream().max(Comparator.comparing(Person::getId));
max.ifPresent(System.out::println);
Random seed = new Random();
Supplier random = seed::nextInt;
Stream.generate(random).limit(10).forEach(System.out::println);
// Another way
IntStream.generate(() -> (int) (System.nanoTime() % 100)).
limit(10).forEach(System.out::println);
Stream.iterate(0, n -> n + 3).limit(10). forEach(x -> System.out.print(x + " "));
Map> resultMap = people.stream()
.collect(Collectors.partitioningBy(p -> p.getId() < 6));
System.out.println(resultMap);
}
}
================================================
FILE: src/main/java/com/java8/Demo0800_Stream.java
================================================
package com.java8;
import java.util.*;
import java.util.stream.Collectors;
public class Demo0800_Stream {
public static void main(String[] args) {
List persons = Arrays.asList(new Person(1, "Bob", 21, 1), new Person(2, "Alice", 25, 0),
new Person(4, "Calvin", 26, 1), new Person(3, "Susan", 34, 0), new Person(5, "Trump", 70, 1));
Person persion = persons.stream().filter(p -> p.getName().equals("Bob")).findFirst().orElse(null);
System.out.println(persion);
// 人小于等于25的人的名字
List names =
persons.stream().filter(p -> p.getAge() <= 25).map(Person::getName).collect(Collectors.toList());
System.out.println(names);
// 分页查询实现
int pageIndex = 1;
int pageSize = 2;
int recordIndex = (pageIndex - 1) * pageSize;
List pagedPerson = persons.stream().skip(recordIndex) // 每页第一条数据的位置
.limit(pageSize) // 页面大小
.collect(Collectors.toList());
System.out.println(pagedPerson);
// Searching
Optional any = persons.stream().filter(p -> p.getAge() < 25).findAny();
System.out.println(any);
System.out.println(persons.stream().anyMatch(p -> p.getAge() < 25));
// Reordering Descending
List sortedPersons = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed()) // 升序
.collect(Collectors.toList());
System.out.println(sortedPersons);
// Summarizing
int sum = 0;
sum = persons.stream().mapToInt(Person::getAge).reduce(0, (total, currentVal) -> total + currentVal);
System.out.println(sum);
sum = persons.stream().mapToInt(Person::getAge).sum();
System.out.println(sum);
long count = 0;
count = persons.stream().mapToInt(Person::getAge).count();
System.out.println(count);
// calculating summary
IntSummaryStatistics ageStatistics = persons.stream().mapToInt(Person::getAge).summaryStatistics();
System.out.println(ageStatistics.getAverage());
System.out.println(ageStatistics.getCount());
System.out.println(ageStatistics.getMax());
System.out.println(ageStatistics.getMin());
System.out.println(ageStatistics.getSum());
// Grouping
Map> peopleGroupBySex =
persons.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.toList()));
System.out.println(peopleGroupBySex);
Map> nameByGender = persons.stream()
.collect(Collectors.groupingBy(Person::getSex, Collectors.mapping(Person::getName, Collectors.toList())));
System.out.println(nameByGender);
Map averageAgeByGender =
persons.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.averagingInt(Person::getAge)));
System.out.println(averageAgeByGender);
}
}
================================================
FILE: src/main/java/com/java8/NewFeatures.java
================================================
/**
*
*/
package com.java8;
import java.util.Arrays;
import java.util.List;
/**
* @author MarkShen
* @see https://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
* @see https://openjdk.org/projects/jdk8/features
* @see http://www.importnew.com/16436.html
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 8 Features and Enhancements
List primes = Arrays.asList(new Integer[]{2, 3,5,7});
int factor = 2;
primes.forEach(element -> { System.out.println(factor*element); });
primes.forEach(element -> System.out.println(factor*element));
primes.forEach(e -> System.out.println("Hello World " + e));
}
}
================================================
FILE: src/main/java/com/java8/Person.java
================================================
package com.java8;
public class Person {
private int id;
private String name;
private int age;
private int sex;
public Person() {}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public Person(int id, String name, int age, int sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age='" + age + '\'' +
", sex=" + sex +
'}';
}
}
================================================
FILE: src/main/java/com/java9/NewFeatures.java
================================================
/**
*
*/
package com.java9;
/**
* @author MarkShen
* @see https://docs.oracle.com/javase/9/whatsnew/toc.htm#JSNEW-GUID-C23AFD78-C777-460B-8ACE-58BE5EA681F6
* @see https://openjdk.org/projects/jdk9/
*/
public class NewFeatures {
public static void main(String[] args) {
// Java SE 9 Features and Enhancements
}
}
================================================
FILE: src/main/java/com/jvm/OutOfMemoryException.java
================================================
package com.jvm;
import java.util.ArrayList;
import java.util.List;
/**
* @author MarkShen
* @since 20190622
* Exception: OutOfMemoryError 抛出,可以改造成多线程往List里面加
*/
public class OutOfMemoryException {
static List