File类
文件可认为是相关记录或放在一起的数据的集合
IO流的原理及概念
通过流来读写文件
– 流是指一连串流动的字符,是以先进先出方式发送信息的通道
IO流的分类
字节流和字符流
字节流
-
文件的读写
- 文本文件的读写
用FileInputStream和FileOutputStream读写文本文件 - 二进制文件的读写
使用DataInputStream和DataOutputStream读写二进制文件以及基本数据类型数据的读写 - 对象的读写
使用ObjectInputStream和ObjectOutputStream读写对象(序列化与反序列化)
- 文本文件的读写
-
InputStream类常用方法
– int read( )
– int read(byte[] b)
– int read(byte[] b,int off,int len)
– void close( )
– int available()
FileInputStream和FileOutputStream
- 子类FileInputStream常用的构造方法
– FileInputStream(File file)
– FileInputStream(String name)
- OutputStream类常用方法
– void write(int c)
– void write(byte[] buf)
– void write(byte[] b,int off,int len)
– void close( ) - 子类FileOutputStream常用的构造方法
– FileOutputStream (File file)
– FileOutputStream(String name)
– FileOutputStream(String name,boolean append)
1、前两种构造方法在向文件写数据时将覆盖文件中原有的内容
2、创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件
操作基本数据的流对象DataInputStream和DataOutputStream
- 写入数据
DataOutputStream dos=new DataOutputStream(new FileOutputStream(“data.txt”));
dos.writeInt(234);
dos.writeBoolean(false);
dos.writeDouble(9943.00);
dos.writeUTF(“中国”);
dos.close(); - 读取数据
DataInputStream dis=new DataInputStream(new FileInputStream(“data.txt”));
int num=dis.readInt();
boolean isFind=dis.readBoolean();
double price=dis.readDouble();
String str=dis.readUTF();
System.out.println(num+"\t"+isFind+"\t"+price+"\t"+str);
操作对象的流ObjectInputStream和ObjectOutputStream
- 序列化对象:ObjectOutputStream
- 反序列化对象:ObjectInputStream
- 序列化:
– ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(“obj.txt”));
– oos.writeObject(new Person(“张三”,19));// 序列化
– oos.close(); - 反序列化:
– ObjectInputStream ois=new ObjectInputStream(new FileInputStream(“obj.txt”));
– Person p=(Person)ois.readObject();//反序列化
– System.out.println§;
字符流
-
Reader类常用方法
– int read( )
– int read(byte[] c)
– read(char[] c,int off,int len)
– void close( )-
子类BufferedReader常用的构造方法
– BufferedReader(Reader in) -
子类BufferedReader特有的方法
– readLine() -
BufferedReader类
BufferedReader类是Reader类的子类
BufferedReader类带有缓冲区
按行读取内容的readLine()方法
-
-
Writer类常用方法
– write(String str)
– write(String str,int off,int len)
– void close()
– void flush()- 子类BufferedWriter常用的构造方法
– BufferedReader(Writer out) - BufferedWriter类
BufferedWriter类是Writer类的子类
BufferedWriter类带有缓冲区
- 子类BufferedWriter常用的构造方法
-
Reader和Writer的编码方式
- 获得当前开发环境的字符编码方式
+System.out.println(System.getProperty(“file.encoding”)); - 字符流的读写根据需要设置编码方式
涉及到的类:
读:FileReader (File file)
写:FileWriter(File file)
加入缓冲区的读:BufferedReader(Reader fr)
加入缓冲区的写:BufferedWriter(Writer bw)
- 获得当前开发环境的字符编码方式
总结
处理流和节点流
- 节点流:可以直接从数据源或目的地读写数据。
- 处理流(包装流):不直接连接到数据源或目的地,是其他流进行封装。目的主要是简化操作和提高性能。
- 节点流和处理流的关系
节点流处于io操作的第一线,所有操作必须通过他们进行
处理流可以对其他流进行处理(提高效率或操作灵活性)
File
package com.petrel;
import java.io.File;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/26 11:15
*/
public class FileDemo {
public static void main(String[] args) throws IOException {
File file = new File("src/abc.txt");
//创建文件
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//判断文件的属性,都会返回boolean类型的值
file.canExecute();
file.canRead();
file.canWrite();
//判断当前文件是否存在
System.out.println(file.exists());//运行结果:true
//获取文件的名称
System.out.println(file.getName());//运行结果:abc.txt
//获取文件的绝对路径
System.out.println(file.getAbsolutePath());//运行结果:F:\Java\io_demo\src\abc.txt
//获取文件的父路径名称,如果文件的路径中只包含文件名称,则显示空
System.out.println(file.getParent());//运行结果:src
//返回文件绝对路径的规范格式
System.out.println(file.getCanonicalPath());//运行结果:F:\Java\io_demo\src\abc.txt
//返回操作系统的文件分割符
System.out.println(File.separator);//运行结果:\
//无论当前文件是否存在,只要给定具体的路径,都可以返回相应的路径名称
File file2 = new File("F:\\Java\\io_demo/a/b/c");
System.out.println(file2.getAbsolutePath());//运行结果:c:\a\b\c
//判断文件是否是文件或者目录
System.out.println(file2.isDirectory());//运行结果:false 目录
System.out.println(file2.isFile());//运行结果:false 文件 false的原因:文件不存在
//输出包含的所有文件
//string类型字符串
File file3 = new File("F:\\Java");
String[] list = file3.list();
for(String str:list){
System.out.println(list.toString());//运行结果:[Ljava.lang.String;@4554617c......
}
System.out.println("---------------");
//具体的文件名称
File[] files = file3.listFiles();
for(File f : files){
System.out.println(f);//运行结果:F:\Java\CollectionDemo、F:\Java\CommonClass......
}
//File.listRoots().var 打印当前文件系统的所有盘符
File[] files1 = File.listRoots();
for(int i = 0;i<files1.length;i++){
System.out.println(files1[i]);//运行结果:C:\ D:\ E:\ F:\
}
//创建单级目录
file2.mkdir(); //运行结果:File file2 = new File("F:\\Java\\io_demo/a/b/c"); F:\\Java\\io_demo这个的文件下建立了一个a文件
//创建多级目录
file2.mkdirs();//运行结果:File file2 = new File("F:\\Java\\io_demo/a/b/c"); F:\\Java\\io_demo这个的文件下建立了a,b,c文件
//循环遍历输出C盘中的所有文件的绝对路径
//使用递归的方式
printFile(new File("F:\\Java\\dJAVA"));
}
/**
* 文件在遍历的时候,会出现空指针的问题,原因在于当前文件系统受保护,某些文件没有访问权限,此时会报空指针异常
* @param file
*/
public static void printFile(File file){
if(file.isDirectory()){
File[] files = file.listFiles();
for(File f:files){
printFile(f);
}
}else{
System.out.println(file.getAbsolutePath());
}
}
}
InputStream
package com.petrel.Stream;
/**
* @author Petrel
* @data 2020/6/26 12:13
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 在java中需要读写文件中的数据的话,需要使用流的概念
* 流表示从一个文件将数据返送到另一个文件,包含一个流向的问题
* 最终需要选择一个参照物:当前程序作为参照物
* 从一个文件中读取数据到程序叫做输入流
* 从程序输出数据到另一个文件叫做输出流
*
* 数据源:所有能存储数据的地方都可以当做数据源
*
* 注意:当编写io流的程序的时候一定要注意关闭流
* 步骤;
* 1、选择合适的io流对象
* 2、创建对象
* 3、传输数据
* 4、关闭流对象(占用系统资源)
*
*/
/*
* 存在问题,每次只能读取一个字节,效率比较低,需要循环N多次
* */
public class InputStreamDemo {
public static void main(String[] args) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("abc.txt");
/* int read = inputStream.read();//inputStream.read().var 每次读取一个字节
System.out.println((char)read);//运行结果:P */
//循环输出所有的字节
int read = 0; //read,这里是读取的字节的
while((read = inputStream.read())!=-1){
System.out.println((char)read);//运行结果:P e t r e l 这里不能识别中文 字节传输
}
//添加缓冲区的方式进行读取,每次会将数据添加到缓冲区中,当缓冲区满了之后,一次读取,而不是每一个字节进行读取
byte[] buffer = new byte[1024];
int lenght = 0; //这里的length是长度 6个长度 缓冲区占用的长度
while((lenght = inputStream.read(buffer))!=-1){
System.out.println(new String(buffer,0,lenght));//运行结果:Petrel (要先把上面的循环输出所有的字节注释)
}
/* //分块输出
byte[] buffer = new byte[1024];
int lenght = 0;
while((lenght = inputStream.read(buffer,2,2))!=-1) {
System.out.println(new String(buffer, 2, lenght)); //运行结果:Pe tr el (要先把上面的 循环输出所有的字节 和 添加缓冲区的方式进行读取, 注释)
}*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStream.close();//关闭流对象(占用系统资源) 不关闭的话一会就卡死了 因为文件使用有限制
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream
package com.petrel.Stream;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/26 16:35
*/
public class OutputStreamDemo {
public static void main(String[] args) {
File file = new File("aa.txt");
OutputStream outputStream = null; //将OutputStream提出来 方便最后的关闭流
try {
//OutputStream outputStream = new FileOutputStream(file);
outputStream = new FileOutputStream(file);
outputStream.write(99);
outputStream.write("Petrel".getBytes()); //运行结果:新建了一个aa.txt文件 文件中包含cPetrel
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件拷贝
package com.petrel.Stream;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/26 19:26
*/
public class CopyFile {
public static void main(String[] args) {
//定义源数据文件
File src = new File("abc.txt");
//定义目的数据文件
File dest = new File("aa.txt");
//创建输入流对象
InputStream inputStream = null;
//创建输出流对象
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(src);
outputStream = new FileOutputStream(dest);
//带缓存的输入输出方式
byte[] buffer = new byte[1024]; //长度自己任意给
int length = 0;
//完成数据传输的过程
while ((length = inputStream.read(buffer))!=-1){
outputStream.write(buffer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Reader
package com.petrel.readerOrWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* @author Petrel
* @data 2020/6/26 19:40
*/
/**
* 字符流可以直接读取中文汉字,而字节流在处理的时候会出现中文乱码
*/
public class ReaderDemo {
public static void main(String[] args) {
Reader reader = null;
try {
reader = new FileReader("abc.txt");
int read = reader.read();
System.out.println((char)read);//运行结果:P 这里可以识别中文 字符传输
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.petrel.readerOrWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* @author Petrel
* @data 2020/6/26 19:40
*/
/**
* ReaderDemo增加while循环 输出多个字符
*/
public class ReaderDemo2 {
public static void main(String[] args) {
Reader reader = null;
try {
reader = new FileReader("abc.txt");
int read = 0;
while ((read = reader.read())!=-1){ //字符读取,作为0到65535( 0x00-0xffff )范围内的整数,如果已经达到流的末尾,则为-1。
System.out.println((char)read);//运行结果:P e t r e l
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.petrel.readerOrWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* @author Petrel
* @data 2020/6/26 19:40
*/
/**
* ReaderDemo2增加缓冲区
*/
public class ReaderDemo3 {
public static void main(String[] args) {
Reader reader = null;
try {
reader = new FileReader("abc.txt");
int length = 0;
char[] chars = new char[1024];
//添加缓冲区
while ((length = reader.read(chars))!=-1){ //chars:缓冲数组
System.out.println(new String(chars,0,length));//运行结果:Petrel
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.petrel.readerOrWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* @author Petrel
* @data 2020/6/26 20:04
*/
/**
* 什么时候需要加flush,什么时候不加flush
* 最保险的方式,在输出流关闭之前每次都flush一下,然后再关闭
* 当某一个输出流对象中带有缓冲区的时候,就需要进行flush,不建议大家去记住每个输出流的分类
*
*/
public class WriteDemo {
public static void main(String[] args) {
File file = new File("writer.txt");
Writer writer = null;
try {
writer = new FileWriter(file);
writer.write("petrel");
writer.write("海燕");
writer.flush(); //加了flush 数据才传输到了文件中
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
图片拷贝
package com.petrel.readerOrWriter;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/26 20:13
*/
public class CopyPicture {
public static void main(String[] args) {
/*
*这里加载图片出现格式问题
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader("1.jpg");
writer = new FileWriter("2.jpg");
int length = 0;
char[] chars = new char[1024];
while ((length = reader.read(chars))!=-1){
writer.write(chars);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} */
//处理图片和视频及其他格式的文件的的时候推荐字节流 因为字节流是万能的
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("1.jpg");
fileOutputStream = new FileOutputStream("3.jpg");
int length = 0;
byte[] buffer = new byte[1024];
while ((length = fileInputStream.read(buffer))!=-1){
fileOutputStream.write(buffer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStreamWriter
package com.petrel.handlerStream;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/26 20:38
*/
public class OutputStreamWriterDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
OutputStreamWriter outputStreamWriter = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"utf-8");
outputStreamWriter.write(99);
outputStreamWriter.write("海燕");
outputStreamWriter.write("abcdef",0,5);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流对象的时候,建议按照创建的顺序的逆序来进行关闭
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
InputStreamReader
package com.petrel.handlerStream;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 9:29
*/
public class InputStreamReaderDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
try {
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream); //这里可以设置编码格式inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
//为什么没有用循环的方式,因为数据比较少,无法占用1024个缓存区,只需要读取一次即可
char[] chars = new char[1024];
int length = inputStreamReader.read(chars);
System.out.println(new String(chars,0,length));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ByteArrayInputStream
package com.petrel.streamtype;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/27 10:25
*/
public class ByteArrayInputStreamDemo {
public static void main(String[] args) {
String str = "asdfghjkl";
byte[] buffer = str.getBytes();
ByteArrayInputStream byteArrayInputStream = null;
byteArrayInputStream = new ByteArrayInputStream(buffer);
/* int read = byteArrayInputStream.read();
System.out.println((char)read);//运行结果:a*/
int read1 = 0;
while((read1 = byteArrayInputStream.read())!=-1){
byteArrayInputStream.skip(2);
System.out.println((char)read1); //运行结果:a f j
}
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ByteArrayOutputStream
package com.petrel.streamtype;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/27 10:43
*/
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) {
ByteArrayOutputStream byteArrayOutputStream = null;
byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(123);
try {
byteArrayOutputStream.write("zxcvbnm".getBytes());
System.out.println(byteArrayOutputStream.toString());//运行结果:{zxcvbnm {就是123
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedInputStream
package com.petrel.streamtype;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 11:17
*/
public class BufferedInputStreamDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
int read = 0;
while ((read = bufferedInputStream.read())!=-1){
bufferedInputStream.skip(4);//在缓冲区中 跳过指针的长度
System.out.print((char)read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedOutputStream
package com.petrel.streamtype;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/27 11:40
*/
public class BufferedOutputStreamDemo {
public static void main(String[] args) {
File file = new File("123.txt");
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(98);
bufferedOutputStream.write("qwertyuiop".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
DataInputStream、DataOutputStream
package com.petrel.streamtype;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 11:49
*/
public class DateDemo {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
FileOutputStream fileOutputStream = null;
try {
//向文件中写入数据流
fileOutputStream = new FileOutputStream("abc.txt");
dataOutputStream = new DataOutputStream(fileOutputStream);
dataOutputStream.writeBoolean(true);
dataOutputStream.writeInt(456);
dataOutputStream.writeShort(123);
dataOutputStream.writeDouble(2.22);
dataOutputStream.writeUTF("abc123海燕");
//从文件读取数据流
fileInputStream = new FileInputStream("abc.txt");
dataInputStream = new DataInputStream(fileInputStream);
System.out.println(dataInputStream.readBoolean());
System.out.println(dataInputStream.readInt());
System.out.println(dataInputStream.readShort());
System.out.println(dataInputStream.readDouble());//读取和写入顺序一致
System.out.println(dataInputStream.readUTF());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectOutputStream、ObjectInputStream
package com.petrel.streamtype;
import java.io.Serializable;
/**
* @author Petrel
* @data 2020/6/27 12:07
*/
/**
* 1、如果需要将对象通过io流进行传输,那么必须要实现序列化接口
* 2、当前类中必须声明一个serialVersionUID的值,值为多少无所谓,但是要有
* 3、transient:使用此关键字修饰的变量,在进行序列化的时候,不会别序列化
*
*/
public class Person implements Serializable { //序列化接口
long serialVersionUID = 1L;
private int id;
private String name;
//private String pwd;
transient private String pwd;//密码不可见
public Person() {
}
public Person(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.petrel.streamtype;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* @author Petrel
* @data 2020/6/27 12:07
*/
public class ObjectOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("abc.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeUTF("123海燕");
objectOutputStream.writeObject(new Person(1,"petrel","147"));
//运行结果:abc.txt文件中:�� w 123海燕sr com.petrel.streamtype.PersonO��� I idJ serialVersionUIDL namet Ljava/lang/String;xp t petrel
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.petrel.streamtype;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* @author Petrel
* @data 2020/6/27 12:26
*/
public class ObjectInputStreamDemo {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = new FileInputStream("abc.txt");
objectInputStream = new ObjectInputStream(fileInputStream);
System.out.println(objectInputStream.readUTF());
Object object = objectInputStream.readObject();
if (object instanceof Person){
Person p = (Person)object;
System.out.println(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CharArrayReader
package com.petrel.readerOrWriter;
import java.io.CharArrayReader;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/27 15:11
*/
public class CharArrayReaderTest {
public static void main(String[] args) {
char[] chars = "米菲".toCharArray();
CharArrayReader charArrayReader = new CharArrayReader(chars);
try {
int read = 0;
while((read = charArrayReader.read())!=-1){
System.out.println((char)read);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
charArrayReader.close();
}
}
}
CharArrayWriter
package com.petrel.readerOrWriter;
import java.io.CharArrayWriter;
/**
* @author Petrel
* @data 2020/6/27 15:28
*/
public class CharArrayWriterTest {
public static void main(String[] args) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
charArrayWriter.write(97);
charArrayWriter.write(98);
charArrayWriter.write(99);
System.out.println(charArrayWriter);
charArrayWriter.close();
}
}
BufferedReader
package com.petrel.readerOrWriter;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 15:32
*/
public class BufferedReaderTest {
public static void main(String[] args) {
//Reader reader = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("aa.txt"));
/**
* reader只有read()方法
int read = reader.read();
System.out.println((char) read);//运行结果:P
*/
//BufferedReader中的readLine()方法读取多个字符
/* String read = reader.readLine();
System.out.println(read);//运行结果:Petrel
read = reader.readLine();
System.out.println(read);//运行结果:Miffy */
//使用while循环简化代码
String read = null;
while((read = reader.readLine())!=null){
System.out.println(read);//运行结果:Petrel Miffy
};
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedWriter
package com.petrel.readerOrWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author Petrel
* @data 2020/6/27 15:48
*/
public class BufferedWriterTest {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(new File("abc.txt"));
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("miffy");
bufferedWriter.newLine();//换行
bufferedWriter.append("米菲");
bufferedWriter.flush();
//运行结果:abc.txt中:miffy 米菲
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
PrintStream
package com.petrel.readerOrWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
* @author Petrel
* @data 2020/6/27 16:44
*/
public class PrintStreamTest {
public static void main(String[] args) {
PrintStream printStream = null;
try {
printStream = new PrintStream(new FileOutputStream("123.txt"));
printStream = new PrintStream(System.out);
printStream.write("petrel".getBytes());//运行结果:petrel
printStream.println(true);//运行结果:true 就相当于输出
System.out.println();
//格式化输出 %s:字符串 %d:整数 %f:浮点数
System.out.printf("%s %d %f","abc",123,2.22);//运行结果:abc 123 2.220000
//错误输出
System.err.println("错误");//运行结果:错误(标红)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关闭io流
package com.petrel.exercise;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 15:57
*/
public class ExitTest {
public static void main(String[] args) {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = "";
try {
while (!str.equals("exit")){
str = bufferedReader.readLine();
bufferedWriter.write(str);
bufferedWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.petrel.exercise;
import java.io.*;
/**
* @author Petrel
* @data 2020/6/27 15:57
*/
public class ExitTest1 {
public static void main(String[] args) {
//好处:不用关闭io流 会自动关闭
try (InputStreamReader inputStreamReader = new InputStreamReader(System.in);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);){
String str = "";
while (!str.equals("exit")){
str = bufferedReader.readLine();
bufferedWriter.write(str);
bufferedWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
拷贝百度网页
package com.petrel.exercise;
import java.io.*;
import java.net.URL;
/**
* @author Petrel
* @data 2020/6/27 16:19
*/
public class BaiDuTest {
public static void main(String[] args) {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8"));
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu.html")));
String msg = null;
while ((msg = bufferedReader.readLine())!=null){
bufferedWriter.write(msg);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件切块
package com.petrel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author Petrel
* @data 2020/6/27 17:08
*/
public class RandomAccessFileTest {
public static void main(String[] args) {
File file = new File("doc.txt");
//整个文件的大小
long length = file.length();
//规定块的大小
int blockSize = 1024;
//文件可以被切分成多少个块
int size = (int)Math.ceil(length*1.0/blockSize);
System.out.printf("要被切成《%d》个块",size);
int beginPos = 0;
int actualSize = (int)(blockSize>length?length:blockSize);
for(int i = 0;i<size;i++){
//每次读取块的时候的起始偏移量
beginPos = i*blockSize;
if(i==size-1){ //如果是最后一个块
actualSize = (int) length;
}else{
actualSize = blockSize; //保证最后一个块可以被读取
length -=actualSize;
}
System.out.println(i+"---》起始位置是:"+beginPos+"---->读取的大小是:"+actualSize);
// readSplit(i,beginPos,actualSize); //显示内容
}
}
public static void readSplit(int i,int beginPos,int actualSize){
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(new File("doc.txt"),"r");
//表示从哪个偏移量开始读取数据
randomAccessFile.seek(beginPos);
byte[] bytes = new byte[1024];
int length = 0;
while((length = randomAccessFile.read(bytes))!=-1){
if(actualSize>length){
System.out.println(new String(bytes,0,length));
actualSize-=length;
}else{
System.out.println(new String(bytes,0,actualSize));
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
commons-io工具类
package com.petrel.commonsio;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.EmptyFileFilter;
import java.io.File;
import java.util.Collection;
/**
* @author Petrel
* @data 2020/6/28 10:09
*/
// 导入commons-io-2.6.jar包
// 有很多方法
public class Commons_ioTest {
public static void main(String[] args) {
//判断文件的大小
long length = FileUtils.sizeOf(new File("abc.txt"));
System.out.println(length); //运行结果:135
//指定当前的目录
Collection<File> files = FileUtils.listFiles(new File("c:"), EmptyFileFilter.NOT_EMPTY, null);
for (File file:files){
System.out.println(file.getAbsolutePath());//运行结果:c:\\BOOTNXT......
}
}
}