文件与流:
Java执行文件读写操作都是通过对象实现的,读取数据的对象称为输入流(input stream),写入数据的对象称为输出流(output stream)。
文件管理:
概述:Java中的对文件的管理,通过java.io包中的File类实现。Java中文件的管理,主要是针对文件或是目录路径名的管理,包括文件的属性信息,文件的检查,文件的删除等,但不包括文件的访问。
File类:
File类的构造方法:
public java.io.File(String pathName)
File file = new File("E:/aaa.txt");
第一个构造方法通过全路径文件名来创建对象,pathName可以是绝对路径也可以是相对的。
public java.io.File(String parent,String fileName)
File file1 = new File("E:/io", "test.txt");
第二个构造方法通过父目录和文件名来创建对象,fileName是不含路径的文件名。
public java.io.File(File parent,String fileName)
File file2 = new File("E:/io"); File file3 = new File(file2, "test.txt");
第三个构造方法也是通过父目录和文件名来创建对象,但父目录由一个File对象提供。
File类常用方法:
boolean exists() 判断文件是否存在
boolean canRead() 文件是否可读
boolean canWrite() 文件是否可写
String getName() 获取文件名
String getPath() 获取文件路径
long length() 返回文件大小
boolean createNewFile() 用来创建文件
boolean delete() 用来删除文件
boolean mkdirs() 创建文件目录(一次性创建多层文件夹)
File[] listFiles() 返回指定目录中所有子文件构成的File数组
File file = new File("E:/aaa.txt"); if(file.exists()){ System.out.println(file.canRead()?"可读":"不可读"); System.out.println(file.canWrite()?"可写":"不可写"); System.out.println(file.getAbsolutePath()); System.out.println(file.getPath()); System.out.println(file.getName()); System.out.println(file.length()); }else{ System.out.println("不存在"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ----------------------------------------------------------------- 可读 可写 E:\aaa.txt E:\aaa.txt aaa.txt 0
//创建多层文件 File file = new File("E:/f1/f2/f3"); if(!file.exists()){ file.mkdirs(); }
流的概念及API
流的分类
按照传输方向的不同:
输入流(读):
输出流(写):
按照传输单位不同:
字节流:
字符流:
按照功能的不同:
节点流:
处理流:
与节点流相比多用处理流
字节流(输入):
节点流:FileInputStream
处理流:BufferedInputStream DataInputStream ObjectInputStream
字节流(输出):
节点流:FileOutputStream
处理流:BufferedOutputStream DataOutputStream ObjectOutputStream
字符流(输入):
节点流:FileReader
处理流:BufferedReader
字符流(输出):
节点流:FileWriter
处理流:BufferedWriter
对象的序列化 对象的反序列化
//把一个文件的内容复制到另一个文件中 BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream("e:/resource.txt")); bos = new BufferedOutputStream(new FileOutputStream("e:/destination.txt")); int b = bis.read(); while(b!=-1){ bos.write(b); b = bis.read(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } }
--2021.4.19
原文:https://www.cnblogs.com/SheepDog/p/14678498.html