30、31_异常
1.异常的各种使用:
class User {
private int age;
public void setage(int age) throws Exception {
if (age < 0) {
/*
* RuntimeException e = new RuntimeException("年龄不能为负数");
* throw e;
*/
Exception e = new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
public class Test {
public static void main(String[] args) {
User user = new User();
try {
user.setage(-10);
} catch (Exception e) {
System.out.println(e);
}
finally {
System.out.println("clean"); //无论是否发生异常,都执行
}
}
}
32、33、34_IO流
1.IO分类方法:
第一种分法:
输入流、输出流
第二种分法:
字节流、字符流
第三种分法:
节点流、处理流
2.字节流的使用:
FileInputStream
FileOutputStream
byte buffer[]
import java.io.*;
public class Test {
public static void main(String[] args) {
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream("c:/from.txt");
fout = new FileOutputStream("c:/out.txt");
byte[] buffer = new byte[100];
int temp = fin.read(buffer, 0, buffer.length); // read()返回读取的字节(byte)数
fout.write(buffer, 0, temp);
String str = new String(buffer);
System.out.println(str.trim()); // 删除字符串首尾空格
} catch (Exception e) {
System.out.println(e);
}
}
}
大文件:import java.io.*;
public class Test {
public static void main(String[] args) {
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream("c:/from.txt");
fout = new FileOutputStream("c:/out.txt");
byte[] buffer = new byte[1024];
while (true) {
int temp = fin.read(buffer, 0, buffer.length);
if (temp == -1) {
break;
}
fout.write(buffer, 0, temp);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
fin.close();
fout.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
3.字符流的使用:
同字节流相似
FileReader
FilrWriter
char buffer[]
4.处理流:
import java.io.*;
public class Test {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufReader = null;
try {
fileReader = new FileReader("c:/from1.txt");
bufReader = new BufferedReader(fileReader);
String line = null;
while (true) {
line = bufReader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
fileReader.close();
bufReader.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
5.装饰者模式:
interface Worker {
public void dosomework();
}
class AWorker implements Worker {
private Worker worker;
public AWorker() {
}
public AWorker(Worker worker) {
this.worker = worker;
}
public void dosomework() {
System.out.println("教授好");
worker.dosomework();
}
}
class Carpenter implements Worker {
public void dosomework() {
System.out.println("修门窗");
}
}
class Plumber implements Worker {
public void dosomework() {
System.out.println("修水管");
}
}
import java.io.*;
public class Test {
public static void main(String[] args) {
Plumber plu = new Plumber();
Carpenter cp = new Carpenter();
AWorker Aw = new AWorker(plu);
AWorker Aw2 = new AWorker(cp);
Aw.dosomework();
Aw2.dosomework();
}
}