File类

File 类的基本概念

  • java.io.File类:文件和文件目录的抽象表示形式,与平台无关。
  • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可以没有一个真实存在的文件或目录。
  • File 能新建、删除、重命名文件和目录,但不能访问(读写)文件内容本身, 如果需要访问文件内容本身,则需要使用IO流。
  • File对象可以作为参数传递给流的构造器。

File 类的构造器

image.png
三种基本构造器:

  • public File(String pathname):以pathname为路径创建File对象,可以是绝对路径或者相对路径。
    • 绝对路径:是一个固定的路径,从盘符开始
    • 相对路径:是相对于某个位置开始,IDEA里是相对于当前工程或模块(main方法是相对于整个工程,单元测试里是相对当前模块)。
  • public File(String parent,String child):以parent为父路径,child为子路径创建File对象。
  • public File(File parent,String child):根据一个父File对象和子文件路径创建File对象

关于分隔符:

  • 路径中的每级目录之间用一个路径分隔符隔开,路径分隔符和系统有关:
    • windows和DOS系统默认使用“\”来表示
    • UNIX和URL使用“/”来表示
  • Java程序支持跨平台运行,因此路径分隔符要慎用,为了解决这个隐患,File类提供了一个常量:public static final String separator。根据操作系统,动态的提供分隔符。

【示例代码】

  1. @Test
  2. public void test1() {
  3. // 构造器1
  4. File file1 = new File("hello.txt");
  5. File file2 = new File("/Users/jyunkai/Documents/Code/JavaSE/IO/hi.txt");
  6. System.out.println(file1);//hello.txt
  7. System.out.println(file2);///Users/jyunkai/Documents/Code/JavaSE/IO/hi.txt
  8. // 构造器2
  9. File file3 = new File("/Users/jyunkai/Documents/Code", "JavaSE/IO");
  10. System.out.println(file3);///Users/jyunkai/Documents/Code/JavaSE/IO
  11. // 构造器3
  12. File file4 = new File(file3, "ha.txt");
  13. System.out.println(file4);///Users/jyunkai/Documents/Code/JavaSE/IO/ha.txt
  14. }

File类的常用方法

File类的获取功能

  • public String getAbsolutePath():获取绝对路径。
  • public String getPath() :获取路径。
  • public String getName() :获取名称。
  • public String getParent():获取上层文件目录路径,若无则返回null。
  • public long length() :获取文件长度(字节数)。不能获取目录的长度。
  • public long lastModified():获取最后一次的修改时间,毫秒值。
  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组。
  • public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组。

【示例代码】

  1. public class FileTest {
  2. @Test
  3. public void test1() {
  4. File file1 = new File("hello.txt");
  5. System.out.println(file1.getAbsoluteFile());
  6. System.out.println(file1.getPath());
  7. System.out.println(file1.getName());
  8. System.out.println(file1.getParent());
  9. System.out.println(file1.length());
  10. System.out.println(new Date(file1.lastModified()));
  11. File file = new File("/Users/eric/Documents/Code/Study/JavaBasic/FileAndIO");
  12. for (String s : Objects.requireNonNull(file.list())) {
  13. System.out.println(s);
  14. }
  15. for (File f : Objects.requireNonNull(file.listFiles())) {
  16. System.out.println(f);
  17. }
  18. }
  19. }

输出:
image.png

File类的重命名功能(剪切)

  • public boolean renameTo(File dest):把文件重命名为指定的文件路径

比如:file1.renameTo(file2)为例:要想保证返回true,需要file1在硬盘中是存在的,且file2在硬盘中不存在。

示例代码:

  1. @Test
  2. public void test5(){
  3. // hello.txt 在硬盘中是存在的
  4. File file1 = new File("hello.txt");
  5. // hi.txt 在硬盘中是不存在的
  6. File file2 = new File("/Users/jyunkai/Documents/IO/hi.txt");
  7. boolean renameTo = file1.renameTo(file2);
  8. System.out.println(renameTo);
  9. }

