大家好,欢迎来到IT知识分享网。
八、流与文件
8.1 File类
8.2 流
8.2.1 简介
| 字节流 | 字符流 | |
| 输入流 | InputStream | Reader |
| 输出流 | OutputStream | Writer |
8.2.2 InputStream与OutputStream
8.2.3 Reader与Writer
| 字节流 | 字符流 |
| InputStream / OutputStream | Reader / Writer 适配器: InputStreamReader / OutputStreamWriter |
| FileInputStream / FileOutputStream | FileReader / FileWriter |
| StringBufferInputStream(已弃用) / (无相应的类) | StringReader / StringWriter |
| ByteArrayInputStream/ByteArrayOutputStream | CharArrayReader / CharArrayWriter |
| PipedInputStream / PipedOutputStream | PipedReader / PipedWriter |
处理流(运用结构型设计模式:装饰模式)相对应:
| 字节流 | 字符流 |
| FilterInputStream / FilterOutputStream | FilterReader / FilterWriter(抽象类,无子类) |
| BufferedInputStream / BufferedOutputStream | BufferedReader(有readLine()) / BufferedWriter |
| PrintStream | PrintWriter |
| LineNumberInputStream(已弃用) | LineNumberReader |
| PushbackInputStream | PushbackReader |
Reader与Writer层次结构:
8.3 示例
8.3.1 文件操作
8.3.1.1 读文件
public static String readFile(String fileName) { File file = new File(fileName).getAbsoluteFile(); if (!file.isFile()) { return ""; } StringBuilder sb = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(new
FileInputStream(file), "UTF-8"); BufferedReader br = new BufferedReader(isr)) { String str; while ((str = br.readLine()) != null) { sb.append(str).append("\r\n"); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } 复制代码
8.3.1.1 写文件
public static void writeFile(String fileName, String msg) { File file = new File(fileName); try { BufferedWriter bf = null; try { bf = new BufferedWriter(new FileWriter(file, true)); bf.write(msg); bf.newLine(); bf.write(msg); } finally { if (bf != null) { bf.flush(); bf.close(); } } } catch (IOException e) { e.printStackTrace(); } } 复制代码
8.3.2 内存操作
public static void memoryOpt(){ String msg = "hello world !!!"; try(InputStream in = new ByteArrayInputStream(msg.getBytes()); OutputStream out = new ByteArrayOutputStream();){ int temp = 0; while((temp = in.read()) != -1){ out.write(Character.toUpperCase(temp)); } System.out.println(out); } catch (IOException e) { e.printStackTrace(); } } 复制代码
8.3.3 管道流
static class Writer implements Runnable { PipedOutputStream out; public Writer(PipedOutputStream out) { this.out = out; } @Override public void run() { try { String message = "I'm K^Joker"; try { out.write(message.getBytes()); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } static class Reader implements Runnable { PipedInputStream in; public Reader(PipedInputStream in) { this.in = in; } @Override public void run() { byte data[] = new byte[1024]; try { try { int len = in.read(data); System.out.println(new String(data, 0, len)); } finally { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { PipedOutputStream out = new PipedOutputStream(); PipedInputStream in; try { in = new PipedInputStream(out); Thread read = new Thread(new Reader(in)); Thread write = new Thread(new Writer(out)); read.start(); write.start(); } catch (IOException e) { e.printStackTrace(); } } 复制代码
8.3.4 对象流
public class Person implements Serializable { private String name; private transient Integer age; private final Integer height = 180; private static Integer weight = 160; private transient final String nickName = "取毛名"; private transient static String phone = "110"; public Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", height=" + height + ", nickName='" + nickName + '\'' + '}'; } public static void serialize() { File file = new File("E:" + File.separator + "serializable.txt"); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) { out.writeObject(new Person("K^Joker", 23)); } catch (IOException e) { e.printStackTrace(); } } public static void deserialize() { File file = new File("E:" + File.separator + "serializable.txt"); try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));){ Object obj = in.readObject(); System.out.println(obj); } catch (IOException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { // serialize(); deserialize(); } } 复制代码
九、枚举
9.1 特性
① 枚举经常用来表示一组相同类型的常量,例如性别、学历、日期。
② 枚举是一种特殊的类,它与普通类一样,不过构造器访问修饰符只能private,enum关键字定义,默认继承了 java.lang.Enum 类,故不能继承其他类,并实现了 java.lang.Seriablizable 和 java.lang.Comparable 两个接口。 ③ 定义为枚举类后编译器会加上final声名,所以该类无法被继承 ④ 所有的枚举值都是 public static final 的,且必须在第一行定义 ⑤ 若在枚举中定义了抽象方法,那所有枚举变量必须实现其抽象方法
9.2 实现机制
我们先定义一个枚举:
public enum ColorEnum { RED(), YELLOW(), BLUE(); } 复制代码
我们可以看到枚举其实就是一个类,并且该类被声明为final,继承了Enum类,枚举定义的变量被声明为public static final,另外多出了静态代码块,和两个静态方法values()和valueOf()。Enum类是一个抽象类,主要有name(枚举变量的名称)和ordinal(枚举变量的位置索引)两个属性,在多出的静态代码块中做了这样的操作:
RED = new ColorEnum("RED", 0); YELLOW = new ColorEnum("YELLOW", 1); BLUE = NEW ColorEnum("BLUE", 2); $VALUES = new ColorEnum[]{RED, YELLOW, BLUE}; 复制代码
values()方法是返回$VALUES数组的复制,valueOf方法是根据传入的变量名称返回对应枚举实例。从下面那张图我们可以大致看出这些。
9.3 枚举使用
① 枚举可以实现接口,具有抽象方法
public enum ColorEnum implements ColorInterface{ RED("红色"){ @Override void say(){ System.out.println("我是红色"); } }, YELLOW("黄色"){ @Override void say(){ System.out.println("我是黄色"); } }, BLUE("蓝色"){ @Override void say(){ System.out.println("我是蓝色"); } }; //必须第一行 private String color; private ColorEnum(String color){ this.color = color; } @Override public String getColor(){ return color; } abstract void say(); public static void main(String[] args) { System.out.println(ColorEnum.RED); //RED System.out.println(ColorEnum.RED.getColor()); //红色 System.out.println(ColorEnum.RED.name()); //RED System.out.println(ColorEnum.RED.ordinal()); //0 for(ColorEnum color : ColorEnum.values()){ System.out.println(color); //RED YELLOW BLUE } ColorEnum.RED.say(); //我是红色 } } 复制代码
② 接口中使用枚举
public interface Food { enum Appetizer implements Food{ SALAD, SOUP, SPRING_ROLLS; } enum Dessert implements Food{ FRUIT, TIRAMISU, GELATO } } 复制代码
十、注解
10.1 基本注解
10.2 自定义注解
10.2.1 元注解
| @Target | 表示该注解可以用于什么地方,其ElementType参数包括: CONSTRUCTOR: 构造器的声明 FIELD: 域声明(包括enum实例) LOCAL_VARIABLE: 局部变量声明 METHOD: 方法声明 PACKAGE: 包声明 PARAMTER: 参数声明 TYPE: 类、接口(包括注解类型)或enum声明 |
| @Retention | 表示需要在什么级别保存该注解信息,其RetentionPolicy参数包括: SOURCE: 注解将被编译器弄丢 CLASS: 注解在class文件中可用,但会被JVM弄丢 RUNTIME: JVM运行期有效,可以通过反射机制读取注解的信息 |
| @Documented | 将此注解包含在Javadoc中 |
| @Inherited | 允许子类继承父类中的注解 |
10.2.2 规则
10.2.3示例
public class Person { @MyValidation(nullable = false, message = "姓名不能为空") private String name; public Person(){ } public Person(String name) { this.name = name; } } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyValidation { boolean nullable() default true; String message() default ""; } public class Validation { public void validate(Object object) throws Exception { Class obj = object.getClass(); Field[] fields = obj.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); verify(field, object); field.setAccessible(false); } } private void verify(Field field, Object object) throws Exception { MyValidation mv = field.getAnnotation(MyValidation.class); if (mv != null && !mv.nullable()) { Object name = field.get(object); if("".equals(name) || name == null){ throw new Exception(mv.message()); } } } public static void main(String[] args) throws Exception { Validation v = new Validation(); // v.validate(new Person("")); v.validate(new Person()); } } 复制代码
十一、结语
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/111422.html