目录
File类的常用方法
构造方法 | |
File ( File parent,String child ) | 从父抽象路径名和子路径名字符串创建新的 File实例 |
File ( String pathname ) | 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例 |
File ( String parent ,String child ) | 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例 |
File( URL uri) | 通过将给定的 file: URI转换为抽象路径名来创建新的 File实例 |
文件判断 | |
public boolean canRead() | 测试应用程序是否可以读取由此抽象路径名表示的文件 |
public boolean canWrite() | 测试应用程序是否可以修改由此抽象路径名表示的文件 |
public boolean exists() | 测试此抽象路径名表示的文件或目录是否存在 |
public boolean isDirectory() | 测试此抽象路径名表示的文件是否为目录 |
public boolean isFile() | 测试此抽象路径名表示的文件是否为普通文件 |
public boolean isHidden() | 测试此抽象路径名命名的文件是否为隐藏文件 |
获取文件的信息 | |
public long lastModified() | 返回此抽象路径名表示的文件上次修改的时间 |
public long length() | 返回由此抽象路径名表示的文件的长度 |
public String getName() | 返回由此抽象路径名表示的文件或目录的名称 |
public String getPath() | 将此抽象路径名转换为路径名字符串 |
public String getAbsolutePath() | 返回此抽象路径名的绝对路径名字符串 |
public File getAbsoluteFile() | 返回此抽象路径名的绝对形式 |
public String getParent() | 返回此抽象路径名的父 null的路径名字符串,如果此路径名未命名为父目录,则返回null |
文件基本操作 | |
public boolean createNewFile() throws IOException | 当且仅当具有该名称的文件尚不存在时,原子地创建一个由该抽象路径名命名的新的空文件 |
public boolean delete() | 删除由此抽象路径名表示的文件或目录 |
public void deleteOnExit() | 请求在虚拟机终止时删除由此抽象路径名表示的文件或目录 |
public boolean mkdir() | 创建由此抽象路径名命名的目录 |
public boolean mkdirs() | 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录 |
public boolean renameTo(File dest) | 重命名由此抽象路径名表示的文件 |
文件列表 | |
public String[] list() | 返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录 |
public File[] listFiles() | 返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件 |
public File[] listFiles(FilenameFilter filter) | 该方法的行为与listFiles()方法的行为相同,只是返回的数组中的路径名必须满足过滤器 |
package packagepath;
import java.io.File;
import java.io.FilenameFilter;
//关于listFiles()和listFiles(new FilenameFilter(){accept})的使用示例
public class ListFilesDemo {
public static void main(String[] args) {
// showFiles("filename");
filterFiles("filename");
}
// 显示目录下的文件
public static void showFiles(String path) {
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
if (f.isDirectory()) {
showFiles(f.getPath());
}
}
}
// 过滤后缀为.chm文件
public static void filterFiles(String path) {
FilenameFilter filter = (dir, name) -> name.endsWith(".chm");
File[] files = new File(path).listFiles(filter);
for (File f : files)
System.out.println(f);
}
}
文件流(Stream)的处理
- 流的逻辑概念
- 相当于数据传输的通道,属于底层的资源,使用完成后需要释放资源
- 流的分类
- 按流的方向
- 输入流 InputStream Reader
- 输出流 OutputStream Writer
- 按数据单元
- 字节流 字节流操作的数据单元是8 位的字节 二进制数据 InputStream OutputStream
- 字符流 字符流操作的数据单元是16位的字符 对字符性能方面提升 Reader Writer
- 按功能分类
- 节点流 最基本的文件流 直接和底层文件关联
- 处理流 必须在节点流的基础上创建|包装 > 修饰器设计模式
-
流的基础用法
- InputStream > FileInputStream
- 方法
- int read() 逐个字节读取 ,并返回读取的内容(int单个字节) IO的频率最高
- int read( byte[] ) 一次读取字节到byte[]数组中,并返回读取的数据长度
-
//read() private void read1() { InputStream is = null; try { is = new FileInputStream(filePath); int c = 0; do { c = is.read(); System.out.print((char) c); } while (c != -1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } //read(byte) private void read2() { InputStream is = null; try { is = new FileInputStream(filePath); byte[] b = new byte[1024]; int len = 0; do { len = is.read(b); for (int i = 0; i < len; i++) { System.out.print((char) b[i]); } } while (len != -1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } }
- 方法
- OutputStream > FileOutputStream
- 方法
- void write( int i ) 单个字节写入
- void write( byte[] ) 写入一批字节
-
/** * write(byte) write() * @param str 写入内容 */ private void write1(String str) { OutputStream ops = null; try { ops = new FileOutputStream(filePath, true); // int ops.write((char) 65); // String ops.write(str.getBytes()); // String offset length ops.write(str.getBytes(), 0, str.length()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ops.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 方法
- Reader > FileReader
- 方法
- int read()
- int read( char[] )
-
private void read1() { Reader r = null; try { r = new FileReader(new File("iotest.txt")); char[] buffer = new char[1024]; StringBuffer sb = new StringBuffer(); while (true) { int len = r.read(buffer); if (len == -1) break; sb.append(buffer, 0, len); } System.out.println(sb.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { r.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 方法
- Writer > FileWriter
- 方法
- void write( int i )
- void write( String str )
-
private void write1() { Writer w = null; try { /* * FileWriter(File file, boolean append) * 参数append为true时,则续写反之重写 */ w = new FileWriter(new File("iotest.txt"), true); char[] cbuf = "\nbyteTest".toCharArray(); String str = "\nHelloWorld3.......\r\n你好世界"; // int w.write(65); // char[] w.write(cbuf); // char[] offset length w.write(cbuf, 0, cbuf.length); // String w.write(str); // String offset length w.write(str, 0, str.length()); // 清除缓存 w.flush(); } catch (IOException e) { e.printStackTrace(); } finally { // close在調用時會調用flush try { w.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 方法
-
综合
private void copyText(String readFilePath,String writeFilePath) { Reader read = null; Writer write = null; try { read = new FileReader(new File(readFilePath)); write = new FileWriter(new File(writeFilePath)); char[] buffer = new char[1024]; int len = 0; while ((len = read.read(buffer)) != -1) { write.write(buffer, 0, len); write.flush(); } System.out.println("copy complete"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { read.close(); write.close(); } catch (IOException e) { e.printStackTrace(); } } } private void copyImage(String readFilePath,String writeFilePath) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(new File(readFilePath)); out = new FileOutputStream(new File(writeFilePath)); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); out.flush(); } System.out.println("copy complete"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
- InputStream > FileInputStream
-
缓冲流
- 特点
- 不能单独创建,必须借助节点流创建
- 类别
- BufferedInputStream > int read read( byte offset length ) 数据读取到末尾时返回-1
- BufferedOutputStream > void write weite(byte offset length)
- 综合
private void copyFile() { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream("iotest2.txt")); bis = new BufferedInputStream( new FileInputStream("iotest.txt")); byte[] arr = new byte[1024]; int len = -1; while ((len = bis.read(arr)) != -1) { bos.write(arr, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 综合
- BufferedReader > readLine数据读取到末尾时返回null
-
private void bufferRead() { BufferedReader br = null; try { FileReader r = new FileReader( new File("iotest.txt")); br = new BufferedReader(r); MyBufferedReader mb = new MyBufferedReader(r); String str = null; // while ((str = mb.myReadLine()) != null) { while ((str = br.readLine()) != null) { System.out.println(str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
- BufferedWriter > 写入后需要刷新flush,关闭前会先刷新
-
public void bufferWrite() { BufferedWriter bw = null; try { bw = new BufferedWriter( new FileWriter("iotest2.txt")); bw.write("bufferWrite重写"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
- 特点
-
转换流
- 类别
- public class OutputStreamWriter extends > WriterOutputStreamWriter ( OutputStream out )
- public class InputStreamReader extends > ReaderInputStreamReader ( InputStream in )
-
//在控制台输入字符回车后,打印大写字符 private void test1() throws IOException { InputStream is = System.in; OutputStream ou = System.out; BufferedReader br = new BufferedReader( new InputStreamReader(is)); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(ou)); String line = null; while ((line = br.readLine()) != null) { if ("end".equals(line)) break; bw.write(line.toUpperCase()); bw.newLine(); bw.flush(); } br.close(); bw.close(); } //在控制台输入字符回车后,打印大写字符在文件中 private void test2() throws IOException { InputStream is = System.in; BufferedReader br = new BufferedReader( new InputStreamReader(is)); BufferedWriter bw = new BufferedWriter( new FileWriter("iotest.txt")); String line = null; while ((line = br.readLine()) != null) { if ("end".equals(line)) break; bw.write(line.toUpperCase()); //newLine()可跨平台换行 bw.newLine(); bw.flush(); } br.close(); bw.close(); } //读取文件中字符,打印到控制台中 private void test3() throws IOException { OutputStream ou = System.out; BufferedReader br = new BufferedReader( new FileReader("iotest.txt")); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(ou)); String line = null; while ((line = br.readLine()) != null) { if ("end".equals(line)) break; bw.write(line.toUpperCase()); bw.newLine(); bw.flush(); } br.close(); bw.close(); } private void test4() throws IOException { InputStream is = System.in; OutputStream ou = System.out; BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream(ou); byte[] buffer = new byte[1024]; bis.read(buffer); bos.write(buffer); bos.close(); }
- 类别
-
打印流
- PrintWriter(OutputStream out, boolean autoFlush) autoFlush为true,自动刷新
private void test1() throws IOException { InputStream is = System.in; PrintWriter out = new PrintWriter(System.out, true); BufferedReader br = new BufferedReader( new InputStreamReader(is)); String str = null; while ((str = br.readLine()) != null) { if ("end".equals(str)) break; out.println(str.toUpperCase()); } out.close(); br.close(); }
- PrintWriter(OutputStream out, boolean autoFlush) autoFlush为true,自动刷新
-
内存流
- 特点
- io 的行为并不是对文件进行操作,而是对内存中byte[]数组进行操作
- byte[ ] 在程序中,是一个临时存放数据的空间,并不是底层的资源,所以并不需要关闭流
- 类别
- ByteArrayInputStream(byte[] buf)
- ByteArrayOutputStream()
-
// 将bos读取到的input中的内容,写入bais中toString返回输出 public String getTextByInputStream(InputStream input) { BufferedInputStream bos = null; ByteArrayOutputStream bais = null; try { bos = new BufferedInputStream(input); bais = new ByteArrayOutputStream(); int len = -1; while ((len = bos.read()) != -1) { bais.write(len); } } catch (IOException e) { e.printStackTrace(); } finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } return bais.toString(); } private void test1() { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { // 将图片文件读取,存入到内存流中 bis = new BufferedInputStream( new FileInputStream("image.png")); bos = new BufferedOutputStream( new FileOutputStream("copyimage.png")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int i = -1; // while ((i = bis.read()) != -1) { // baos.write(i); // } while ((i = bis.read(buffer)) != -1) { baos.write(buffer, 0, i); } System.out.println("完成存入内存操作"); // 将内存流中的图片读取,写入到文件中 ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); int j = -1; while ((j = bais.read()) != -1) { bos.write(j); } System.out.println("完成磁盘写入操作"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 特点
-
对象流
- 序列化:把对象状态(内部数据等)保存到某种介质中,该介质可以是文件、网络等
- 反序列化:从介质中根据所保存的对象状态信息,重构对象
- 类别
- ObjectInputStream(InputStream in) 将对象保存到二进制文件中序列化(串行化)
- ObjectOutputStream (OutputStream out) 在二进制文件中查找对象进行反序列化(并行化)
-
private void readObject() { ObjectInputStream ois = null; try { ois = new ObjectInputStream( new FileInputStream("iotest2.bin")); Person person = (Person) ois.readObject(); System.out.println("——重构对象完成——"); System.out.println(person); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void writeTo(Person person) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream( new FileOutputStream("iotest2.bin")); oos.writeObject(person); System.out.println("——写入对象完成——"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } //只有支持java.io.Serializable接口的对象才能写入流中 //只能从流中读取支持java.io.Serializable或 java.io.Externalizable接口的对象 public class Person implements Serializable { private static final long serialVersionUID = 1293810121342278585L; private String name; private String sex; public Person(String name, String sex) { super(); this.name = name; this.sex = sex; } //省略toString() }
-
数据流
- 特点:提供了各种数据类型对应的读取和写入的方式
- 类别
- DataInputStream (InputStream in)
- DataOutputStream (OutputStream out)
-
public static void main(String[] args) { DataOutputStream dataOutput = null; DataInputStream dataInput = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); dataOutput = new DataOutputStream(baos); dataOutput.writeBoolean(true); dataOutput.writeUTF("string"); dataOutput.writeInt(1024); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); dataInput = new DataInputStream(bais); System.out.println( dataInput.readBoolean() + ":" + dataInput.readUTF() + ":" + dataInput.readInt()); } catch (IOException e) { e.printStackTrace(); } finally { try { dataOutput.close(); dataInput.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
序列流
- 类别
- SequenceInputStream (InputStream s1, InputStream s2) 合并两个输入字节流
- SequenceInputStream (Enumeration<? extends InputStream> e) 合并多个个输入字节流
-
/** * 合并多個文件 */ private void test2() { FileInputStream fis1 = null; FileInputStream fis2 = null; FileInputStream fis3 = null; FileOutputStream fos = null; SequenceInputStream sis = null; try { fis1 = new FileInputStream(new File("iotest.txt")); fis2 = new FileInputStream(new File("iotest2.txt")); fis3 = new FileInputStream(new File("iotest3.txt")); fos = new FileOutputStream(new File("iotest1.txt")); Vector<InputStream> v = new Vector<>(); v.add(fis1); v.add(fis2); v.add(fis3); Enumeration<InputStream> enumeration = v.elements(); sis = new SequenceInputStream(enumeration); byte[] buffer = new byte[1024]; int len = -1; while ((len = sis.read(buffer)) != -1) { fos.write(buffer, 0, len); } System.out.println("——合并完成——"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fis1.close(); fis2.close(); fis3.close(); fos.close(); sis.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 合并两个文件 */ private void test1() { SequenceInputStream sis = null; FileOutputStream fos = null; InputStream f1 = null; InputStream f2 = null; try { f1 = new FileInputStream("iotest.txt"); f2 = new FileInputStream("iotest2.txt"); fos = new FileOutputStream("iotest3.txt"); sis = new SequenceInputStream(f1, f2); int len = -1; byte[] buffer = new byte[1024]; while ((len = sis.read(buffer)) != -1) { fos.write(buffer, 0, len); } System.out.println("————合并完成————"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { f1.close(); f2.close(); sis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 类别
-
RandomAccessFile
- 特点:RandomAccessFile(任意访问文件)实现 DataOutput和 DataInput 具备对文件读取和写入的功能
- 方法
- void seek(long pos) 设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入
- long getFilePointer() 返回此文件中的当前偏移量
-
//写入对象 private void test2() throws IOException { RandomAccessFile ra = new RandomAccessFile("002.bin", "rw"); Person person1 = new Person("make", "male"); Person person2 = new Person("mary", "female"); person1.writeToFile(ra); person2.writeToFile(ra); for (int i = 0; i < ra.length(); i = (int) ra.getFilePointer()){ ra.seek(i); System.out.println(ra.readUTF() + "," + ra.readUTF()); } ra.close(); } //写入字符串 private void test1() throws IOException { /** * r 以只读的方式打开文件 * rw 以读、写的方式打开文件,如果不存在尝试创建 * rwd 相对rw模式,还要求对文件<内容>的每个更新都同步写入到底层存储设备中 * rws 相对rw模式,还要求对文件的<内容或元数据>的每个更新都同步写入到底层存储设备中 */ RandomAccessFile raf = new RandomAccessFile("001.txt", "rw"); System.out.println(raf.getFilePointer()); raf.writeUTF("helloworld"); System.out.println(raf.getFilePointer()); raf.writeUTF("你好世界HelloWorld"); System.out.println("写入完成"); // raf.seek(0); // System.out.println(raf.readUTF()); // raf.seek(12); // System.out.println(raf.readInt()); for (int i = 0; i < raf.length();i = (int) raf.getFilePointer()){ raf.seek(i); System.out.println(raf.readUTF()); } raf.close(); } public class Person implements Serializable { private static final long serialVersionUID = 1293810121342278585L; private String name; private String sex; public Person(String name, String sex) { super(); this.name = name; this.sex = sex; } public void writeToFile(RandomAccessFile ra) { try { ra.writeUTF(this.name); ra.writeUTF(this.sex); } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { return "Person [name=" + name + ", sex=" + sex + "]"; } }
- 按流的方向