明翰Java入门教学系列之IO篇
分类
|
字节输入流
|
字节输出流
|
字符输入流
|
字符输出流
|
抽象父类
|
InputStream
|
OutputStream
|
Reader
|
Writer
|
访问文件 (节点流 )
|
FileInputStream
|
FileOutputStream
|
FileReader
|
FileWriter
|
访问数组 (节点流 )
|
ByteArrayInputStream
|
ByteArrayOutputStream
|
CharArrayReader
|
CharArrayWriter
|
访问管道 (节点流)
|
PipedInputStream
|
PipedOutputStream
|
PipedReader
|
PipedWriter
|
访问字符串 (节点流 )
|
StringReader
|
StringWriter
|
||
缓冲流
|
BufferedInputStream
|
BufferedOutputStream
|
BufferedReader
|
BufferedWriter
|
转换流
|
InputStreamReader
|
OutputStreamWriter
|
||
对象流
|
ObjectInputStream
|
ObjectOutputStream
|
||
过滤器流
|
FilterInputStream
|
FilterOutputStream
|
FilterReader
|
FilterWriter
|
打印流
|
PrintStream
|
PrintReader
|
||
推回输入流
|
PushbackInputStream
|
PushbackReader
|
||
特殊流
|
DataInputStream
|
DataOutputStream
|
public class FileInputOutStreamDemo1 {public static void main(String[] args) {FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream("enya恩雅-only time.mp3");fos = new FileOutputStream("new-enya恩雅-only time.mp3");byte[] temp = new byte[1024];while(fis.read(temp)!=-1) {fos.write(temp);}temp = new byte[1024];//将字符串写入到文件fos = new FileOutputStream("aaa.txt");fos.write("我爱你亲爱的姑娘".getBytes());//直接覆盖,而不是追加。如果想追加怎么办?fis = new FileInputStream("aaa.txt");fis.read(temp);System.out.println(new String(temp));} catch (Exception e) {e.printStackTrace();} finally {if(fis!=null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}if(fos!=null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}System.out.println("结束");}
}
public class FileWriterDemo1 {public static void main(String[] args) {FileReader fr = null;FileWriter fw = null;try {char[] temp = new char[1024];// 将字符串写入到文件fw = new FileWriter("aaa.txt");fw.write("我爱你亲爱的姑娘55555");// 直接覆盖,而不是追加。如果想追加怎么办?fr = new FileReader("aaa.txt");fr.read(temp);System.out.println(new String(temp));} catch (Exception e) {e.printStackTrace();} finally {if (fr != null) {try {fr.close();} catch (IOException e) {e.printStackTrace();}if (fw != null) {try {fw.close();} catch (IOException e) {e.printStackTrace();}}}System.out.println("结束");}
}
File f = new File("D:\\VSS存放目录\\KOOF\\3-开发阶段\\3.3-数据库","koof30.sql");
FileReader fi = new FileReader(f);
BufferedReader in = new BufferedReader(fi);
String s ;
String total = "";
while((s=in.readLine())!=null){
total += s+"\n";
}
public class PrintStreamDemo1 {public static void main(String[] args) {PrintStream ps = null;try {ps = new PrintStream(new FileOutputStream("bbb.txt"));ps.print("太阳当空照花儿对我笑");ps.println("小鸟说早早早你为什么背上小书包");ps.println(new PrintStreamDemo1());System.out.println("结束");} catch (Exception e) {e.printStackTrace();} finally {if (ps != null) {ps.close();}}}
}
public class BufferedDemo1 {public static void main(String[] args) {// jdk1.7支持的自动关闭资源的try写法try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("123.mp3"));BufferedInputStream bis = new BufferedInputStream(new FileInputStream("enya恩雅-only time.mp3"));BufferedReader br = new BufferedReader(new FileReader("456.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("789.txt"))) {String tempStr = null;while ((tempStr = br.readLine()) != null) {// 如遇乱码问题可以:// 1.将文本文件保存到UTF-8的编码集// 2.使用转换流并设置编码集而并非FileReader文件流System.out.println(tempStr);//BufferedWriter不会自动换行,可以使用PrintWriter自动换行。bw.write(tempStr);}byte[] temp = new byte[1024];while (bis.read(temp) > 0) {bos.write(temp);}System.out.println("结束");} catch (Exception e) {e.printStackTrace();}}
}
public class RandomAccessFileDemo1 {public static void main(String[] args) {RandomAccessFile raf = null;try {raf = new RandomAccessFile("aaa.txt","rw");//获取指针位置,初始位置为0System.out.println(raf.getFilePointer());raf.write("江山如此多娇,引无数英雄尽折腰。".getBytes());//移动指针位置raf.seek(6);System.out.println(raf.getFilePointer());//追加内容raf.seek(raf.length());raf.write("昔秦皇汉武略输文采,唐宗宋祖稍逊风骚。".getBytes());//从头到尾读raf.seek(0);byte[] temp = new byte[1024];while(raf.read(temp)>0) {System.out.println(new String(temp));}System.out.println("结束");} catch (Exception e) {e.printStackTrace();} finally {try {raf.close();} catch (IOException e) {e.printStackTrace();}}}
}
public class FileDemo1 {public static void main(String[] args) throws Exception {File f1 = new File("enya恩雅-only time.mp3");//相对路径文件名File f2 = new File("D:\\yangWorkSpaces\\yangDemoWorkSpace\\javademo");//绝对路径/*** 访问文件名&路径相关方法*/System.out.println(f1.getName());//返回文件名System.out.println(f2.getName());//返回路径名,只返回最后一级子路径名System.out.println(f2.getPath());//返回路径名,在File的构造里怎么写的就返回什么System.out.println(f1.getAbsolutePath());//返回绝对路径System.out.println(f1.getAbsoluteFile());//返回绝对路径对应的File对象System.out.println(f2.getParentFile());//返回父目录对应的File对象System.out.println(f2.getParent());//返回父目录对象System.out.println(f1.renameTo(new File("abc.mp3")));//重命名文件&目录,成功返回true,否则返回false/*** 文件检查相关方法*/System.out.println(f1.exists());//判断文件&目录是否存在System.out.println(f1.canWrite());//判断文件&目录是否可写System.out.println(f1.canRead());//判断文件&目录是否可读System.out.println(f1.isFile());//判断文件&目录是否是文件System.out.println(f1.isDirectory());//判断文件&目录是否是目录System.out.println(f2.isAbsolute());//判断文件&目录是否是绝对路径/*** 获取常规文件信息*/System.out.println(f1.lastModified());//返回文件&目录的最后修改时间,long类型System.out.println(f1.length());//返回文件&目录的长度/*** 文件操作相关方法*///当File对象不存在时创建对象,创建成功返回true,否则返回falseSystem.out.println(new File("4.mp3").createNewFile());System.out.println(new File("4.mp3").delete());//删除文件&目录,删除成功返回true,否则返回false//创建临时空文件,在前缀与后缀中间会有一串随机数组成临时文件名System.out.println(File.createTempFile("aaa", ".txt"));System.out.println(new File("4.mp3").createNewFile());//在jvm退出后删除文件new File("4.mp3").deleteOnExit();//删除文件,成功返回true,失败返回falseSystem.out.println(new File("4.mp3").delete());/*** 目录操作相关方法*/System.out.println(new File("D:\\aaa\\bb").mkdir());//创建目录,成功返回true,错误返回falseSystem.out.println(Arrays.asList(new File("D:\\aaa").list()));//返回子文件名&目录名的字符串数组System.out.println(Arrays.asList(new File("D:\\aaa").listFiles()));//返回子文件名&目录名的文件数组System.out.println(Arrays.asList(File.listRoots()));//列出系统根路径,例如[C:\, D:\]/*** 文件过滤*/File f = new File("D:\\yangWorkSpaces\\yangDemoWorkSpace\\javase\\src\\main\\java\\com\\mingyisoft\\javase\\thread\\threadsafe\\demo1");System.out.println(Arrays.asList(f.list(new FilenameFilter(){@Overridepublic boolean accept(File dir, String name) {return name.endsWith(".java") || new File(name).isDirectory();}})));}
}
public class SerializableDemo1 {public static void main(String[] args) {Teacher t = new Teacher();t.setName("alex");t.setAge(18);Student s1 = new Student();s1.setName("张三555");s1.setSex('5');s1.setYear(5);s1.description = "xxx";//嵌套对象s1.setTeacher(t);Student s2 = new Student();s2.setName("李四555");s2.setSex('6');s2.setYear(6);s2.description = "666";//嵌套对象s2.setTeacher(t);try {// Student对象序列化过程,使用ObjectOutputStreamObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"));oos.writeObject(s1);oos.writeObject(s2);oos.writeObject(t);s1.setName("王二麻子");oos.writeObject(s1);Student2 s3 = new Student2();s3.setYear(33);s3.setGpa(33);oos.writeObject(s3);oos.flush();oos.close();// Student对象反序列化过程,使用ObjectInputStreamObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"));Student ss1 = (Student) ois.readObject();System.out.println("name = " + ss1.getName());System.out.println("sex = " + ss1.getSex());System.out.println("year = " + ss1.getYear());System.out.println("gpa = " + ss1.getGpa());System.out.println("description = " + ss1.description);System.out.println("t.name = " + ss1.getTeacher().getName());System.out.println("t.age = " + ss1.getTeacher().getAge());Student ss2 = (Student) ois.readObject();System.out.println("name = " + ss2.getName());System.out.println("sex = " + ss2.getSex());System.out.println("year = " + ss2.getYear());System.out.println("gpa = " + ss2.getGpa());System.out.println("description = " + ss1.description);System.out.println("t.name = " + ss2.getTeacher().getName());System.out.println("t.age = " + ss2.getTeacher().getAge());Teacher tt = (Teacher) ois.readObject();System.out.println(tt.getName()+" "+tt.getAge());/*** 所有采用序列化机制的java对象都有一个序列化编号(不同于序列化版本号),* 当程序尝试序列化一个对象时,先检查当前对象是否已经被序列化过,只有从未序列化(本次jvm进程)过的对象,* 系统才会将该对象转换成字节序列,如果当前对象已经被序列化过,则自动使用其序列化编号而不是重新*/System.out.println(ss1.getTeacher()==ss2.getTeacher());System.out.println(ss1.getTeacher()==tt);System.out.println(ss2.getTeacher()==tt);Student ss3 = (Student) ois.readObject();/*** 即使属性改变,也不会序列化成新属性。内存里只有1个s1对象,并且s1的属性不能再被改变。*/System.out.println("应该是王二麻子吗->"+ss3.getName());/*** 自定义序列化,返回集合*/List returnList = (List) ois.readObject();for (Object obj : returnList) {System.out.println(obj);}ois.close();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}class Student extends Person implements Serializable{private String name;/*** 不进行序列化transient关键字,transient只能修饰属性*/private transient char sex;private int year;private double gpa;private Teacher teacher;public String getName() {return name;}public void setName(String name) {this.name = name;}public char getSex() {return sex;}public void setSex(char sex) {this.sex = sex;}public int getYear() {return year;}public void setYear(int year) {this.year = year;}public double getGpa() {return gpa;}public void setGpa(double gpa) {this.gpa = gpa;}public Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}
}class Teacher implements Serializable{/****/private static final long serialVersionUID = -1053051757102136827L;private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}class Student2 extends Person implements Serializable{private String name;/*** 不进行序列化transient关键字,transient只能修饰属性*/private transient char sex;private int year;private double gpa;private Teacher teacher;private Object writeReplace() {List<Object> returnList = new ArrayList<Object>();returnList.add(year);returnList.add(gpa);return returnList;}public String getName() {return name;}public void setName(String name) {this.name = name;}public char getSex() {return sex;}public void setSex(char sex) {this.sex = sex;}public int getYear() {return year;}public void setYear(int year) {this.year = year;}public double getGpa() {return gpa;}public void setGpa(double gpa) {this.gpa = gpa;}public Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}
}class Person implements Serializable{protected String description;
}
class Teacher implements Serializable{/****/private static final long serialVersionUID = -1053051757102136827L;private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}private void writeObject(ObjectOutputStream out) throws IOException {System.out.println("自定义写出");//反转一下名字out.writeObject(new StringBuffer(name).reverse());out.writeInt(age);}private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {System.out.println("自定义读入");//反转一下名字this.name = (((StringBuffer)in.readObject()).reverse()).toString();this.age = in.readInt();}
}class Student2 extends Person implements Serializable{private String name;/*** 不进行序列化transient关键字,transient只能修饰属性*/private transient char sex;private int year;private double gpa;private Teacher teacher;private Object writeReplace() {List<Object> returnList = new ArrayList<Object>();returnList.add(year);returnList.add(gpa);return returnList;}public String getName() {return name;}public void setName(String name) {this.name = name;}public char getSex() {return sex;}public void setSex(char sex) {this.sex = sex;}public int getYear() {return year;}public void setYear(int year) {this.year = year;}public double getGpa() {return gpa;}public void setGpa(double gpa) {this.gpa = gpa;}public Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}
}
public class ExternalizableDemo1 {public static void main(String[] args) {try {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("xxx.aaa"));Car c1 = new Car("alex", 12);Car c2 = new Car("jack", 15);oos.writeObject(c1);oos.writeObject(c2);oos.flush();oos.close();ObjectInputStream ois = new ObjectInputStream(new FileInputStream("xxx.aaa"));Car c11 = (Car) ois.readObject();Car c22 = (Car) ois.readObject();System.out.println(c11);System.out.println(c22);ois.close();} catch (Exception e) {e.printStackTrace();}}
}class Car implements Externalizable {private String name;private Integer age;public Car() {}public Car(String name, Integer age) {this.name = name;this.age = age;}public String toString() {return this.name + this.age;}public void writeExternal(ObjectOutput out) throws IOException {out.writeObject(new StringBuffer(name).reverse());out.writeInt(age);}public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {this.name = (((StringBuffer) in.readObject()).reverse()).toString();this.age = in.readInt();}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
明翰Java入门教学系列之IO篇相关推荐
- 1.偏头痛杨的Java入门教学系列之认识Java篇
转载自:偏头痛杨的Java入门教学系列 地址:https://blog.csdn.net/piantoutongyang/article/details/70138697 前戏 今天我们主要来介绍一下 ...
- 明翰Java教学系列之认识Java篇V1.3(持续更新)
文章目录 传送门 前言 什么是Java? Java之父 `Java的应用场景` Java部分特点 Java工作机制 JDK(Java Development Kit) JRE(Java Runtime ...
- 明翰Java教学系列之多线程篇V0.2(持续更新)
文章目录 传送门 前言 背景知识 并行与并发 线程与进程 内存模型 1. 计算机内存模型 `2. Java内存模型` 2.1 内存交互 2.1.1 交互操作 2.1.2 交互规则 `2.2 并发编程特 ...
- 明翰Java教学系列之集合框架篇V0.2(持续更新)
文章目录 传送门 前言 什么是集合框架 集合框架体系 Collection接口 `Set接口` `HashSet` LinkedHashSet TreeSet EnumSet Queue接口 Prio ...
- 明翰英语教学系列之方法篇
文章目录 传送门 前言 `学习路径&知识体系` 学习技巧 `构词规律` `词汇的偏旁部首` 词义前缀 否定前缀 `in-` mis- dis- de- un- con前缀 out前缀 sur前 ...
- 明翰英语教学系列之动词篇V0.3
文章目录 传送门 前言 1. 动词概念 2. `动词的分类` 2.1 按照功能分类 2.1.1 实义动词&行为动词 2.1.2 `系动词&联系动词` 系动词的分类 `状态系动词` `感 ...
- 明翰英语教学系列之数词篇V0.2(持续更新)
文章目录 传送门 什么是数词 基数词 基数词的单复数 序数词 数词应用 `表达[日期/时间]` 日期 年 月.日 年.月.日 `时间` 直接表达 间接表达 分数 小数 百分数 钱币 长度单位 重量单位 ...
- PHP on Windows Azure 入门教学系列(2) ——利用SQL Azure做一个简单的访问计数器...
公告:本博客为微软云计算中文博客的镜像博客.部分文章因为博客兼容性问题,会影响阅读体验.如遇此情况,请访问原博客. 本文是PHP on Windows Azure 入门教学系列第二篇文章.请上一篇文章 ...
- java重学系列之IO字节流
java重学系列之IO流 字符集和编码 IO概述 什么是IO IO的分类 顶级父类们 总结 字节流 一切皆为字节 字节输出流[OutputStream] FileOutputStream类 构造方法 ...
最新文章
- python画三维平面-Python 绘制酷炫的三维图步骤详解
- 安装Nginx1.14.2过程及配置
- 情怀成驱动力 网游改编手游能火多久?
- 【转】名企献身说法:我们喜欢这样的简历
- VIM之Project 项目管理工具
- Andrew Ng教你如何引领公司进入AI时代
- phpcms文章的发布时间改为可输入的文本框
- 黄冈中学首页布局(自己做的)
- vue-cli 中stylus写样式莫名报错?
- Android异常总结---ActivityManager: Warning: Activity not started,its current task has been brought to th
- java进制转换方法
- window server 2012 win7 远程桌面报错问题,无法远程
- python程序员工资待遇-为什么企业很难招聘到好的python程序员?
- KUI-金山界面库 自定义消息
- google即将进入游戏产业
- 文件查找,打包压缩,解压相关分享
- 用python绘制熊猫图案,在python中绘制熊猫系列的CDF
- Win10 用户管理中无法删除唯一的administrators组用户
- HASH查找算法—JAVA实现
- 互联网晚报 | 8月23日|共享充电宝涨至4元/小时;公安部辟谣2022红绿灯新国标:不存在;滴滴高德曹操首汽等11家公司被约谈...
热门文章
- SpringBoot实现Java高并发秒杀系统之Service层开发(二)
- docker bind source path does not exist: /etc/timezone“
- ai字母组合发音规律_使用和尚ai的俄语字母分类
- OSI七层网络、TCP/IP五层网络架构、二层/三层网络
- Android体系架构及认识
- Catching Cheaters
- 2022年Servlect课时十七——什么是监听器@@回顾过滤器@@Servlect
- 巴西龟饲养日志----养龟第二年开始
- 金大侠的亲属与剑桥大学最厉害的三个学院
- USB NCM usbnet 枚举流程代码分析