File类
看API
什么是输入和输出流
以程序为参照物
1.输入流:从文件输入到程序中,叫读操作(就是输入流)
2.输出流:从程序输入到文件中,叫写操作(就是输出流)
I/O流的分类
字节流
InputSteam输入流
输入字节流的顶级父类(超类)
ByteArrayInputStream
PipedInputStream
FilterInputStream
BufferedInputStream
DataInputStream
FileInputStream
ObjectInputStream
OutputStream输出流
输出字节流的顶级父类(超类)
ByteArrayOutputStream
PipedOutputStream
FilterOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
FileOutputStream
ObjectOutputStream
字符流
Reader
CharArrayReader
PipedReader
FilterReader
BufferedReader
InputStreamReader
FileReader
Writer
CharArrayWriter
PipedWriter
FilterWriter
BufferedWriter
OutputStreamWriter
FileWriter
PrintWriter
写i/o流步骤及注意事项
步骤:1.选择合适的I/O流
2.创建对象
3.传输数据
4.关闭流对象
注意事项:
1.在使用io流编程的时候,要对流进行关闭操作
2.当出现多个流对象的时候,进行关闭的时候,要根据创建流对象的顺序,进行倒序关闭
什么时候使用flush?
*什么时候使用flush?
* 最保险的方式,在输出流关闭之前每次都flush一下,然后再关闭
* 当某一个输出流对象中存在缓冲区的时候,就要进行flush;
序列化和反序列化
序列化:把对象转换为字节序列的过程称为对象序列化
反序列化:把字节序列恢复为对象的过程称为对象反序列化
什么情况下需要序列化
1.当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;
2.当你想用套接字在网络上传送对象的时候;
3.当你想通过RMI传输对象的时候;
如何实现序列化?
实现Serializable接口即可
transient关键字
1.变量前如果加上,可以阻止变量序列化到文件中,该变量被反序列化后,变量会被赋以初始值,例如:int-->0;
2.当一个父类实现序列化,那么子类会自动实现序列化,不需要显示序列化
3.当某个字段声明为transient后,默认序列化机制机制会忽略该字段
4.如果想要序列化这个字段,可以添加writeObject()和readObject()方法进行序列
【下面是各个类的演示代码:首先是字节输入\输出流】
File类:
package ioliu.zijie;
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) {
File file = new File("888.txt");
// try {
// file.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// System.out.println(file.canExecute());
// System.out.println(file.canRead());
// System.out.println(file.canWrite());
//删除由此路径名表示的文件或目录
file.delete();
//测试此抽象路径名表示的文件或目录是否存在
file.exists();
// File file1 = new File("8854.txt");
// try {
// file1.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
//if (file1.exists()){
// System.out.println("存在该文件,已经删除成功!");
// file1.delete();
//}else{
// System.out.println("不存在该文件!");
//}
// try {
// file.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
//返回该文件的绝对路径
System.out.println(file.getAbsoluteFile());
//当文件不存在时也会返回文件的绝对路径
File file1 = new File("sj54.txt");
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(file1.getAbsoluteFile());
//返回此路径的父类名称,如果没有父类就返回为null
System.out.println(file1.getParent());
System.out.println(file1.getPath());
//查看分割符
System.out.println(File.separator);
//查看是目录还是文件
if (file.isDirectory()){
System.out.println(file.getName() + "我是目录!");
}else if (file.isFile()){
System.out.println(file.getName()+"我是文件!");
}
//最后一次的修改时间
System.out.println(file.lastModified());
System.out.println(file1.length());
File file2 = new File("D:\\java\\Idea\\Idea_spacework");
String[] list = file2.list();
for (String s : list){
System.out.println(s);
}
System.out.println("*******************");
File[] files = file2.listFiles();
for(File f : files){
System.out.println(f.getAbsolutePath());
}
//创建目录
File file3 = new File("D:/1/2/3");
file3.mkdir();
// file3.delete();
//创建多级目录
file3.mkdirs();
FileDemo f = new FileDemo();
f.deletes(new File("D:\\1"));
//f.printFiles(new File("D:\\java\\Idea\\Idea_spacework\\Project"));
}
// //遍历D盘下idea的所有工作项目!
// public void printFiles(File file){
// //判断是文件还是目录,如果是目录继续进入目录获取文件列表
// File[] files = file.listFiles();
// //遍历目录中所有的文件
// for (File f :files){
// if(f.isDirectory()){
// //如果是目录,则需要再次进行遍历
// printFiles(f);
// }else if(f.isFile()){
// System.out.println(f.getAbsolutePath());
// }
// }
// }
//删除d盘中指定目录下所有的文件和目录
public void deletes(File file){
//判断是目录还是文件,如果是目录就继续进入,是文件就进行删除
File[] files = file.listFiles();
for (File f : files){
if (f.isDirectory()){
deletes(f);
f.delete();
}else if (f.isFile()){
f.delete();
}
file.delete();
}
}
}
ByteArrayInputStream:
package ioliu.zijie;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteArrayInputStreamDemo {
public static void main(String[] args) {
//自带缓冲区的意思就是他读取的就是str里面自己的内容
String str = "www.baidu.com百度";
byte[] buf = str.getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
//输出数据
int read = 0;
while((read = byteArrayInputStream.read())!=-1){
System.out.print((char) read);
}
//每次写完流 都要记得进行关流操作
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ByteArrayOutputStream:
package ioliu.zijie;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
//输出流 就是从程序中输入到目标文件中的操作 称为写操作(也叫输出流)
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) {
//这个类自带缓冲区所以就直接写到了自身中,所以读取的时候可以使用toString方法进行查看
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
arrayOutputStream.write(97);//返回的是ASCII码表的数值
try {
arrayOutputStream.write("www.alibaba.com阿里巴巴".getBytes());
System.out.println(arrayOutputStream.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
arrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
DataInputStream:
package ioliu.zijie;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutPutStreamDemo {
public static void main(String[] args) {
DataOutputStream dataOutputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("sj54.txt");
dataOutputStream = new DataOutputStream(fileOutputStream);
dataOutputStream.write(97);
dataOutputStream.writeChar('5');
dataOutputStream.writeDouble(100.56);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
DataOutPutStream:
package ioliu.zijie;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutPutStreamDemo {
public static void main(String[] args) {
DataOutputStream dataOutputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("sj54.txt");
dataOutputStream = new DataOutputStream(fileOutputStream);
dataOutputStream.write(97);
dataOutputStream.writeChar('5');
dataOutputStream.writeDouble(100.56);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
InputStream:(所有字节输出流的超类)
package ioliu.zijie;
import java.io.*;
import java.util.InputMismatchException;
/**
* 在java中需要读写文件中的数据的话,需要使用流的概念
* 流表示从一个文件将数据传送到另一个文件,包含一个流向的问题
* 最终需要选择一个参照物:当前程序作为参照物
* 从一个文件中读取数据到程序中的操作叫做读操作(也就是输入流)
* 从程序中输出数据到另一个文件的操作叫写操作(也就是输出流)
* 注意:
* 1.在使用io编写程序的时候,要对流进行关闭操作
* 2.当出现多个流对象的时候,进行关闭的时候,要根据创建流对象的顺序,进行倒序关闭
*/
//输入流
public class InputSteamDemo {
public static void main(String[] args) {
//创建一个新的文件
File file = new File("a.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//创建一个流的对象
InputStream inputStream = null;
try {
inputStream = new FileInputStream("a.txt");
//存在问题每次只能读取一个效率低
// int read = inputStream.read();
// System.out.println((char) read);
//存在问题,代码量虽然减少,但是还是一个一个的读取,效率低
// int read = 0;
// while ( (read = inputStream.read())!=-1){
// System.out.println((char) read);
// }
//使用缓冲区来存储读取到的数据,等缓冲区满的时候一次性输出
int length = 0;
byte[] buffer = new byte[2048];
while ((length = inputStream.read(buffer))!=-1){
System.out.println(new String(buffer,0,length));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream:(所有顶级字节输出流的超类)
package ioliu.zijie;
import java.io.*;
/**
输出流:
把程序中的输出到文件中
*/
public class OutputStreamDemo {
public static void main(String[] args) {
File file = new File("b.txt");
OutputStream oUtputStream = null;
//创建输出流的对象
try {
oUtputStream = new FileOutputStream(file);
//传入数据
oUtputStream.write(97);
oUtputStream.write("666java".getBytes());
oUtputStream.write("\r\na123456".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
oUtputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
PS:既然是对象字节流(处理流),n那么一定是会有一类类型的供我们使用
package ioliu.zijie;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = -1972306312535661910L;
private String id;
private String name;
private int age;
public Person() {
}
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
ObjectInputStream:
package ioliu.zijie;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectInputStreamDemo {
public static void main(String[] args) {
FileInputStream fileInputStream=null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = new FileInputStream("b.txt");
objectInputStream = new ObjectInputStream(fileInputStream);
int read = objectInputStream.read();
Person person=(Person)objectInputStream.readObject();
System.out.println((char) read);
System.out.println(person);
} 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();
}
}
}
}
ObjectOutputStream:
package ioliu.zijie;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class ObjectOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("b.txt",true);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.write(97);
objectOutputStream.writeObject(new Person("001","张飞",18));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【下面是字符输出流的类代码演示(均是成对出现,上面的字节也是如此)】
Reader:
package ioliu.zifu;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
//字符输入流
public class ReaderDemo {
public static void main(String[] args) {
Reader reader = null;
try {
//创建一个字符输入流的对象
reader = new FileReader("a.txt");
//有弊端,一个一个读取效率低
// int read =0;
// read = reader.read();
// System.out.println((char) read);
// read = reader.read();
// System.out.println((char) read);
// read = reader.read();
// System.out.println((char) read);
// int read =0;
// while (( read = reader.read())!=-1){
// System.out.println((char) read);
// }
// int length = 0;
// char[] buffer =new char[1024];
// while (( length = reader.read(buffer))!=-1){
// System.out.println(new String(buffer,0,length));
// }
int length= 0;
char[] buffer = new char[1024];
while((length = reader.read(buffer,0,5))!=-1){
System.out.println(new String(buffer,0,length));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Writer:
package ioliu.zifu;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
*什么时候使用flush?
* 最保险的方式,在输出流关闭之前每次都flush一下,然后再关闭
* 当某一个输出流对象中存在缓冲区的时候,就要进行flush;
*/
//字符输出流
public class WriterDemo {
public static void main(String[] args) {
File file = new File("b.txt");
Writer writer = null;
try {
//创建一个字符输出流对象
writer = new FileWriter(file);
int write = 0;
writer.write(97);
writer.write("我是傻逼!");
writer.write('l');
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferReader:
package ioliu.zifu;
import java.io.*;
public class BufferedReaderDemo {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader("a.txt");
bufferedReader = new BufferedReader(fileReader);
// int read= bufferedReader.read();
// System.out.println((char) read);
// int read = 0;
// char[] chars = new char[1024];
// while ((read = bufferedReader.read(chars))!=-1){
// System.out.println(new String(chars,0,read));
// }
//代码冗长
// String s = bufferedReader.readLine();
// System.out.println(s);
// String s1 = bufferedReader.readLine();
// System.out.println(s1);
// String s2 = bufferedReader.readLine();
// System.out.println(s2);
String s = "";
while ((s = bufferedReader.readLine()) != null) {
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//郑重提醒 记得关流
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferWriter:
package ioliu.zifu;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) {
FileWriter fileWriter = null;
BufferedWriter bufferedWriter= null;
try {
fileWriter = new FileWriter("d.txt");
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(97);
bufferedWriter.write("www.baidu.com百度".toCharArray());
bufferedWriter.newLine();
bufferedWriter.write("张继顺");
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CharArrayReader:
package ioliu.zifu;
import java.io.CharArrayReader;
import java.io.IOException;
//字符输入流
public class CharArrayReaderDemo {
public static void main(String[] args) {
String str = "www.baidu.com百度";
char[] chars = str.toCharArray();
CharArrayReader charArrayReader = new CharArrayReader(chars);
try {
int length = 0;
while ((length = charArrayReader.read())!=-1){
System.out.print((char)length);
}
// int read = charArrayReader.read();
// System.out.println((char) read);
} catch (IOException e) {
e.printStackTrace();
}finally {
charArrayReader.close();
}
}
}
CharArrayWriter:
package ioliu.zifu;
import java.io.CharArrayWriter;
import java.io.IOException;
public class CharArrayWriterDemo {
public static void main(String[] args) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
try {
charArrayWriter.write(97);
charArrayWriter.write("www.baidu.com".toCharArray());
charArrayWriter.write("dada");
charArrayWriter.append('s').append('d');
System.out.println(charArrayWriter.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
charArrayWriter.close();
}
}
}