文件操作
Java流简介
文件File的使用
FileOutputStream和FileInputStream的使用
FileWriter和FileReader的使用
ObjectOutputStream和ObjectInputStream的使用
BufferedOutputStream和BufferedInputStream的使用
BufferedWriter和BufferedReader的使用
PrintStream和PrintWriter的使用
一.Java流(Stream)
Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。
流Stream,封装数据的写入写出,统一管理数据的写入和读取
一个流可以理解为一个数据的序列。流的方向,参考的是自己的内存空间-代码的位置是内存空间。
输出流:从内存空间将数据写到外部。
输入流:将外部数据写到内存中。
粉红色是类型归纳,绿色是接口,黄色是类
字节流类型通过byte[]数组,接受数据或者保存数据。
字符流类型通过char[]数组,接受数据或者保存数据。
二.文件File
1.构造方法
//通过将给定的路径名字符串转换为抽象路径名来创建 File(String pathname) //从父抽象路径名和子路径名字符串创建 File(File parent, String child) //从父路径名字符串和子路径名字符串创建 File(String parent, String child) //通过将给定的 file: URI转换为抽象路径名来创建 File(URL uri)2.具体的方法
- 测试此抽象路径名表示的文件或目录是否存在。
public boolean exists()
- 当且仅当具有该名称的文件尚不存在时,原子地创建一个由该抽象路径名命名的新的空文件。
public boolean createNewFile() throws IOException
- 测试此抽象路径名表示的文件是否为目录。
public boolean isDirectory()
- 测试此抽象路径名表示的文件是否为普通文件。
public boolean isFile()
- 删除由此抽象路径名表示的文件或目录。 如果此路径名表示目录,则目录必须为空才能删除。
public boolean delete()
- 创建由此抽象路径名命名的目录。
public boolean mkdir()
- 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。请注意,如果此操作失败,它可能已成功创建一些必需的父目录。
public boolean mkdirs()
- 返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件。如果此抽象路径名不表示目录,则此方法返回null 。
public File[] listFiles()
- 返回一个抽象路径名数组,表示由此抽象路径名表示的满足指定过滤器的目录中的文件和目录。
public File[] listFiles(FilenameFilter filter)
- 创建例子
String path = "G:/Android_Studio"; //方式1 File file = new File(path.concat("/1.txt")); //方式2 File file = new File(path,"1.txt"); //判断是否存在 if (file.exists() == false){ //不存在就创建 file.createNewFile(); }
三.FileOutputStream和FileInputStream的使用
FileOutputStream
1.构造方法
第二个参数默认是false,写入是覆盖写入;true表示追加方式写入。
//创建文件输出流以指定的名称写入文件。 FileOutputStream(String name) //创建文件输出流以指定的名称写入文件。 FileOutputStream(String name, boolean append) // 创建文件输出流以写入由指定的 File对象表示的文件。 FileOutputStream(File file) //创建文件输出流以写入由指定的 File对象表示的文件 FileOutputStream(File file, boolean append)2.写入数据方法
//将 b.length字节从指定的字节数组写入此文件输出流。 public void write(byte[] b) throws IOException //从位于偏移量 off的指定字节数组写入 len字节到该文件输出流。 public void write(byte[] b int off, int len) throws IOException3.关闭连接方法
//关闭此文件输出流并释放与此流相关联的任何系统资源。 此文件输出流可能不再用于写入字节。 public void close() throws IOException4.清空流,把缓冲区的内容强制的写出
flush
FileInputStream
1.构造方法
//通过打开与实际文件的连接来创建一个 FileInputStream //该文件由文件系统中的路径名 name命名。 FileInputStream(String name) // 通过打开与实际文件的连接创建一个 FileInputStream //该文件由文件系统中的 File对象 file命名。 FileIntputStream(File file)2.读取数据方法
//返回值是读取到缓冲区的总字节数;如果为-1,达到文件末尾 //从该输入流读取最多b.length字节的数据到字节数组。 public int read(byte[] b) throws IOException //从该输入流读取最多len字节的数据到字节数组,起始索引从off开始。 public int read(byte[] b int off,int len) throws IOException3.关闭连接方法
//关闭此文件输入流并释放与流相关联的任何系统资源。 // 如果该流具有相关联的信道,则该信道也被关闭。 public void close() throws IOException
FileOutputStream和FileInputStream的具体使用
String path = "G:/Android_Studio/AndroidStudioProjects/JavaCode/Java/src/main/java/swu/xl/day8/Base"; File file = new File(path.concat("/1.txt")); //判断是否存在 if (file.exists() == false){ //不存在就创建 file.createNewFile(); } //1.创建文件输出流对象 FileOutputStream fos = new FileOutputStream(file); //2.调用write方法写入 byte[] bytes = {'a','b','c'}; fos.write(bytes); //3.把缓冲区的内容强制写出,确保缓冲区没有东西 fos.flush(); //4.操作完毕需要关闭Stream对象 fos.close(); FileInputStream fis = new FileInputStream(file); //2.调用read方法写入 byte[] names = new byte[12]; int count = fis.read(names); fis.close(); System.out.println(count+" "+(new String(names)));
四.FileWriter和FileReader的使用
FileWriter
1.构造方法
第二个参数默认是false,写入是覆盖写入;true表示追加方式写入。
//构造一个给定文件名的FileWriter对象。 FileWriter(String fileName) //构造一个给定文件名的FileWriter对象。 FileWriter(String fileName, boolean append) //给一个File对象构造一个FileWriter对象。 FileWriter(File file) //给一个File对象构造一个FileWriter对象。 FileWriter(File file, boolean append)2.写入数据方法
//写入字符数组 public void write(char[] cbuf) throws IOException //写入字符数组的一部分。 public void write(char[] cbuf,int off,int len) throws IOException // 写一个字符串 public void write(String str) throws IOException // 写一个字符串的一部分。 public void write(String str, int off, int len) throws IOException3.关闭连接方法
//关闭此文件输出流并释放与此流相关联的任何系统资源。 此文件输出流可能不再用于写入字节。 public void close() throws IOException4.清空流,缓冲区的内容强制的写出
flush
FileReader
1.构造方法
//创建一个新的 FileReader ,给定要读取的文件的名称。 FileReader(String name) //创建一个新的 FileReader ,给出 File读取。 FileIReader(File file)2.读取数据方法
//将字符读入数组 public int read(char[] cbuf) throws IOException //将字符读入数组的一部分。 public int read(char[] cbuf, int offset, int length) throws IOException3.关闭连接方法
//关闭此文件输入流并释放与流相关联的任何系统资源。 // 如果该流具有相关联的信道,则该信道也被关闭。 public void close() throws IOException
FileWriter和FileReader的具体使用
String path = "G:/Android_Studio/AndroidStudioProjects/JavaCode/Java/src/main/java/swu/xl/day8/Base"; File file = new File(path.concat("/1.txt")); //判断是否存在 if (file.exists() == false){ //不存在就创建 file.createNewFile(); } //1.创建文件输出流对象 FileWriter fw = new FileWriter(file); //2.调用write方法写入 char[] name = {'安','桌','开','发'}; fw.write(name); //String string = new String("sac"); //fw.write(string); //3.把缓冲区的内容强制写出,确保缓冲区没有东西 fw.flush(); //4.操作完毕需要关闭Stream对象 fw.close(); FileReader fr = new FileReader(file); char[] book = new char[4]; count = fr.read(book); fr.close(); System.out.println(count+" "+(new String(book)));
五.ObjectOutputStream和ObjectInputStream
ObjectOutputStream和ObjectInputStream用于向文件中写入对象,类似于iOS的NSKeyedArchiver和NSKeyedUnarchiver对数据的归档和解档。类比iOS对自定义的类创建出来的对象进行归档,我们需要先实现
NSCoding协议。Java里面需要对自定义的类实现
serializable接口实现序列化,该接口没有任何方法。如果自定义的类内部还有属性变量是其他自定义的类的对象,这个类也必须实现
Seriablizable接口
ObjectOutputStream和ObjectInputStream都需要传入一个OutputStream和InputStream类型的对象,它们是抽象类,所以使用子类FileOutputStream和FileInputStream来实现初始化。具体使用
//序列化好的类 import java.io.Serializable; public class Person implements Serializable { String name; int age; } //file和之前的例子相同 //具体写入 Person xw = new Person(); xw.name = "小王"; xw.age = 18; OutputStream os = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(xw); oos.close(); //具体读取 InputStream is = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(is); Person xw = (Person) ois.readObject(); System.out.println(xw.name+" "+xw.age); ois.close();
六.BufferedOutputStream和BufferedInputStream
BufferedOutputStream和BufferedInputStream类的构造函数都需要传入一个OutputStream或InputStream类型的对象,它们是抽象类,所以使用子类FileOutputStream或FileInputStream来实现初始化。数据覆盖写入的意思是下一次运行写入是覆盖写入,
RandomAccessFile有类似于C语言文件操作中seek,如果你想要可以读取文件的任意位置可以使用它。具体使用:将图片复制到指定位置。
//1.源文件的路径 String sourcePath = "C:/Users/a2867/Desktop/壁纸/1.jpg"; //2.目标文件的路径 String desPath = "C:/Users/a2867/Desktop/1.jpg"; FileInputStream fis = new FileInputStream(sourcePath); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(desPath); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] in = new byte[1024]; int count = 0; while((count = bis.read(in)) != -1){ bos.write(in,0,count); } bis.close(); bos.flush(); bos.close();
七.BufferedWriter和BufferedReader的使用
BufferedWriter和BufferedReader类的构造函数都需要传入一个OutputStreamWriter或InputStreamReader类型的对象。
OutputStreamWriter和InputStreamReader类的构造函数都需要传入一个OutputStream或InputStream类型的对象。
public readLine() throws IOException读一行文字。 一行被视为由换行符('\ n'),回车符('\ r')中的任何一个或随后的换行符终止。具体使用:将图片复制到指定位置。
//1.源文件的路径 String sourcePath = "C:/Users/a2867/Desktop/壁纸/1.jpg"; //2.目标文件的路径 String desPath = "C:/Users/a2867/Desktop/1.jpg"; FileInputStream fis = new FileInputStream(sourcePath); BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); FileOutputStream fos = new FileOutputStream(desPath); BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(fos)); char[] in = new char[1024]; int count = 0; while((count = bis.read(in)) != -1){ bos.write(in,0,count); } bis.close(); bos.flush(); bos.close(); //结果不对,对于这种图片,视频等操作建议使用字节流方式,不然很可能出错具体使用:读取控制台输入(Java 的控制台输入由 System.in 完成)
public class BRReadLines { public static void main(String args[]) throws IOException { // 使用 System.in 创建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do { str = br.readLine(); System.out.println(str); } while (!str.equals("end")); } } 输出: Enter lines of text. Enter 'end' to quit. This is line one This is line one This is line two This is line two end end
八.PrintStream和PrintWriter的使用
PrintStream
Java的控制台的输出由
print()和println()完成。这些方法都由类PrintStream定义,System.out是该类对象的一个引用。
PrintStream继承了OutputStream类,并且实现了方法write()。这样,write()也可以用来往控制台写操作。
write()方法不经常使用,因为print()和println()方法用起来更为方便。
format()使用指定的格式字符串和参数将格式化的字符串写入此输出流。
append()将指定的字符或者字符序列附加到此输出流。
checkError()刷新流并检查其错误状,因为该输出流不会抛异常。
clearError()清除此流的内部错误状态。。
flush()刷新流。
close()关闭流。具体使用:向控制台输出
public class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } } 输出: APrintWriter
构造方法:
public PrintWriter(Writer out,boolean autoFlush)其他方法和PrintStream类似
PrintStream和PrintWriter的区别
PrintStream操纵的是字节流,PrintWriter操纵的是字符流。
PrintStream在遇到换行符的时候就会自动刷新,即在调用了println()方法,或者文本中出现“\n”,就会自动flush。
PrintWriter需要在构造方法中设置自动刷新,或者手动flush。
