Enum
Enum 枚举 可以通过构造函数添加描述信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| enum Code { INVALID("this is invalid"), WHATEVER("whatever"), GOOD("Good");
String msg;
Code(String msg) { this.msg = msg; } }
public class Main { static void main(String[] args) { Code code = Code.INVALID; System.out.println(code.msg); } }
|
HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Main { static void main(String[] args) { HashMap<String, String> map = new HashMap<String,String>(); map.put("A", "something A"); map.put("B", "something B"); map.remove("B"); System.out.println(map); System.out.println(map.get("A")); System.out.println(map.size()); System.out.println(map.containsKey("A")); map.replace("A", "new A");
System.out.println(map); } }
|
向上转型与向下转型
向上转型:父类引用指向子类对象
向下转型:子类引用指向父类对象
1 2 3 4 5 6 7 8 9 10 11
| public class Main { static void main(String[] args) { Parent parent = new Child(); System.out.println(parent.getClass()); System.out.println(parent instanceof Child); System.out.println(parent instanceof Parent); } }
public class Parent {} public class Child extends Parent {}
|
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 26 27 28 29 30
| class Animal { public void display() { System.out.println("Animal"); } }
class Dog extends Animal { public void display() { System.out.println("dog"); }
public void eat() { System.out.println("吃骨头"); } }
public class Main{ public static void main(String[] args) { Animal animal = new Dog(); animal.display();
animal = (Dog)animal; ((Dog) animal).eat(); } }
|
安全性:使用 instanceof 判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Main { public static void main(String[] args) { Animal animal = new Dog(); if(animal instanceof Dog) { animal = (Dog)animal; ((Dog) animal).eat(); } else { System.out.println("Animal无法向下转型为Dog"); } } }
|
Lambda
Lambda 表达式
1 2 3 4 5 6 7 8
| public class Main { static void main(String[] args) { Runnable r = () -> { System.out.println("Hello World"); } r.run(); } }
|
FunctionalInterface 函数式接口是 Java 8 引入的一种新特性,它是一个有且仅有一个抽象方法的接口,但可以有多个非抽象方法。函数式接口可以被隐式转换为 lambda 表达式,使得代码更加简洁和易读。
1 2 3 4 5 6 7 8 9 10 11
| @FunctionalInterface interface MyInterface { void DoSome(); }
public class Main{ public static void main(String[] args) { MyInterface face = () -> System.out.println("das"); face.DoSome(); } }
|
泛型 public static <T> void
1 2 3 4 5 6 7 8 9 10 11
| public class Main { public static void main(String[] args) { displayThing("DSDD"); displayThing(1234); }
public static <T> void displayThing(T t) { System.out.println(t); } }
|
泛型类 class MyGenericClass<T>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Main { public static void main(String[] args) { MyGenericClass<Integer> class1 = new MyGenericClass<>(123); class1.display();
}
}
class MyGenericClass<T> { T t;
MyGenericClass(T t) { this.t = t; }
void display() { System.out.println(t); } }
|
带有约束的泛型 <T extends Number>
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
| public class Main { public static void main(String[] args) { displayThing(123); } public static <T extends Number> void displayThing(T t) { System.out.println(t); } }
## Thread
```java public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }
class MyThread extends Thread { @Override public void run() { System.out.println("Thread is running"); } }
|
文件IO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.io.*;
public class Main { public static void main(String[] args) { try { byte bWrite[] = {65,66,67,74,82}; OutputStream os = new FileOutputStream("test.txt"); for (int x = 0; x < bWrite.length; x++) { os.write(bWrite[x]); } os.close();
InputStream is = new FileInputStream("test.txt"); int size = is.available();
for (int i = 0; i < size; i++) { System.out.print((char) is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); } } }
|
指定编码:
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import java.io.*; public class fileStreamTest2 { public static void main(String[] args) throws IOException { File f = new File("a.txt"); FileOutputStream fop = new FileOutputStream(f); OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); writer.append("中文输入"); writer.append("\r\n"); writer.append("English"); writer.close(); fop.close(); FileInputStream fip = new FileInputStream(f); InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); StringBuffer sb = new StringBuffer(); while (reader.ready()) { sb.append((char) reader.read()); } System.out.println(sb.toString()); reader.close(); fip.close(); } }
|
反射
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws Exception { Class<?> clazz = Person.class; Constructor<?> constructor = clazz.getConstructor(String.class, int.class); Object person = constructor.newInstance("John", 30); Field nameField = clazz.getDeclaredField("name"); nameField.setAccessible(true); System.out.println("Name: " + nameField.get(person)); nameField.set(person, "Doe"); System.out.println("Updated Name: " + nameField.get(person)); Method greetMethod = clazz.getMethod("greet", String.class); greetMethod.invoke(person, "World"); } }
class Person { private String name; private int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public void greet(String message) { System.out.println(name + " says: " + message); } }
|
双冒号 (::)
:: 是 方法引用,属于 Java 8 新特性,本质是简写 Lambda 表达式,用来直接引用一个已经存在的方法,不用写多余参数。
方法引用要匹配函数式接口:
- 接口只有一个抽象方法
- 被引用的方法,参数列表、返回值要和接口抽象方法匹配
1 2 3
| String str = "hello"; Supplier<String> supplier = str::toString;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Function<Integer, Integer> func = Math::abs;
Function<String, Integer> f = String::length;
Supplier<String> sup = String::new;
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);
|
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.io.*; import java.util.Arrays; import java.util.List;
public class Main { static int total = 10;
public static void main(String[] args) { List<String> list = Arrays.asList("Java", "Python", "C++"); list.forEach(Main::print); }
public static void print(String content) { System.out.println(content); } }
|
Thread 和 Runnable 的区别
Runnable 是接口:代表要执行的任务,里面只有一个 run() 方法,描述线程要做什么。
Thread 是类:代表线程本身,负责创建、启动、管理线程。Thread 类本身也实现了 Runnable。
1 2 3 4 5 6 7 8
| class MyTask implements Runnable { @Override public void run() { System.out.println("线程任务"); } }
new Thread(new MyTask()).start();
|
优点:只是实现接口,不占用继承位;同一个任务对象可以交给多个线程执行。
共享变量例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Task implements Runnable{ private int num = 10; @Override public void run() { while(num>0){ System.out.println(num--); } } } public class Test{ public static void main(String[] args) { Task task = new Task(); new Thread(task).start(); new Thread(task).start(); } }
|
多线程 Runnable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.io.*;
public class Main { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < 4; i++) { System.out.println(Thread.currentThread().getName() + " -> " + i); } } };
new Thread(runnable).start();
for (int i = 0; i < 4; i++) { System.out.println(Thread.currentThread().getName() + " -> " + i); } } }
|
Callable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import java.io.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask;
public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { return 1; } }; FutureTask<Integer> futureTask = new FutureTask<>(callable); new Thread(futureTask).start(); System.out.println(futureTask.get()); return; } }
|
Synchronized
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 26 27 28 29 30
| import java.io.*;
public class Main { static int total = 10; static Object object = new Object();
public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { doSome(); } };
new Thread(runnable, "Thread1").start(); new Thread(runnable, "Thread2").start(); }
public static void doSome() { while (total > 0) { synchronized (object) { System.out.println(Thread.currentThread().getName() + " -> " + total); total--; } }
} }
|
同步方法
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 26 27 28 29 30
| import java.io.*;
public class Main { static int total = 10;
public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } while (total > 0) { doSome(); } } };
new Thread(runnable, "Thread1").start(); new Thread(runnable, "Thread2").start(); new Thread(runnable, "Thread3").start(); }
public synchronized static void doSome() { System.out.println(Thread.currentThread().getName() + " -> " + total); total--; } }
|
生产者 - 消费者模型
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import java.io.*; import java.util.Arrays; import java.util.List;
class Maker { int count = 0; int producedTotal = 0;
void produce() { count++; producedTotal++; System.out.println("Produced a product #" + producedTotal); }
void comsume() { System.out.println("Consumed a product, " + count + " left."); count--; } }
class Producer implements Runnable { private Maker maker;
public Producer(Maker maker) { this.maker = maker; }
@Override public void run() { while (true) { synchronized (maker) { if (maker.count > 0) { try { maker.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } maker.produce(); maker.notify(); } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
class Consumer implements Runnable { private Maker maker;
public Consumer(Maker maker) { this.maker = maker; }
@Override public void run() { while (true) { synchronized (maker) { if (maker.count == 0) { try { maker.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } maker.comsume(); maker.notify(); } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
public class Main {
public static void main(String[] args) { Maker maker = new Maker(); Producer producer = new Producer(maker); Consumer consumer = new Consumer(maker);
Thread thread1 = new Thread(producer); Thread thread2 = new Thread(consumer);
thread1.start(); thread2.start(); }
}
|
锁对象:maker,生产者、消费者共用这一把锁。
wait():释放锁,阻塞当前线程,等待被唤醒。
notify():唤醒一个在这个锁上等待的线程。
场景 A:生产者先拿到锁(synchronized (maker))
- 进入同步块,判断
maker.count > 0 → 当前 count=0,条件不成立,不 wait
- 调用
maker.produce():count=1,producedTotal=1,打印:Produced a product #1
maker.notify():唤醒等待在 maker 锁上的线程(此时消费者还没 wait,notify 相当于空操作)
- 退出 synchronized 块,释放 maker 锁
- 生产者执行
Thread.sleep(100),生产者休眠 100ms(此时生产者不持有锁)
生产者 sleep 期间,CPU 调度到消费者线程
- 消费者抢到锁
synchronized(maker)
- 判断
maker.count ==0 → count=1,条件不成立,不 wait
maker.consume():打印 Consumed a product, 1 left.,count=0
maker.notify():唤醒生产者(生产者此时正在 sleep,不是 wait 状态,notify 无效)
- 退出同步块,释放锁
- 消费者
Thread.sleep(100) 休眠
消费者 sleep 期间,生产者 sleep 结束,再次进入循环抢锁
- 生产者再次拿到锁,
count>0?count=0 → false,生产:count=1,#2,notify,释放锁,sleep
- 消费者睡醒抢锁,count 不为 0 → 消费 count=0,notify,sleep
如此循环往复:生产 → 消费 → 生产 → 消费…… 交替打印
ThreadPool
线程池:线程复用,避免频繁创建线程,提高性能。
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 26 27
| import java.io.*; import java.util.concurrent.*;
public class Main { public static void main(String[] args) { ExecutorService es = Executors.newFixedThreadPool(2); es.submit(new MyRunnable()); es.submit(new MyRunnable()); es.submit(new MyRunnable()); es.submit(new MyRunnable()); es.shutdown(); } }
class MyRunnable implements Runnable {
@Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName() + " finished!"); } }
|
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 26 27 28 29 30 31 32 33 34 35 36 37
| import java.util.concurrent.*;
public class ThreadPoolDemo { public static void main(String[] args) { ThreadPoolExecutor pool = new ThreadPoolExecutor( 2, 5, 3L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() );
for (int i = 0; i < 15; i++) { int idx = i; pool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 执行任务:" + idx); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); }
pool.shutdown(); } }
|
List
使用 Iterator<String> it = list.iterator() 迭代获取最高的访问效率
1 2 3 4 5 6 7 8 9 10 11 12
| import java.util.Iterator; import java.util.List;
public class Main { public static void main(String[] args) { List<String> list=List.of("Apple","Banana"); for (Iterator<String> it = list.iterator();it.hasNext();){ String s=it.next(); System.out.println(s); } } }
|
| 集合 |
线程安全 |
默认初始容量 |
扩容规则 |
底层 |
| ArrayList |
否 |
10(首次 add 创建) |
1.5 倍 |
数组 |
| LinkedList |
否 |
- |
无扩容 |
双向链表 |
| Vector |
是 |
10 |
2 倍 |
数组 |
| CopyOnWriteArrayList |
是 |
0 |
长度 + 1 |
数组 |
| ConcurrentLinkedQueue |
是 |
- |
无扩容 |
单向链表 |
| ConcurrentHashMap(JDK8) |
是 |
16 |
翻倍 |
数组 + 链表 / 红黑树 |
| HashMap(JDK8) |
否 |
16 |
翻倍 |
数组 + 链表 / 红黑树 |
list.contains
1 2 3 4 5 6 7 8 9 10 11
| import java.util.List;
public class Main { public static void main(String[] args) { List<String> list = List.of("A", "B", "C"); System.out.println(list.contains("C")); System.out.println(list.contains("X")); System.out.println(list.indexOf("C")); System.out.println(list.indexOf("X")); } }
|
要正确使用List的contains()、indexOf()这些方法,放入的实例必须正确覆写equals()方法,否则,放进去的实例,查找不到。
如何正确编写equals()方法?equals()方法要求我们必须满足以下条件:
- 自反性(Reflexive):对于非
null的x来说,x.equals(x)必须返回true;
- 对称性(Symmetric):对于非
null的x和y来说,如果x.equals(y)为true,则y.equals(x)也必须为true;
- 传递性(Transitive):对于非
null的x、y和z来说,如果x.equals(y)为true,y.equals(z)也为true,那么x.equals(z)也必须为true;
- 一致性(Consistent):对于非
null的x和y来说,只要x和y状态不变,则x.equals(y)总是一致地返回true或者false;
- 对
null的比较:即x.equals(null)永远返回false。
1 2 3 4 5 6
| public boolean equals(Object o) { if (o instanceof Person p) { return Objects.equals(this.name, p.name) && this.age == p.age; } return false; }
|
Map
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 26
| import java.util.HashMap; import java.util.Map;
public class Main { public static void main(String[] args) { Student s = new Student("Xiao Ming", 99); Map<String, Student> map = new HashMap<>(); map.put("Xiao Ming", s); Student target = map.get("Xiao Ming"); System.out.println(target == s); System.out.println(target.score); Student another = map.get("Bob"); System.out.println(another); } }
class Student { public String name; public int score; public Student(String name, int score) { this.name = name; this.score = score; } }
|
对Map来说,要遍历key可以使用for each循环遍历Map实例的keySet()方法返回的Set集合,它包含不重复的key的集合:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import java.util.HashMap; import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("apple", 123); map.put("pear", 456); map.put("banana", 789); for (String key : map.keySet()) { Integer value = map.get(key); System.out.println(key + " = " + value); } } }
|
同时遍历key和value可以使用for each循环遍历Map对象的entrySet()集合,它包含每一个key-value映射:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.util.HashMap; import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("apple", 123); map.put("pear", 456); map.put("banana", 789); for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + " = " + value); } } }
|
正确使用Map必须保证:
作为key的对象必须正确覆写equals()方法,相等的两个key实例调用equals()必须返回true;
作为
的对象还必须正确覆写
方法,且
方法要严格遵循以下规范:
- 如果两个对象相等,则两个对象的
hashCode()必须相等;
- 如果两个对象不相等,则两个对象的
hashCode()尽量不要相等。
NIO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import java.io.*; import java.nio.file.*;
public class Main { public static void main(String[] args) throws IOException { Path p1 = Paths.get(".", "project", "study"); System.out.println(p1); Path p2 = p1.toAbsolutePath(); System.out.println(p2); Path p3 = p2.normalize(); System.out.println(p3); File f = p3.toFile(); System.out.println(f); for (Path p : Paths.get("..").toAbsolutePath()) { System.out.println(" " + p); } } }
|
读取文件
1 2 3 4 5 6 7 8 9 10 11 12
| public void readFile() throws IOException { InputStream input = null; try { input = new FileInputStream("src/readme.txt"); int n; while ((n = input.read()) != -1) { System.out.println(n); } } finally { if (input != null) { input.close(); } } }
|
用try ... finally来编写上述代码会感觉比较复杂,更好的写法是利用Java 7引入的新的try(resource)的语法,只需要编写try语句,让编译器自动为我们关闭资源。推荐的写法如下:
1 2 3 4 5 6 7 8
| public void readFile() throws IOException { try (InputStream input = new FileInputStream("src/readme.txt")) { int n; while ((n = input.read()) != -1) { System.out.println(n); } } }
|
实际上,编译器并不会特别地为InputStream加上自动关闭。编译器只看try(resource = ...)中的对象是否实现了java.lang.AutoCloseable接口,如果实现了,就自动加上finally语句并调用close()方法。InputStream和OutputStream都实现了这个接口,因此,都可以用在try(resource)中。
在读取流的时候,一次读取一个字节并不是最高效的方法。很多流支持一次性读取多个字节到缓冲区,对于文件和网络流来说,利用缓冲区一次性读取多个字节效率往往要高很多。InputStream提供了两个重载方法来支持读取多个字节:
int read(byte[] b):读取若干字节并填充到byte[]数组,返回读取的字节数
int read(byte[] b, int off, int len):指定byte[]数组的偏移量和最大填充数
利用上述方法一次读取多个字节时,需要先定义一个byte[]数组作为缓冲区,read()方法会尽可能多地读取字节到缓冲区, 但不会超过缓冲区的大小。read()方法的返回值不再是字节的int值,而是返回实际读取了多少个字节。如果返回-1,表示没有更多的数据了。
利用缓冲区一次读取多个字节的代码如下:
1 2 3 4 5 6 7 8 9 10
| public void readFile() throws IOException { try (InputStream input = new FileInputStream("src/readme.txt")) { byte[] buffer = new byte[1000]; int n; while ((n = input.read(buffer)) != -1) { System.out.println("read " + n + " bytes."); } } }
|
想从文件中读取所有字节,并转换成char然后拼成一个字符串,可以这么写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Main { public static void main(String[] args) throws IOException { String s; try (InputStream input = new FileInputStream("C:\\test\\README.txt")) { int n; StringBuilder sb = new StringBuilder(); while ((n = input.read()) != -1) { sb.append((char) n); } s = sb.toString(); } System.out.println(s); } }
|
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.io.*;
public class Main { public static void main(String[] args) throws IOException { byte[] data = { 72, 101, 108, 108, 111, 33 }; try (InputStream input = new ByteArrayInputStream(data)) { String s = readAsString(input); System.out.println(s); } }
public static String readAsString(InputStream input) throws IOException { int n; StringBuilder sb = new StringBuilder(); while ((n = input.read()) != -1) { sb.append((char) n); } return sb.toString(); } }
|
每次写入一个字节非常麻烦,更常见的方法是一次性写入若干字节。这时,可以用OutputStream提供的重载方法void write(byte[])来实现:
1 2 3 4 5 6
| public void writeFile() throws IOException { OutputStream output = new FileOutputStream("out/readme.txt"); output.write("Hello".getBytes("UTF-8")); output.close(); }
|
Reader Writer
1 2 3 4 5 6 7 8 9 10 11 12
| public void readFile() throws IOException { Reader reader = new FileReader("src/readme.txt"); for (;;) { int n = reader.read(); if (n == -1) { break; } System.out.println((char)n); } reader.close(); }
|
和InputStream类似,Reader也是一种资源,需要保证出错的时候也能正确关闭,所以我们需要用try (resource)来保证Reader在无论有没有IO错误的时候都能够正确地关闭:
1 2 3
| try (Reader reader = new FileReader("src/readme.txt", StandardCharsets.UTF_8)) { }
|
FileWriter就是向文件中写入字符流的Writer。它的使用方法和FileReader类似:
1 2 3 4 5
| try (Writer writer = new FileWriter("readme.txt", StandardCharsets.UTF_8)) { writer.write('H'); writer.write("Hello".toCharArray()); writer.write("Hello"); }
|
PrintStream最终输出的总是byte数据,而PrintWriter则是扩展了Writer接口,它的print()/println()方法最终输出的是char数据。两者的使用方法几乎是一模一样的:
1 2 3 4 5 6 7 8 9 10 11 12 13
| import java.io.*;
public class Main { public static void main(String[] args) { StringWriter buffer = new StringWriter(); try (PrintWriter pw = new PrintWriter(buffer)) { pw.println("Hello"); pw.println(12345); pw.println(true); } System.out.println(buffer.toString()); } }
|
Files
从Java 7开始,提供了Files这个工具类,能极大地方便我们读写文件。
虽然Files是java.nio包里面的类,但他俩封装了很多读写文件的简单方法,例如,我们要把一个文件的全部内容读取为一个byte[],可以这么写:
1
| byte[] data = Files.readAllBytes(Path.of("/path/to/file.txt"));
|
如果是文本文件,可以把一个文件的全部内容读取为String:
1 2 3 4 5 6
| String content1 = Files.readString(Path.of("/path/to/file.txt"));
String content2 = Files.readString(Path.of("/path", "to", "file.txt"), StandardCharsets.ISO_8859_1);
List<String> lines = Files.readAllLines(Path.of("/path/to/file.txt"));
|
写入文件也非常方便:
1 2 3 4 5 6 7 8
| byte[] data = ... Files.write(Path.of("/path/to/file.txt"), data);
Files.writeString(Path.of("/path/to/file.txt"), "文本内容...", StandardCharsets.ISO_8859_1);
List<String> lines = ... Files.write(Path.of("/path/to/file.txt"), lines);
|
此外,Files工具类还有copy()、delete()、exists()、move()等快捷方法操作文件和目录。
虚拟线程
方法一:直接创建虚拟线程并运行:
1 2 3 4 5 6
| Thread vt = Thread.startVirtualThread(() -> { System.out.println("Start virtual thread..."); Thread.sleep(10); System.out.println("End virtual thread."); });
|
方法二:创建虚拟线程但不自动运行,而是手动调用start()开始运行:
1 2 3 4 5 6 7 8
| Thread vt = Thread.ofVirtual().unstarted(() -> { System.out.println("Start virtual thread..."); Thread.sleep(1000); System.out.println("End virtual thread."); });
vt.start();
|
方法三:通过虚拟线程的ThreadFactory创建虚拟线程,然后手动调用start()开始运行:
1 2 3 4 5 6 7 8 9 10
| ThreadFactory tf = Thread.ofVirtual().factory();
Thread vt = tf.newThread(() -> { System.out.println("Start virtual thread..."); Thread.sleep(1000); System.out.println("End virtual thread."); });
vt.start();
|
直接调用start()实际上是由ForkJoinPool的线程来调度的。我们也可以自己创建调度线程,然后运行虚拟线程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
ThreadFactory tf = Thread.ofVirtual().factory(); for (int i=0; i<100000; i++) { Thread vt = tf.newThread(() -> { ... }); executor.submit(vt); executor.submit(() -> { System.out.println("Start virtual thread..."); Thread.sleep(1000); System.out.println("End virtual thread."); return true; }); }
|
由于虚拟线程属于非常轻量级的资源,因此,用时创建,用完就扔,不要池化虚拟线程。