每日要點(diǎn)
概要
兩種對(duì)稱性
字節(jié) | 字符 |
---|---|
InputStream | Reader |
OutputStream | Writer |
輸入 | 輸出 |
---|---|
InputStream | OutputStream |
Reader | Writer |
read() | write() |
兩種設(shè)計(jì)模式
1.裝潢模式 - 過濾流
2.適配器模式 - 轉(zhuǎn)換流
三種流
1.數(shù)據(jù)流(原始流)
2.過濾流(處理流)
2.轉(zhuǎn)換流(編碼轉(zhuǎn)換)
原始流
FileOutputSteam - 指定文件作為輸出的目的地 - 數(shù)據(jù)流(原始流)
過濾流
PrintStream - 本身沒有輸出的目的地要依賴數(shù)據(jù)流才能使用 - 過濾流(處理流)
過濾流通常都比數(shù)據(jù)流擁有更多的方法方便對(duì)流進(jìn)行各種的操作
System中的in和out的兩個(gè)流可以進(jìn)行重定向
System.setOut(out);
例子1:99乘法表
public static void main(String[] args) {
try (PrintStream out = new PrintStream(new FileOutputStream("c:/99.txt"))) {
// try (PrintStream out = new PrintStream("c:/99.txt")) {
// System中的in和out的兩個(gè)流可以進(jìn)行重定向
// System.setOut(out);
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
// System.out.printf("%d*%d=%d\t", i, j, i * j);
out.printf("%d*%d=%d\t", i, j, i * j);
}
// System.out.println();
out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
例子2:
其中小知識(shí):如何在類路徑下取資源文件:
public static void main(String[] args) throws InterruptedException {
// 如何在類路徑下取資源文件
ClassLoader loader = Test01.class.getClassLoader();
InputStream in = loader.getResourceAsStream("resources/致橡樹.txt");
// try (Reader reader = new FileReader("c:/致橡樹.txt")) {
try (Reader reader = new InputStreamReader(in)) {
BufferedReader br = new BufferedReader(reader);
// LineNumberReader lineNumberReader = new LineNumberReader(reader);
String str;
while ((str = br.readLine()) != null) {
// while ((str = lineNumberReader.readLine()) != null) {
// System.out.print(lineNumberReader.getLineNumber());
System.out.println(str);
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
轉(zhuǎn)換流
轉(zhuǎn)換流 - 將字節(jié)流適配成字符流 (實(shí)現(xiàn)從字節(jié)到字符的轉(zhuǎn)換)
如果應(yīng)用程序中需要做編碼轉(zhuǎn)換(將8位編碼轉(zhuǎn)換成16位編碼)就需要使用轉(zhuǎn)換流
例子1:普通方法
public static void main(String[] args) {
System.out.print("請(qǐng)輸入: ");
byte[] buffer = new byte[1024];
try {
int totalBytes = System.in.read(buffer);
String str = new String(buffer, 0, totalBytes);
int endIndex = str.indexOf("\r\n");
if (endIndex != -1) {
str = str.substring(0, endIndex);
}
int a = Integer.parseInt(str);
// System.out.println(str.toUpperCase());
System.out.println(a > 5);
} catch (IOException e) {
e.printStackTrace();
}
}
例子2:轉(zhuǎn)換流 不使用Scanner從鍵盤輸入讀取數(shù)據(jù)
public static void main(String[] args) {
System.out.print("請(qǐng)輸入: ");
try {
// 轉(zhuǎn)換流 - 將字節(jié)流適配成字符流 (實(shí)現(xiàn)從字節(jié)到字符的轉(zhuǎn)換)
// 如果應(yīng)用程序中需要做編碼轉(zhuǎn)換(將8位編碼轉(zhuǎn)換成16位編碼)就需要使用轉(zhuǎn)換流
InputStreamReader inputReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String str;
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
}
}
序列化和反序列化
把對(duì)象寫入到流中 - 序列化(serialization)
串行化/歸檔/腌咸菜
從流中讀取對(duì)象 - 反序列化(反串行化/解歸檔)
serialVersionUID 相當(dāng)于版本號(hào)
被transient修飾的屬性不參與系列化和反序列化
private transient String tel;
注意:如果學(xué)生對(duì)象要支持序列化操作那么學(xué)生對(duì)象關(guān)聯(lián)的其他對(duì)象也要支持序列化
例子1:實(shí)現(xiàn)對(duì)學(xué)生類和車類序列化保存對(duì)象為文件净薛,再反序列化讀取
學(xué)生類:
public class Student implements Serializable{
private static final long serialVersionUID = 1L; // serialVersionUID 相當(dāng)于版本號(hào)
private String name;
private int age;
// 被transient修飾的屬性不參與系列化和反序列化
private transient String tel;
// 如果學(xué)生對(duì)象要支持序列化操作那么學(xué)生對(duì)象關(guān)聯(lián)的其他對(duì)象也要支持序列化
private Car car;
public Student(String name, int age, String tel) {
this.name = name;
this.age = age;
this.tel = tel;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age +
", tel=" + tel + "," + car.toString();
}
}
車類:
public class Car implements Serializable{
private static final long serialVersionUID = 1L;
private String brand;
private int maxSpeed;
public Car(String brand, int maxSpeed) {
this.brand = brand;
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "car=[brand=" + brand + ", maxSpeed=" + maxSpeed + "]";
}
}
序列化:
public static void main(String[] args) {
Student student = new Student("王大錘", 18, "13521324325");
student.setCar(new Car("QQ", 128));
System.out.println(student);
try (OutputStream out = new FileOutputStream("c:/stu.data")) {
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(student);
System.out.println("存檔成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
反序列化:
public static void main(String[] args) {
try (InputStream in = new FileInputStream("c:/stu.data")) {
ObjectInputStream ois = new ObjectInputStream(in);
Object object = ois.readObject();
System.out.println(object);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
昨日作業(yè)講解
- 作業(yè)1:九九乘法表文件輸出(普通方法)
public static void main(String[] args) {
try (Writer writer = new FileWriter("c:/九九表.txt")) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
String str = String.format("%d*%d=%d\t", i, j, i * j);
writer.write(str);
}
writer.write("\r\n");
}
System.out.println("程序執(zhí)行成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
- 作業(yè)2:寫一個(gè)方法實(shí)現(xiàn)文件拷貝功能
public static void fileCopy(String source, String target) throws IOException {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buffer = new byte[512];
int totalBytes;
while ((totalBytes = in.read(buffer)) != -1) {
out.write(buffer, 0, totalBytes);
}
}
}
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
fileCopy("C:/Users/Administrator/Downloads/YoudaoDict.exe", "C:/Users/Administrator/Desktop");
long end = System.currentTimeMillis();
System.out.println((end - start) + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
作業(yè)
- **作業(yè)1:建一個(gè)文本文件 寫很多話 做一個(gè)窗口 隨機(jī)顯示一句話 點(diǎn)一下?lián)Q一句 **
隨機(jī)文本類:
public class RandomText {
private List<String> list = new ArrayList<>();
private String str;
private int totalRows;
private int randomNum;
public RandomText() {
try {
this.random();
} catch (IOException e) {
e.printStackTrace();
}
}
private void random() throws IOException {
ClassLoader loader = RandomText.class.getClassLoader();
InputStream in = loader.getResourceAsStream("resources/致橡樹.txt");
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
while ((str = br.readLine()) != null) {
list.add(str);
totalRows += 1;
}
}
public String randomLine() {
randomNum = (int) (Math.random() * totalRows);
str = list.get(randomNum);
return str;
}
}
窗口類:
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private RandomText rt = new RandomText();
private JLabel label;
public MyFrame() {
this.setTitle("隨機(jī)話");
this.setSize(350, 200);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel(rt.randomLine());
label.setFont(new Font("微軟雅黑", Font.PLAIN, 18));
this.add(label);
JPanel panel = new JPanel();
this.add(panel, BorderLayout.SOUTH);
JButton button = new JButton("換一句");
button.addActionListener(e -> {
String command = e.getActionCommand();
if (command.equals("換一句")) {
label.setText(rt.randomLine());
}
});
panel.add(button);
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}