File类的判断功能

  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile():判断是否是文件
  • public boolean exists():判断是否存在
  • public boolean canRead():判断是否可读
  • public boolean canWrite():判断是否可写
  • public boolean isHidden():判断是否隐藏

【示例代码】

  1. @Test
  2. public void test3(){
  3. // File file1 = new File("hello.txt");
  4. File file1 = new File("/Users/jyunkai/Documents/Code/JavaSE");
  5. System.out.println(file1.isDirectory());
  6. System.out.println(file1.isFile());
  7. System.out.println(file1.canRead());
  8. System.out.println(file1.canWrite());
  9. System.out.println(file1.isHidden());
  10. }

File类的创建功能

  • public boolean createNewFile():创建文件,若文件存在则不创建,返回false
  • public boolean mkdir():创建文件目录,如果此文件目录存在就不创建了,如果此文件目录的上层目录不存在也不创建。
  • public boolean mkdirs() :创建文件目录,如果上层文件目录不存在,一并创建。

注意:如果你创建文件或者文件目录没有写盘符路径,那么默认在项目路径下(当前工程或模块)。
image.png

File类的删除功能

  • public boolean delete():删除文件或者文件夹。

【删除注意事项】

  • Java中的删除不走回收站。
  • 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录。

示例代码:

  1. @Test
  2. public void test4() throws IOException {
  3. File file = new File("hi.txt");
  4. // 文件的创建与删除
  5. if (!file.exists()) {
  6. file.createNewFile();
  7. System.out.println("创建成功");
  8. } else {
  9. file.delete();
  10. System.out.println("删除成功");
  11. }
  12. // 文件目录的创建
  13. File file1 = new File("/Users/jyunkai/Documents/IO/io1");
  14. boolean mkdir = file1.mkdir();
  15. if (mkdir) {
  16. System.out.println("创建成功1");
  17. }
  18. File file2 = new File("/Users/jyunkai/Documents/IO/io2");
  19. boolean mkdirs = file2.mkdirs();
  20. if (mkdirs) {
  21. System.out.println("创建成功2");
  22. }
  23. //要想删除成功,文件目录下不能有子目录或文件
  24. System.out.println(file2.delete());
  25. }

IO流

IO基本概念

IO原理

  • I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输,如读/写文件,网络通讯等。
  • Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
  • java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。

IO流的分类

  • 按操作数据单位不同分为:
    • 字节流(8 bit):用于处理图片、视频等文件。
    • 字符流(16 bit):用于处理文本文件。
  • 按数据流的流向不同分为:
    • 输入流:将硬盘中的文件中的数据读入到内存中。
    • 输出流:将内存中的数据写出到硬盘中的文件里。
  • 按流的角色的不同分为:
    • 节点流(文件流):直接从数据源或目的地读写数据,主要是:
      • FileInputStream
      • FileOutputStream
      • FileReader
      • FileWriter
    • 处理流:不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提 供更为强大的读写功能。

image.png
image.png

Java的IO流共涉及40多个类,实际上非常规则,都是从上图4个抽象基类派生的。由这四个类派生出来的子类名称都是以其父类名作为子类名后缀,如下图所示,其中背景颜色深的需要重点掌握。

image.png

节点流(文件流)

  • 字符流操作字符,只能操作普通文本文件,最常见的文本文件有:.txt,.java,.c,.cpp 等。
    • FileReader
    • FileWriter
  • 字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt,.xlsx等。

    • FileInputStream
    • FileOutputStream

      FileReader

      要求:将当前模块下的hello.txt文件内容读入程序中,并输出到控制台。
      说明点:
  • read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1。

  • 异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理。
  • 读入的文件一定要存在,否则就会报FileNotFoundException

