Java 快速入门

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); // {A=something A}
System.out.println(map.get("A")); // something A
System.out.println(map.size()); // 1
System.out.println(map.containsKey("A")); // true

map.replace("A", "new A");

System.out.println(map); // {A=new A}
}
}

向上转型与向下转型

向上转型:父类引用指向子类对象
向下转型:子类引用指向父类对象

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()); // class Child
System.out.println(parent instanceof Child); // true
System.out.println(parent instanceof Parent); // true
}
}

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类中原本没有 eat方法,在向下转型之前如果调用eat方法会报错
//向下转型为子类Dog类后,就可以调用子类中特有的方法,而不会报错
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();

//判断instanceof 是否为 true
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]); // writes the bytes
}
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);
// 构建FileOutputStream对象,文件不存在会自动新建

OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk

writer.append("中文输入");
// 写入到缓冲区

writer.append("\r\n");
// 换行

writer.append("English");
// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入

writer.close();
// 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉

fop.close();
// 关闭输出流,释放系统资源

FileInputStream fip = new FileInputStream(f);
// 构建FileInputStream对象

InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
// 构建InputStreamReader对象,编码与写入相同

StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char) reader.read());
// 转成char加到StringBuffer对象中
}
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 对象
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;
// 等价于 Lambda:() -> str.toString()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Function<Integer, Integer> func = Math::abs;
// 等价于 Lambda:x -> Math.abs(x)

Function<String, Integer> f = String::length;
// 等价于 Lambda:(s) -> s.length()

Supplier<String> sup = String::new;
// 等价于 Lambda:() -> new String()

// Lambda
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("线程任务");
}
}
// 把任务交给 Thread 去执行
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();
// 同一个任务,交给2个线程,共享num
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))

  1. 进入同步块,判断 maker.count > 0 → 当前 count=0,条件不成立,不 wait
  2. 调用 maker.produce():count=1,producedTotal=1,打印:Produced a product #1
  3. maker.notify():唤醒等待在 maker 锁上的线程(此时消费者还没 wait,notify 相当于空操作)
  4. 退出 synchronized 块,释放 maker 锁
  5. 生产者执行 Thread.sleep(100),生产者休眠 100ms(此时生产者不持有锁)

生产者 sleep 期间,CPU 调度到消费者线程

  1. 消费者抢到锁 synchronized(maker)
  2. 判断 maker.count ==0 → count=1,条件不成立,不 wait
  3. maker.consume():打印 Consumed a product, 1 left.,count=0
  4. maker.notify():唤醒生产者(生产者此时正在 sleep,不是 wait 状态,notify 无效)
  5. 退出同步块,释放锁
  6. 消费者 Thread.sleep(100) 休眠

消费者 sleep 期间,生产者 sleep 结束,再次进入循环抢锁

  1. 生产者再次拿到锁,count>0?count=0 → false,生产:count=1,#2,notify,释放锁,sleep
  2. 消费者睡醒抢锁,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) {
// 1. 创建线程池
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, // 核心线程2个
5, // 最大线程5个
3L, // 非核心线程空闲3秒回收
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10), // 有界队列,容量10
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);

// 2. 提交任务:2种方式
// 方式1:execute() 提交Runnable,无返回值
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();
}
});
}

// 方式2:submit() 提交任务,有返回值Future,可以捕获异常
// Future<?> future = pool.submit(() -> System.out.println("有返回任务"));

// 3. 关闭线程池
pool.shutdown(); // 平缓关闭:不再接收新任务,等待已有任务执行完毕
// pool.shutdownNow(); // 强制关闭:尝试中断正在执行任务,返回未执行任务列表
}
}

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")); // true
System.out.println(list.contains("X")); // false
System.out.println(list.indexOf("C")); // 2
System.out.println(list.indexOf("X")); // -1
}
}

要正确使用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); // 将"Xiao Ming"和Student实例映射并关联
Student target = map.get("Xiao Ming"); // 通过key查找并返回映射的Student实例
System.out.println(target == s); // true,同一个实例
System.out.println(target.score); // 99
Student another = map.get("Bob"); // 通过另一个key查找
System.out.println(another); // 未找到返回null
}
}

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必须保证:

  1. 作为key的对象必须正确覆写equals()方法,相等的两个key实例调用equals()必须返回true;

  2. 作为

    1
    key

    的对象还必须正确覆写

    1
    hashCode()

    方法,且

    1
    hashCode()

    方法要严格遵循以下规范:

    • 如果两个对象相等,则两个对象的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"); // 构造一个Path对象
System.out.println(p1);
Path p2 = p1.toAbsolutePath(); // 转换为绝对路径
System.out.println(p2);
Path p3 = p2.normalize(); // 转换为规范路径
System.out.println(p3);
File f = p3.toFile(); // 转换为File对象
System.out.println(f);
for (Path p : Paths.get("..").toAbsolutePath()) { // 可以直接遍历Path
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) { // 利用while同时读取并判断
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);
}
} // 编译器在此自动为我们写入finally并调用close()
}

实际上,编译器并不会特别地为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")) {
// 定义1000个字节大小的缓冲区:
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")); // Hello
// "Hello world".getBytes(StandardCharsets.UTF_8)
output.close();
}

Reader Writer

1
2
3
4
5
6
7
8
9
10
11
12
public void readFile() throws IOException {
// 创建一个FileReader对象:
Reader reader = new FileReader("src/readme.txt"); // 字符编码是???
for (;;) {
int n = reader.read(); // 反复调用read()方法,直到返回-1
if (n == -1) {
break;
}
System.out.println((char)n); // 打印char
}
reader.close(); // 关闭流
}

和InputStream类似,Reader也是一种资源,需要保证出错的时候也能正确关闭,所以我们需要用try (resource)来保证Reader在无论有没有IO错误的时候都能够正确地关闭:

1
2
3
try (Reader reader = new FileReader("src/readme.txt", StandardCharsets.UTF_8)) {
// TODO
}

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()); // 写入char[]
writer.write("Hello"); // 写入String
}

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
// 默认使用UTF-8编码读取:
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
// 传入Runnable实例并立刻运行:
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
// 创建VirtualThread:
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:
ThreadFactory tf = Thread.ofVirtual().factory();
// 创建VirtualThread:
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);
// 也可以直接传入Runnable或Callable:
executor.submit(() -> {
System.out.println("Start virtual thread...");
Thread.sleep(1000);
System.out.println("End virtual thread.");
return true;
});
}

由于虚拟线程属于非常轻量级的资源,因此,用时创建,用完就扔,不要池化虚拟线程。


Java 快速入门
https://taylorandtony.github.io/2026/10/08/Java-快速入门/
作者
TaylorAndTony
发布于
2026年10月8日
许可协议