IO操作(Java版)
IO操作
流的传向、读取单位 (wori)
字节(byte): InputStream, OutputStream
字符(char): Reader, Writer (只适用于纯文本)
FileInputStream
try-with-resources 写法自动关闭流
try(FileInputStream inputStream = new FileInputStream("hhh.txt")) {int tmp;while((tmp = inputStream.read()) != -1) // 逐个System.out.println((char) tmp);byte[] bytes = new byte[inputStream.available()]; // 全部inputStream.read(bytes); // 内部调用readBytes(), 返回 读数System.out.println(new String(bytes));inputStream.skip(1); // 跳过1个字节}catch (IOException e) {e.printStackTrace();}
FileOutputStream
try(FileOutputStream outputStream =new FileOutputStream("out.txt",true)) { // 没有则创建,true 表示追加outputStream.write('a');outputStream.write("\nabc".getBytes());outputStream.flush(); // 确保写入} catch (IOException e) {e.printStackTrace();
}
单个文件拷贝(字节)
try(FileInputStream inputStream = new FileInputStream("hhh.txt");FileOutputStream outputStream = new FileOutputStream("out.txt")) {byte[] bytes = new byte[10]; // 传输媒介,单位为10字节int tmp;while ((tmp = inputStream.read(bytes)) != -1)outputStream.write(bytes,0,tmp);outputStream.flush();} catch (IOException e) {e.printStackTrace();}
FileReader
try(FileReader reader = new FileReader("hhh.txt")) {char[] chars = new char[10];reader.read(chars);System.out.println(chars);} catch (IOException e) {e.printStackTrace();}
FileWriter
try (FileWriter writer = new FileWriter("out.txt")) {writer.getEncoding();writer.write('牛'); // 字符writer // 内部调用 write(), 返回本身,故可以链式调用.append('牛').append('牛').append('牛');writer.flush();} catch (IOException e) {e.printStackTrace();}
单个文件拷贝(字符)
try(FileReader reader = new FileReader("hhh.txt");FileWriter writer = new FileWriter("out.txt")) {char[] chars = new char[10];int tmp;while ((tmp = reader.read(chars)) != -1)writer.write(chars,0,tmp);writer.flush();} catch (IOException e) {e.printStackTrace();}
File
File file = new File("C:/");System.out.println(Arrays.toString(file.list()));for (File f: file.listFiles()) {System.out.println(f);}File file = new File(".idea/a/b/c");file.mkdirs(); // 递归式地创建
文件夹拷贝
File file = new File(".idea/");File target = new File("new/");target.mkdir();for (File f: file.listFiles()) {try (FileInputStream inputStream = new FileInputStream(f);FileOutputStream outputStream= new FileOutputStream(target.getPath() +"/"+ f.getName())) {byte[] bytes = new byte[10];int tmp;while ((tmp = inputStream.read(bytes)) != -1)outputStream.write(bytes,0,tmp);outputStream.flush();} catch (IOException e) {e.printStackTrace();}
缓冲流
装饰者 模式
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("hhh.txt"),2);bufferedInputStream.mark(1); // 保留之后的1个字节System.out.println((char)bufferedInputStream.read());bufferedInputStream.reset();System.out.println((char)bufferedInputStream.read());BufferedReader reader = new BufferedReader(new FileReader("hhh.txt"));System.out.println((char)reader.read());System.out.println(reader.readLine()); // Stringreader.lines().limit(1).sorted().forEach(System.out::println);
流 (Stream)
自理阶段,不一定按顺序执行
List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(3);list.add(4);list = list.stream().distinct().sorted((a, b) -> b - a).map(e -> e + 1).limit(2).collect(Collectors.toList());list.forEach(System.out::println);Random random = new Random();random.ints(-100,100).limit(10).filter(i -> i<0).sorted().forEach(System.out::println);
Optional 类
避免显示 null 判断
String str = "B"; // 对单个对象操作Optional<String> optional = Optional.ofNullable(str);optional.ifPresent(System.out::println);System.out.println(optional.orElse("lbwnb"));System.out.println(optional.filter(e -> e.equals("B")).get());System.out.println(optional.map(e -> e + "A").get());
转换流
字符式 地操作流
try (OutputStreamWriter outputStreamWriter =new OutputStreamWriter(new FileOutputStream("hhh.txt"))) {outputStreamWriter.write("玩!!!"); // 支持Writer以 字符 形式写入} catch (IOException e) {e.printStackTrace();}try (BufferedReader reader =new BufferedReader(new InputStreamReader(new FileInputStream("hhh.txt")))) {System.out.println(reader.readLine()); // 套娃}
打印流
try (PrintStream stream = new PrintStream(new FileOutputStream("hhh.txt"))) {stream.println("12321"); // System.out 也是一个 PrintStream, 默认到 console} catch (IOException e) {e.printStackTrace();}
数据流
基本类型即可,二进制写入
try (DataOutputStream outputStream =new DataOutputStream(new FileOutputStream("hhh.txt"));DataInputStream inputStream =new DataInputStream(new FileInputStream("hhh.txt"))) {outputStream.writeFloat(1.5F);System.out.println(inputStream.readFloat());}
对象流
public static void main(String[] args) throws IOException {try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("hhh.txt"));ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("hhh.txt"))) {Student oliver = new Student("Oliver");outputStream.writeObject(oliver); // writeoutputStream.flush();oliver = (Student) inputStream.readObject(); // read, 反序列化对象。如果类的版本不匹配(serialVersionUID 变化),则 InvalidClassExceptionSystem.out.println(oliver.name);} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}static class Student implements Serializable{private static final long serialVersionUID = 123457; // 自动添加transient int age; // 该属性不参与序列化String name;public Student(String name) {this.name = name ;}}
注解
@Target({ElementType.METHOD,ElementType.TYPE}) // 限定作用位置
@Retention(RetentionPolicy.RUNTIME) // 保留策略
public @interface Test {// 注解成员变量以“无形参方法”声明String value() default "666"; // 不强制再赋值String test();
}public class Main {public static void main(String[] args) throws IOException {Class<Student> clazz = Student.class;for (Annotation annotation : clazz.getAnnotations()) {System.out.println(annotation.annotationType());System.out.println(annotation instanceof Test);Test test = (Test) annotation;System.out.println(test.test());System.out.println(test.value());}}}@Test(test = "hello")
class Student {String name;@Test(test = "yooo")void play() {}
}
IO操作(Java版)相关推荐
- java io操作_Java IO 操作
IO操作 Java对数据的操作都是通过流的方式,IO流用来处理设备之间的数据传输,文件上传和文件下载,Java用于操作流的对象都在IO包,NIO(New IO)包中. 创建文件 Java创建文件的方式 ...
- JAVA版StarDict星际译王简单实现
由胡正开发的星际译王是Linux平台上很强大的一个开源的翻译软件(也有Windows版本的)支持多种词库.多种语言版本.尤其词库设计比较合理.之前看到一篇博文<星际译王词库应用-自制英汉词典&g ...
- java版mosquitto客户端使用SSL功能的具体操作总结
在开发java版mosquitto客户端程序时需要使用paho库,如果开发的java客户端要用ssl功能,则需要Bouncy Castle库:在使用ssl功能时,需要证书文件进行进行身份认证,但在测试 ...
- [零基础学JAVA]Java SE应用部分-27.Java IO操作(01)
JAVA IO操作目标 本季知识点 1.File类 2.RandomAccessFile类 File类 在JAVA中所有的IO操作全部存放在java.io包中. File是唯一一个与文件本身有关的操作 ...
- java中的IO操作总结(一)
转载:http://www.cnblogs.com/nerxious/archive/2012/12/15/2818848.html 所谓IO,也就是Input与Output的缩写.在java中 ...
- java安全编码指南之:文件IO操作
文章目录 简介 创建文件的时候指定合适的权限 注意检查文件操作的返回值 删除使用过后的临时文件 释放不再被使用的资源 注意Buffer的安全性 注意 Process 的标准输入输出 InputStre ...
- Java之IO操作总结
所谓IO,也就是Input与Output的缩写.在java中,IO涉及的范围比较大,这里主要讨论针对文件内容的读写 其他知识点将放置后续章节 对于文件内容的操作主要分为两大类 分别是: 字符流 字节流 ...
- java中的IO操作之File类
Java的集合框架: 类和接口存在于java.util包中. Java的IO: 类和接口存在于java.io包中. 学习方法: 文档在手,天下我有! --------- ...
- java堆外内存为何比java堆更适合用来进行网络IO操作
java执行socket.write对java堆内的数组数据进行网络IO操作时,其实分两步进行: 1.把java堆的数据拷贝到C堆内存中(对Java来说就是堆外内存,只是这个内存不归java管理) 2 ...
- Java基础复习笔记系列 七 IO操作
Java基础复习笔记系列之 IO操作 我们说的出入,都是站在程序的角度来说的.FileInputStream是读入数据.?????? 1.流是什么东西? 这章的理解的关键是:形象思维.一个管道插入了一 ...
最新文章
- c语言 栈求解表达式_非线性方程组的编程求解方法
- AUP2敏捷统一过程之一:序言及降低过程的总体拥有成本
- python代码自动格式化_代码的自动格式化
- 解决.gitgnore加入.idea无效问题
- mysql/mariadb应该使用utf8mb4而不是utf8
- SQL 关于地图两个坐标点之间的距离运算
- 一款基于.NET Core的认证授权解决方案-葫芦藤1.0开源啦
- .NET core3.0 使用Jwt保护api
- codevs 1028 花店橱窗布置 (KM)
- [js] 使用ajax轮询接口有什么优缺点?
- vue data 值如何渲染_vue源码阅读复盘-watcher模块
- matlab语句跳转,matlab编程 跳转语句
- vb将excel数据导入mysql_使用VB将Excel导入到Sql中
- 网吧十大漏洞曝光(转)
- App Links(APP关联)
- 专科毕业五年,曲线救国进腾讯
- 草根程序员转型做项目管理走过的点点滴滴之_华为裁员感想
- 这些东西适合做什么?
- Java5分钟制作海报
- 使用Cocoapods创建私有podspec