【示例代码】

  1. @Test
  2. public void test1() {
  3. FileReader fr = null;
  4. try {
  5. //1.实例化File类的对象,指明要操作的文件
  6. File file = new File("hello.txt");
  7. //2.提供具体的流
  8. fr = new FileReader(file);
  9. //3.数据的读入
  10. //方式一:
  11. // int data = fr.read();
  12. // while (data != -1) {
  13. // System.out.print((char) data);
  14. // data = fr.read();
  15. // }
  16. //方式二:语法上针对于方式一的修改
  17. int data;
  18. while ((data = fr.read()) != -1) {
  19. System.out.print((char) data);
  20. }
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. } finally {
  24. //4.流的关闭
  25. if (fr != null) {
  26. try {
  27. fr.close();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. }
  34. //对read()操作升级:使用read的重载方法
  35. @Test
  36. public void test2() {
  37. FileReader fr = null;
  38. try {
  39. //1.File类的实例化
  40. File file = new File("hello.txt");
  41. //2.FileReader流的实例化
  42. fr = new FileReader(file);
  43. //3.读入的操作
  44. //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
  45. char[] cbuf = new char[5];
  46. int len;
  47. while ((len = fr.read(cbuf)) != -1) {
  48. //方式一
  49. //错误的写法:
  50. // for (int i = 0; i < cbuf.length; i++) {
  51. // System.out.print(cbuf[i]);
  52. // }
  53. //正确的写法:
  54. // for (int i = 0; i < len; i++) {
  55. // System.out.print(cbuf[i]);
  56. // }
  57. //方式二
  58. //错误的写法:对应着方式一的错误写法
  59. // String s = new String(cbuf);
  60. //正确的写法:
  61. String s = new String(cbuf, 0, len);
  62. System.out.print(s);
  63. }
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. } finally {
  67. //4.资源的关闭
  68. if (fr != null) {
  69. try {
  70. fr.close();
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. }
  76. }

FileWriter

从内存中写出数据到硬盘的文件里。
说明:

  • 输出操作对应的File可以不存在的,并不会报异常。
  • File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
  • File对应的硬盘中的文件如果存在:
    • 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖;
    • 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容。

【示例代码】

  1. @Test
  2. public void test3() {
  3. FileWriter fw = null;
  4. try {
  5. //1.提供File类的对象,指明写出到的文件
  6. File file = new File("hi.txt");
  7. //2.提供FileWriter的对象,用于数据的写出
  8. fw = new FileWriter(file, true);
  9. //3.写出的操作
  10. fw.write("I have a dream.\n");
  11. fw.write("You need to have a dream.\n");
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. } finally {
  15. //4.流资源的关闭
  16. try {
  17. if (fw != null)
  18. fw.close();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. //读入和写出
  25. @Test
  26. public void test4() {
  27. FileReader fr = null;
  28. FileWriter fw = null;
  29. try {
  30. //1.创建File类的对象,指明读入和写出的文件
  31. File srcFile = new File("hello.txt");
  32. File destFile = new File("hi.txt");
  33. //2.创建输入流和输出流的对象
  34. fr = new FileReader(srcFile);
  35. fw = new FileWriter(destFile);
  36. //3.数据的读入和写出操作
  37. char[] cbuf = new char[5];
  38. int len;//记录每次读入字符的个数
  39. while ((len = fr.read(cbuf)) != -1) {
  40. //每次写出len个字符
  41. fw.write(cbuf, 0, len);
  42. }
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. } finally {
  46. //4.关闭流资源
  47. try {
  48. if (fw != null)
  49. fw.close();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. try {
  54. if (fr != null)
  55. fr.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. }

FileInputStream

使用字节流FileInputStream处理文本文件,可能出现乱码。下面的程序在控制台输出时候,中文会有乱码。

  1. @Test
  2. public void test1() {
  3. File file = null;
  4. FileInputStream fis = null;
  5. try {
  6. //1.造文件
  7. file = new File("hello.txt");
  8. //2.造流
  9. fis = new FileInputStream(file);
  10. //3.读数据
  11. byte[] buffer = new byte[5];
  12. int len;
  13. while ((len = fis.read(buffer)) != -1) {
  14. String s = new String(buffer, 0, len);
  15. System.out.print(s);
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. } finally {
  20. //4.关闭流资源
  21. if(fis != null) {
  22. try {
  23. fis.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. }

FileOutputStream

值得注意的是,复制操作可以操作文本文件,因为中间没有打印输出。

  1. public void copyFile(String srcPath, String destPath) {
  2. FileInputStream fis = null;
  3. FileOutputStream fos = null;
  4. try {
  5. File srcFile = new File(srcPath);
  6. File destFile = new File(destPath);
  7. fis = new FileInputStream(srcFile);
  8. fos = new FileOutputStream(destFile);
  9. byte[] buffer = new byte[1024];
  10. int len;
  11. while ((len = fis.read(buffer)) != -1) {
  12. fos.write(buffer, 0, len);
  13. }
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. } finally {
  17. if (fos != null) {
  18. try {
  19. fos.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. if (fis != null) {
  25. try {
  26. fis.close();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. }
  33. @Test
  34. public void test2(){
  35. String srcPath = "爱情与友情.jpg";
  36. String destPath = "爱情与友情1.jpg";
  37. copyFile(srcPath, destPath);
  38. }

缓冲流(BufferedXxxxx)

为了提高数据的读写速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,使用8192个字节(8Kb)的缓冲区,如下所示:
image.png

【注意点】

  • 缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
    • 操作字节文件:BufferedInputStreamBufferedOutputStream
    • 操作字符文件:BufferedReaderBufferedWriter
  • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。
  • 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个字节(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。
  • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。
  • flush()方法的使用:手动将buffer中内容写入文件,一般不需要手动。
  • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。

image.png
【示例代码】

  1. public class BufferedTest {
  2. //使用BufferedInputStream、BufferedOutputStream实现图片视频等文件的复制
  3. public void copyFileWithBuffered(String srcPath, String destPath) {
  4. BufferedInputStream bis = null;
  5. BufferedOutputStream bos = null;
  6. try {
  7. //1.造文件
  8. File srcFile = new File(srcPath);
  9. File destFile = new File(destPath);
  10. //2.造流
  11. //2.1节点流
  12. FileInputStream fis = new FileInputStream(srcFile);
  13. FileOutputStream fos = new FileOutputStream(destFile);
  14. //2.2缓冲流
  15. bis = new BufferedInputStream(fis);
  16. bos = new BufferedOutputStream(fos);
  17. //3.复制操作
  18. byte[] buffer = new byte[1024];
  19. int len;
  20. while ((len = bis.read(buffer)) != -1) {
  21. bos.write(buffer, 0, len);
  22. }
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. } finally {
  26. //4.流的关闭
  27. //要求先关外层再关内存,在关闭外层的时候内层也会自动关闭
  28. if (bos != null) {
  29. try {
  30. bos.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. if (bis != null) {
  36. try {
  37. bis.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. }
  44. @Test
  45. public void test1(){
  46. long start = System.currentTimeMillis();
  47. String srcPath = "/Users/jyunkai/Downloads/mac软件推荐1.mp4";
  48. String destPath = "/Users/jyunkai/Downloads/mac软件推荐1-1.mp4";
  49. copyFileWithBuffered(srcPath, destPath);
  50. long end = System.currentTimeMillis();
  51. System.out.println("花费时间:" + (end - start));//399-->118
  52. }
  53. //使用BufferedReader、BufferedWriter实现文本文件的复制
  54. @Test
  55. public void test2() {
  56. BufferedReader br = null;
  57. BufferedWriter bw = null;
  58. try {
  59. //创建文件和相应的流
  60. br = new BufferedReader(new FileReader(new File("红楼梦.txt")));
  61. bw = new BufferedWriter(new FileWriter(new File("红楼梦1.txt")));
  62. //读写操作
  63. //方式一:使用char[]
  64. // char[] cbuf = new char[1024];
  65. // int len;
  66. // while ((len = br.read(cbuf)) != -1) {
  67. // bw.write(cbuf, 0, len);
  68. // //bw.flush();
  69. // }
  70. //方式二:使用String
  71. String data;
  72. while ((data = br.readLine()) != null) {
  73. bw.write(data);//data中不包含换行符
  74. bw.newLine();
  75. }
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. } finally {
  79. //关闭资源
  80. if (bw != null) {
  81. try {
  82. bw.close();
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. if (br != null) {
  88. try {
  89. br.close();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. }
  95. }
  96. }

转换流

  • 转换流提供了在字节流和字符流之间的转换,转换流属于字符流。
  • Java API提供了两个转换流:
    • InputStreamReader:将InputStream转换为Reader
    • OutputStreamWriter:将Writer转换为OutputStream
  • 字节流中的数据都是字符时,转成字符流操作更高效。
  • 很多时候我们使用转换流来处理文件乱码问题,实现编码和解码的功能。

image.png
image.png
image.png

【示例代码】

  1. public class IsReaderOsWriterTest {
  2. /**
  3. * 转换流的使用
  4. * 1.转换流:属于字符流
  5. * InputStreamReader:将一个字节的输入流转换为字符的输入流
  6. * OutputStreamWriter:将一个字符的输出流转换为字节的输出流
  7. *
  8. * 2.作用:提供字节流与字符流之间的转换
  9. *
  10. * 3. 解码:字节、字节数组 --->字符数组、字符串
  11. * 编码:字符数组、字符串 ---> 字节、字节数组
  12. *
  13. * 4.字符集
  14. * ASCII:美国标准信息交换码,用一个字节的7位可以表示。
  15. * ISO8859-1:拉丁码表。欧洲码表,用一个字节的8位表示。
  16. * GB2312:中国的中文编码表,最多两个字节编码所有字符。
  17. * GBK:中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码。
  18. * Unicode:国际标准码,融合了目前人类使用的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节来表示。
  19. * UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
  20. */
  21. @Test
  22. public void test1(){
  23. InputStreamReader isr = null;
  24. OutputStreamWriter osw = null;
  25. try {
  26. //造文件、造流
  27. FileInputStream fis = new FileInputStream("红楼梦.txt");
  28. FileOutputStream fos = new FileOutputStream("红楼梦2.txt");
  29. isr = new InputStreamReader(fis);//使用系统默认的字符集,IDEA里设置的是UTF-8
  30. osw = new OutputStreamWriter(fos, "gbk");//指明字符集
  31. //读写过程
  32. char[] cbuf = new char[1024];
  33. int len;
  34. while ((len = isr.read(cbuf)) != -1) {
  35. osw.write(cbuf, 0, len);
  36. }
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. } finally {
  40. //关闭资源
  41. try {
  42. if (osw != null)
  43. osw.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. try {
  48. if (isr != null)
  49. isr.close();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. }

标准输入输出流(System.in/out)

  • System.inSystem.out分别代表了系统标准的输入和输出设备。
  • 默认输入设备是键盘,输出设备是显示器。
  • System.in的类型是InputStream
  • System.out的类型是PrintStream,其是OutputStream的子类,FilterOutputStream 的子类
  • 重定向:通过System类的setInsetOut方法对默认设备进行改变。
    • public static void setIn(InputStream in)
    • public static void setOut(PrintStream out)

【练习】
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in —-> 转换流 —-> BufferedReader的readLine()

  1. public class OtherStreamTest {
  2. public static void main(String[] args) {
  3. BufferedReader br = null;
  4. try {
  5. InputStreamReader isr = new InputStreamReader(System.in);
  6. br = new BufferedReader(isr);
  7. while (true) {
  8. System.out.print("请输入字符串:");
  9. String data = br.readLine();
  10. if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
  11. System.out.println("程序结束");
  12. break;
  13. }
  14. String upperCase = data.toUpperCase();
  15. System.out.println(upperCase);
  16. }
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. } finally {
  20. if (br != null) {
  21. try {
  22. br.close();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  28. }
  29. }

打印流

打印流:PrintStreamPrintWriter,实现将基本数据类型的数据格式转化为字符串输出。

  • 提供了一系列重载的print()println()方法,用于多种数据类型的输出。
  • PrintStreamPrintWriter 的输出不会抛出IOException异常。
  • PrintStreamPrintWriter有自动flush功能。
  • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节,在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
  • System.out返回的是PrintStream的实例。

【示例代码】

  1. @Test
  2. public void test2() {
  3. PrintStream ps = null;
  4. try {
  5. //造文件、造流
  6. FileOutputStream fos = new FileOutputStream(new File("ASCII.txt"));
  7. //创建打印输出流,true为自动刷新模式(写入换行符或字节'\n'时都会刷新输出缓冲区)
  8. ps = new PrintStream(fos, true);
  9. if (ps != null) {
  10. //把标准输出流(控制台输出)改成文件
  11. System.setOut(ps);
  12. }
  13. //输出ASCII字符
  14. for (int i = 0; i <= 255; i++) {
  15. System.out.print((char) i);
  16. if (i % 50 == 0) {
  17. //每50个字符一行
  18. System.out.println();
  19. }
  20. }
  21. } catch (FileNotFoundException e) {
  22. e.printStackTrace();
  23. } finally {
  24. if (ps != null)
  25. ps.close();
  26. }
  27. }

数据流

为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。

数据流有两个类,用于读取和写出基本数据类型、String类的数据,分别“套接”在 InputStreamOutputStream 子类的流上:

  • DataInputStream
  • DataOutputStream

DataInputStream 中的方法示例:

  • boolean readBoolean()
  • char readChar()
  • double readDouble()
  • long readLong()
  • String readUTF()
  • byte readByte()
  • float readFloat()
  • short readShort()
  • int readInt()
  • void readFully(byte[] b)

DataOutputStream中的方法

  • 将上述的方法的read改为相应的write即可。

【示例代码】

  1. /*
  2. 数据流
  3. DataInputStream 和 DataOutputStream
  4. 作用:用于读取或写出基本数据类型的变量或字符串
  5. 练习:将内存中的字符串、基本数据类型的变量写出到文件中。
  6. */
  7. @Test
  8. public void test3() {
  9. DataOutputStream dos = null;
  10. try {
  11. dos = new DataOutputStream(new FileOutputStream("data.txt"));
  12. dos.writeUTF("杰克");
  13. dos.flush();//刷新操作,将内存中的数据写入文件
  14. dos.writeInt(18);
  15. dos.flush();
  16. dos.writeBoolean(true);
  17. dos.flush();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21. try {
  22. if (dos != null)
  23. dos.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. /*
  30. 将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
  31. 注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
  32. */
  33. @Test
  34. public void test4() {
  35. DataInputStream dis = null;
  36. try {
  37. dis = new DataInputStream(new FileInputStream("data.txt"));
  38. String name = dis.readUTF();
  39. int age = dis.readInt();
  40. boolean isMale = dis.readBoolean();
  41. System.out.println("name = " + name);
  42. System.out.println("age = " + age);
  43. System.out.println("isMale = " + isMale);
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. } finally {
  47. if (dis!=null) {
  48. try {
  49. dis.close();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. }

对象流

ObjectInputStreamOjbectOutputSteam 是用于存储和读取基本数据类型数据或对象的处理流。

  • 它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
    • 序列化:用 ObjectOutputStream 类保存基本类型数据或对象的机制。
    • 反序列化:用 ObjectInputStream 类读取基本类型数据或对象的机制。
  • ObjectOutputStreamObjectInputStream 不能序列化 statictransient 修饰的成员变量。

关于对象的序列化

  • 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
  • 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原。
  • 序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是JavaEE 平台的基础。
  • 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。 否则,会抛出NotSerializableException异常。
    • Serializable
    • Externalizable
  • 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:private static final long serialVersionUID; 用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化,建议最好显式声明。
    • 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同 就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常InvalidCastException

【示例代码】

  1. public class ObjectInputOutputStreamTest {
  2. /*
  3. 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
  4. 使用ObjectOutputStream实现
  5. */
  6. @Test
  7. public void test1() {
  8. ObjectOutputStream oos = null;
  9. try {
  10. oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
  11. oos.writeObject(new String("我爱北京天安门"));
  12. oos.flush();
  13. oos.writeObject(new Person("jack", 24, new Account(2000)));
  14. oos.flush();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. } finally {
  18. if (oos != null) {
  19. try {
  20. oos.close();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }
  26. }
  27. /*
  28. 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
  29. 使用ObjectInputStream来实现
  30. */
  31. @Test
  32. public void test2() {
  33. ObjectInputStream ois = null;
  34. try {
  35. ois = new ObjectInputStream(new FileInputStream("object.dat"));
  36. String str = (String) ois.readObject();
  37. Person person = (Person) ois.readObject();
  38. System.out.println(str);
  39. System.out.println(person);
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. } catch (ClassNotFoundException e) {
  43. e.printStackTrace();
  44. } finally {
  45. if (ois!=null) {
  46. try {
  47. ois.close();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }
  53. }
  54. }
  1. public class Person implements Serializable {
  2. /**
  3. * Person需要满足如下的要求,方可序列化
  4. * 1.需要实现接口:Serializable
  5. * 2.当前类提供一个全局常量:serialVersionUID
  6. * 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。
  7. * 默认情况下,基本数据类型都是可序列化的。
  8. * 补充:ObjectOutputStream 和 ObjectInputStream 不能序列化 static 和 transient 修饰的成员变量。
  9. */
  10. private static final long serialVersionUID = 422983570235L;
  11. private String name;
  12. private int age;
  13. private Account account;
  14. public Person() {
  15. }
  16. public Person(String name, int age, Account account) {
  17. this.name = name;
  18. this.age = age;
  19. this.account = account;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public int getAge() {
  28. return age;
  29. }
  30. public void setAge(int age) {
  31. this.age = age;
  32. }
  33. public Account getAccount() {
  34. return account;
  35. }
  36. public void setAccount(Account account) {
  37. this.account = account;
  38. }
  39. @Override
  40. public String toString() {
  41. return "Person{" +
  42. "name='" + name + '\'' +
  43. ", age=" + age +
  44. ", account=" + account +
  45. '}';
  46. }
  47. }
  1. public class Account implements Serializable {
  2. private static final long serialVersionUID = 256998083235L;
  3. private double balance;
  4. public Account() {
  5. }
  6. public Account(double balance) {
  7. this.balance = balance;
  8. }
  9. public double getBalance() {
  10. return balance;
  11. }
  12. public void setBalance(double balance) {
  13. this.balance = balance;
  14. }
  15. @Override
  16. public String toString() {
  17. return "Account{" +
  18. "balance=" + balance +
  19. '}';
  20. }
  21. }

随机存取文件流

基本概念

  • RandomAccessFile 声明在 java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInputDataOutput这两个接口,也就意味着这个类既可以读也可以写。
  • RandomAccessFile 类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读、写文件
    • 支持只访问文件的部分内容
    • 可以向已存在的文件后追加内容
  • RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置:
    • long getFilePointer():获取文件记录指针的当前位置。
    • void seek(long pos):将文件记录指针定位到 pos 位置。
  • RandomAccessFile 构造器
    • public ``RandomAccessFile``(``File ``file, ``String ``mode)
    • public ``RandomAccessFile``(``String ``name, ``String ``mode)
    • 创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
      • r:以只读方式打开,不会创建文件而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。
      • rw:打开以便读取和写入,如果文件不存在则会去创建文件,如果存在则不会创建。
      • rwd:打开以便读取和写入,同步文件内容的更新。
      • rws:打开以便读取和写入,同步文件内容和元数据的更新。

应用
我们可以用RandomAccessFile这个类,来实现一个多线程断点下载的功能, 用过下载工具的朋友们都知道,下载前都会建立两个临时文件,一个是与被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次暂停的时候,都会保存上一次的指针,然后断点下载的时候,会继续从上 一次的地方下载,从而实现断点下载或上传的功能,有兴趣的朋友们可以 自己实现下。

【示例代码】

  1. public class RandomAccessFileTest {
  2. @Test
  3. public void test1() {
  4. RandomAccessFile raf1 = null;
  5. RandomAccessFile raf2 = null;
  6. try {
  7. // r: 以只读方式打开;
  8. // rw:打开以便读取和写入;
  9. raf1 = new RandomAccessFile(new File("爱情与友情.jpg"), "r");
  10. raf2 = new RandomAccessFile(new File("爱情与友情2.jpg"), "rw");
  11. byte[] buffer = new byte[1024];
  12. int len;
  13. while ((len = raf1.read(buffer)) != -1) {
  14. raf2.write(buffer, 0, len);
  15. }
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } finally {
  19. if (raf1 != null) {
  20. try {
  21. raf1.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. if (raf2 != null) {
  27. try {
  28. raf2.close();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }
  35. /*
  36. 使用RandomAccessFile实现数据的插入效果
  37. */
  38. @Test
  39. public void test2() {
  40. RandomAccessFile raf = null;
  41. try {
  42. raf = new RandomAccessFile("hello.txt", "rw");
  43. // 将指针调到角标为3的位置
  44. raf.seek(3);
  45. // 保存指针3后面的所有数据到StringBuilder中
  46. StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
  47. byte[] buffer = new byte[20];
  48. int len;
  49. while ((len = raf.read(buffer)) != -1) {
  50. builder.append(new String(buffer, 0, len));
  51. }
  52. // 调回指针,写入"xyz"
  53. raf.seek(3);
  54. raf.write("xyz".getBytes());
  55. // 将StringBuilder中的数据写入到文件中
  56. raf.write(builder.toString().getBytes());
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. } finally {
  60. if (raf != null) {
  61. try {
  62. raf.close();
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }
  68. }
  69. }

拓展(详细的在框架时讲解)

NIO

Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的 IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的、基于通道的IO操作,而IO是面向流的。NIO将以更加高效的方式进行文件的读写操作。

Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。

  • java.nio.channels.Channel
    • FileChannel:处理本地文件
    • SocketChannel:TCP网络编程的客户端的Channel
    • ServerSocketChannel:TCP网络编程的服务器端的Channel
    • DatagramChannel:UDP网络编程中发送端和接收端的Channel

NIO.2

随着 JDK 7 的发布,Java对 NIO 进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。

Path/Paths/Files

  • 早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且大多数方法在出错时仅返回失败,并不会提供异常信息。
  • NIO. 2为了弥补这种不足,引入了 Path 接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。
  • Path可以看成是File类的升级版本,实际引用的资源也可以不存在。

在以前IO操作都是这样写的:

  1. import java.io.File;
  2. File file = new File("index.html");

但在Java7 中,我们可以这样写:

  1. import java.nio.file.Path;
  2. import java.nio.file.Paths;
  3. Path path = Paths.get("index.html");
  • 同时,NIO.2在 java.nio.file 包下还提供了 FilesPaths 工具类,Files包含了大量静态的工具方法来操作文件,Paths 则包含了两个返回Path的静态工厂方法。
  • Paths 类提供的静态 get()方法用来获取 Path 对象:
    • static Path get(String first, String ... more):用于将多个字符串串连成路径
    • static Path get(URI uri):返回指定uri对应的Path路径

image.png
image.png
image.png