[关闭]
@adamhand 2019-01-05T13:59:49.000000Z 字数 39744 阅读 692

Java——I/O


一、概览

Java 的 I/O 大概可以分成以下几类:

二、字节操作和字符操作——字节流和字符流



流的概念和作用

流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

IO流的分类

字符流和字节流

字节流的两个顶层父类:InputStream、OutputStream.

字符流的两个顶层父类:Reader、Writer。

这些体系的子类都以父类名作为后缀,而且子类名的前缀就是该对象的功能

字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表,简单来说,字符流=字节流+编码表。 字节流和字符流的区别:

设备上的数据无论是图片或者视频,文字,它们都以二进制存储的。二进制的最终都是以一个8位为数据单元进行体现,所以计算机中的最小数据单元就是字节。意味着,字节流可以处理设备上的所有数据,所以字节流一样可以处理字符数据。

结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

字节流

输入字节流 InputStream

  • InputStream 是所有的输入字节流的父类,它是一个抽象类。
  • ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。
  • PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
  • ObjectInputStream 和所有FilterInputStream 的子类都是装饰流(装饰器模式的主角)。

输出字节流 OutputStream

  • OutputStream 是所有的输出字节流的父类,它是一个抽象类。
  • ByteArrayOutputStream、FileOutputStream 是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。
  • PipedOutputStream 是向与其它线程共用的管道中写入数据。
  • ObjectOutputStream 和所有FilterOutputStream 的子类都是装饰流。

常用字节流——FileInputStrem和FileOutPutStrem

FileInputStrem和FileOutPutStrem的写入和读取方式有4中,如下:

  • 直接读取和写入单个字节。这种方式效率很低,应该避免使用。
  • 使用FileInputStrem的available方法估计流的大小,从而创建缓冲区数组。这种方法会创建一个和流文件大小相同的数组,如果流文件很大,缓冲区会很大,所以在文件比较大的时候不建议使用。
  • 创建固定大小的缓冲区。推荐使用。
  • 使用BufferedInputStream和BufferedOutputStream。推荐使用。

下面看具体的例子:

  • 例子1:FileInputStrem读取文本文件中的内容并打印到控制台上。
  1. public class FileInputStreamDemo {
  2. public static String demoRead(String filePath){
  3. FileInputStream fis = null;
  4. String result = null;
  5. try {
  6. //1.根据path路径数实例化一个输入流对象
  7. fis = new FileInputStream(filePath);
  8. //2.返回这个流中可以被读的剩下的bytes字节的估计值
  9. int size = fis.available();
  10. //3.根据估计值创建缓冲数组
  11. byte[] buf = new byte[size];
  12. //4.将数据读入缓冲数组
  13. fis.read(buf);
  14. //5.将读到的数据创建成一个字符串,用于返回
  15. result = new String(buf);
  16. } catch (FileNotFoundException e) {
  17. e.printStackTrace();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21. if(fis != null){
  22. try {
  23. fis.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. return result;
  30. }
  31. public static void main(String[] args) {
  32. String filePath = "D:\\Prom\\testAll\\src\\IO\\FileInputStreamDemo\\demoRead.txt";
  33. String result = demoRead(filePath);
  34. System.out.println(result);
  35. }
  36. }
  • 例子2:FileOutputStrem写入文本文件。
  1. public class FileOutputStreamDemo {
  2. public static void WriteDemo(String filePath, String data){
  3. FileOutputStream fos = null;
  4. try {
  5. //1.根据文件路径创建输出流
  6. fos = new FileOutputStream(filePath);
  7. //2.将字符串转化为数组并写入
  8. fos.write(data.getBytes());
  9. } catch (FileNotFoundException e) {
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. } finally {
  14. if(fos != null){
  15. try {
  16. fos.close();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. }
  23. public static void main(String[] args) {
  24. String filePath = "D:\\Prom\\testAll\\src\\IO\\FileOutPutSreamDemo\\WriteDemo.txt";
  25. WriteDemo(filePath, "FileOutPutStream:" + "WriteDemo");
  26. }
  27. }
  • 例子3:使用四种方式复制mp3文件。
  1. public class CopyMp3Demo {
  2. //D:\Prom\testAll\src\IO\CopyMp3Demo
  3. public static void main(String[] args) {
  4. String fromPath = "D:\\Prom\\testAll\\src\\IO\\CopyMp3Demo\\0.mp3";
  5. String toPath = "D:\\Prom\\testAll\\src\\IO\\CopyMp3Demo\\1.mp3";
  6. // copyMp3Demo_1(fromPath, toPath);
  7. // copyMp3Demo_2(fromPath, toPath);
  8. // copyMp3Demo_3(fromPath, toPath);
  9. copyMp3Demo_4(fromPath, toPath);
  10. }
  11. /**
  12. * 一个字节一个字节读取,效率很慢,不要用。
  13. * @param fromPath
  14. * @param toPath
  15. */
  16. public static void copyMp3Demo_1(String fromPath, String toPath){
  17. FileInputStream fis = null;
  18. FileOutputStream fos = null;
  19. try {
  20. fis = new FileInputStream(fromPath);
  21. fos = new FileOutputStream(toPath);
  22. //一个字节一个字节读取
  23. int ch = 0;
  24. while ((ch = fis.read()) != -1){
  25. fos.write(ch);
  26. }
  27. } catch (FileNotFoundException e) {
  28. e.printStackTrace();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. } finally {
  32. if(fis != null){
  33. try {
  34. fis.close();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. if(fos != null){
  40. try {
  41. fos.close();
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. }
  48. /**
  49. * 使用available定义缓冲区,当文件很大的时候,缓冲区会很大,不建议使用。
  50. * @param fromPath
  51. * @param toPath
  52. */
  53. public static void copyMp3Demo_2(String fromPath, String toPath){
  54. FileInputStream fis = null;
  55. FileOutputStream fos = null;
  56. try {
  57. fis = new FileInputStream(fromPath);
  58. fos = new FileOutputStream(toPath);
  59. byte[] buf = new byte[fis.available()];
  60. fis.read(buf);
  61. fos.write(buf);
  62. } catch (FileNotFoundException e) {
  63. e.printStackTrace();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. } finally {
  67. if(fis != null){
  68. try {
  69. fis.close();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. if(fos != null){
  75. try {
  76. fos.close();
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  82. }
  83. /**
  84. * 使用BufferedInputStream和BufferedOutputStream缓冲区。建议使用。
  85. * @param fromPath
  86. * @param toPath
  87. */
  88. public static void copyMp3Demo_3(String fromPath, String toPath){
  89. BufferedInputStream bufis = null;
  90. BufferedOutputStream bufos = null;
  91. try {
  92. bufis = new BufferedInputStream(new FileInputStream(fromPath));
  93. bufos = new BufferedOutputStream(new FileOutputStream(toPath));
  94. int ch = 0;
  95. while((ch = bufis.read()) != -1){
  96. bufos.write(ch);
  97. }
  98. } catch (FileNotFoundException e) {
  99. e.printStackTrace();
  100. } catch (IOException e) {
  101. e.printStackTrace();
  102. } finally {
  103. if(bufis != null){
  104. try {
  105. bufis.close();
  106. } catch (IOException e) {
  107. e.printStackTrace();
  108. }
  109. }
  110. if(bufos != null){
  111. try {
  112. bufos.close();
  113. } catch (IOException e) {
  114. e.printStackTrace();
  115. }
  116. }
  117. }
  118. }
  119. /**
  120. * 使用自定义的数组缓冲区,建议使用。
  121. * @param fromPath
  122. * @param toPath
  123. */
  124. public static void copyMp3Demo_4(String fromPath, String toPath){
  125. FileInputStream fis = null;
  126. FileOutputStream fos = null;
  127. try {
  128. fis = new FileInputStream(fromPath);
  129. fos = new FileOutputStream(toPath);
  130. byte[] buf = new byte[1024];
  131. int len = 0;
  132. while((len = fis.read(buf)) != -1){
  133. fos.write(buf, 0, len);
  134. }
  135. } catch (FileNotFoundException e) {
  136. e.printStackTrace();
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. } finally {
  140. if(fis != null){
  141. try {
  142. fis.close();
  143. } catch (IOException e) {
  144. e.printStackTrace();
  145. }
  146. }
  147. if(fos != null){
  148. try {
  149. fos.close();
  150. } catch (IOException e) {
  151. e.printStackTrace();
  152. }
  153. }
  154. }
  155. }
  156. }

装饰者模式

装饰设计模式,可以在原有技能的基础上,新增技能,降低继承所带来的耦合性。装饰者和被装饰者必须实现同一个接口或者继承自同一个父类。

一个装饰者模式的例子如下:

  1. public class DecratorPattern {
  2. public static void main(String[] args) {
  3. Coder coder = new Coder(new Student());
  4. coder.code();
  5. }
  6. }
  7. //编码技能接口
  8. interface coding{
  9. public void code();
  10. }
  11. //学生会的编程语言:java和C
  12. class Student implements coding{
  13. public void code() {
  14. System.out.println("java");
  15. System.out.println("C");
  16. }
  17. }
  18. //学生变成程序员之后又学会了一些编程语言。这个类就是装饰类。
  19. class Coder implements coding{
  20. private Student student;
  21. public Coder(Student student) {
  22. this.student = student;
  23. }
  24. public void code() {
  25. student.code();
  26. System.out.println("C#");
  27. System.out.println("C++");
  28. }
  29. }

Java I/O 使用了装饰者模式来实现。以 InputStream 为例,

  • InputStream 是抽象组件;
  • FileInputStream 是 InputStream 的子类,属于具体组件,提供了字节流的输入操作;
  • FilterInputStream 属于抽象装饰者,装饰者用于装饰组件,为组件提供额外的功能。例如 BufferedInputStream 为 FileInputStream 提供缓存的功能。



实例化一个具有缓存功能的字节流对象时,只需要在 FileInputStream 对象上再套一层 BufferedInputStream 对象即可。

  1. FileInputStream fileInputStream = new FileInputStream(filePath);
  2. BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

DataInputStream 装饰者提供了对更多数据类型进行输入的操作,比如 int、double 等基本类型。

其他字节流

打印流——PrintSream

PrintStream 继承于FilterOutputStream,用来装饰其它输出流。它能为其他输出流添加了功能,使它们能够按照原格式进行打印。System.out对应的类型就是PrintStream。

PrintStream 永远不会抛出 IOException;它产生的IOException会被自身的函数所捕获并设置错误标记。

它的构造函数函数可以接收三种数据类型的值。

  • 字符串路径。
  • File对象。
  • OutputStream。
  1. public static void printStreamDemo() throws IOException {
  2. File file = new File("/usr/Prom/eclipse/testAll/src/FileFilter/printstream.txt");
  3. if(!file.exists())
  4. file.createNewFile();
  5. PrintStream out = new PrintStream(file);
  6. out.write(610); //接受的是一个byte数组,只写最低8位,结果是将b写入到文件中
  7. out.println(97); //97
  8. out.println('a'); //a
  9. out.println("hello world"); //hello world
  10. out.println(true); //true
  11. out.println(3.14); //3.14
  12. //out.println(new Student("酒香逢")); //姓名:酒香逢
  13. }

序列流,也称为合并流——SequenceInputStream:

特点:可以将多个读取流合并成一个流。这样操作起来很方便。
原理:其实就是将每一个读取流对象存储到一个集合中。最后一个流对象结尾作为这个流的结尾。

  1. public static void sequenceInputStreamDemo() throws IOException {
  2. /*
  3. * 需求:将1.txt 2.txt 3.txt文件中的数据合并到一个文件中。
  4. */
  5. //不推荐使用Vector对象,因为效率比较低。
  6. // Vector<FileInputStream> v = new Vector<FileInputStream>();
  7. // v.add(new FileInputStream("1.txt"));
  8. // v.add(new FileInputStream("2.txt"));
  9. // v.add(new FileInputStream("3.txt"));
  10. // Enumeration<FileInputStream> en = v.elements();
  11. File file1 = new File("/usr/Prom/eclipse/testAll/src/FileFilter/1.txt");
  12. File file2 = new File("/usr/Prom/eclipse/testAll/src/FileFilter/2.txt");
  13. File file3 = new File("/usr/Prom/eclipse/testAll/src/FileFilter/3.txt");
  14. // 如果没有目标文件就创建
  15. if (!file1.exists()) {
  16. file1.createNewFile();
  17. }
  18. if (!file2.exists()) {
  19. file2.createNewFile();
  20. }
  21. if (!file3.exists()) {
  22. file3.createNewFile();
  23. }
  24. //将流对象放入集合中,便于合并。
  25. ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
  26. al.add(new FileInputStream(file1));
  27. al.add(new FileInputStream(file2));
  28. al.add(new FileInputStream(file3));
  29. //获取迭代器
  30. Enumeration<FileInputStream> en = Collections.enumeration(al);
  31. //通过序列流将三个流串起来
  32. SequenceInputStream sis = new SequenceInputStream(en);
  33. FileOutputStream fos = new FileOutputStream("/usr/Prom/eclipse/testAll/src/FileFilter/1234.txt");
  34. byte[] buf = new byte[1024];
  35. int len = 0;
  36. while((len=sis.read(buf))!=-1){
  37. fos.write(buf,0,len);
  38. }
  39. fos.close();
  40. sis.close();
  41. }

字符流

编码与解码

编码就是把字符转换为字节,而解码是把字节重新组合成字符。

如果编码和解码过程使用不同的编码方式那么就出现了乱码。

  • GBK 编码中,中文字符占 2 个字节,英文字符占 1 个字节;
  • UTF-8 编码中,中文字符占 3 个字节,英文字符占 1 个字节;
  • UTF-16be 编码中,中文字符和英文字符都占 2 个字节。

UTF-16be 中的 be 指的是 Big Endian,也就是大端。相应地也有 UTF-16le,le 指的是 Little Endian,也就是小端。

Java 使用双字节编码 UTF-16be,这不是指 Java 只支持这一种编码方式,而是说 char 这种类型使用 UTF-16be 进行编码。char 类型占 16 位,也就是两个字节,Java 使用这种双字节编码是为了让一个中文或者一个英文都能使用一个 char 来存储。

补充:大端和小端:
小端字节序:低字节存于内存低地址;高字节存于内存高地址。如一个long型数据0x12345678

  1.         0x0029f458  0x78
  2.         0x0029f459  0x56
  3.         0x0029f45a  0x34
  4.         0x0029f45b  0x12

在以上数据存放于内存中的表现形式中,0x0029f458 < 0x0029f459 < 0x0029f45a < 0x0029f45b,可以知道内存的地址是由低到高的顺序;而数据的字节也是由低到高的,故以上字节序是小端字节序。

大端字节序:高字节存于内存低地址;低字节存于内存高地址。

  1.         0x0029f458  0x12
  2.         0x0029f459  0x34
  3.         0x0029f45a  0x56
  4.         0x0029f45b  0x79

在以上数据存放于内存中的表现形式中,0x0029f458 < 0x0029f459 < 0x0029f45a < 0x0029f45b,可以知道内存的地址是由低到高的顺序;而数据的字节却是由高到低的,故以上字节序是大端字节序。

Java提供了方法测试平台的大小端,程序如下:

  1. public class EndianTest {
  2. public static void endianTest() {
  3. if(ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
  4. System.out.println("big endian");
  5. else
  6. System.out.println("little endian");
  7. }
  8. public static void main(String[] args) {
  9. EndianTest.endianTest();
  10. }
  11. }

ByteOrder属于java.nio.ByteOrder,它的原理如下:

  1. public static ByteOrder nativeOrder() {
  2. return Bits.byteOrder();
  3. }
  1. static ByteOrder byteOrder() {
  2. if (byteOrder == null)
  3. throw new Error("Unknown byte order");
  4. return byteOrder;
  5. }
  6. static {
  7. long a = unsafe.allocateMemory(8);
  8. try {
  9. unsafe.putLong(a, 0x0102030405060708L);
  10. byte b = unsafe.getByte(a);
  11. switch (b) {
  12. case 0x01: byteOrder = ByteOrder.BIG_ENDIAN; break;
  13. case 0x08: byteOrder = ByteOrder.LITTLE_ENDIAN; break;
  14. default:
  15. assert false;
  16. byteOrder = null;
  17. }
  18. } finally {
  19. unsafe.freeMemory(a);
  20. }
  21. }

可以模仿着自己写一个:

  1. public class TestEndian{
  2. private static final int a = 0x12345678;
  3. public static void test(){
  4. char ch = (char)a;
  5. if(0x12 == ch){
  6. System.out.println("大端!");
  7. }
  8. else{
  9. assert(ch == 0x78);
  10. System.out.println("小端!");
  11. }
  12. }
  13. public static void main(String[] args){
  14. TestEndian.test();
  15. }
  16. }

String 的编码方式

String 可以看成一个字符序列,可以指定一个编码方式将它编码为字节序列,也可以指定一个编码方式将一个字节序列解码为 String。

  1. String str1 = "中文";
  2. byte[] bytes = str1.getBytes("UTF-8");
  3. String str2 = new String(bytes, "UTF-8");
  4. System.out.println(str2);

在调用无参数 getBytes() 方法时,默认的编码方式不是 UTF-16be。双字节编码的好处是可以使用一个 char 存储中文和英文,而将 String 转为 bytes[] 字节数组就不再需要这个好处,因此也就不再需要双字节编码。getBytes() 的默认编码方式与平台有关,一般为 UTF-8。

  1. byte[] bytes = str1.getBytes();

常用字符流——FileReader和FileWriter

与FileInputStrem和FileOutPutStrem类似,FileReader和FileWriter的写入和读取方式有3中,如下:

  • 直接读取和写入单个字节。这种方式效率很低,应该避免使用。
  • 创建固定大小的缓冲区。推荐使用。
  • 使用BufferedInputStream和BufferedOutputStream。推荐使用。

具体如下所示:

  1. /**
  2. * 将一个文本文件中的数据写入另一个文本文件。
  3. */
  4. public class FileReaderWriterDemo {
  5. public static void main(String[] args) {
  6. String fromPath = "D:\\Prom\\testAll\\src\\IO\\FileReaderWriterDemo\\0.txt";
  7. String toPath = "D:\\Prom\\testAll\\src\\IO\\FileReaderWriterDemo\\1.txt";
  8. // readWriteDemo_1(fromPath, toPath);
  9. // readWriteDemo_2(fromPath, toPath);
  10. readWriteDemo_3(fromPath, toPath);
  11. }
  12. /**
  13. * 直接读取写入的方式,效率低下,不建议使用。
  14. * @param fromPath
  15. * @param toPath
  16. */
  17. public static void readWriteDemo_1(String fromPath, String toPath){
  18. FileReader fr = null;
  19. FileWriter fw = null;
  20. try {
  21. fr = new FileReader(fromPath);
  22. fw = new FileWriter(toPath);
  23. //直接读取
  24. int ch = 0;
  25. while((ch = fr.read()) != -1){
  26. fw.write(ch);
  27. }
  28. } catch (FileNotFoundException e) {
  29. e.printStackTrace();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. } finally {
  33. if(fr != null){
  34. try {
  35. fr.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. if(fw != null){
  41. try {
  42. fw.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48. }
  49. /**
  50. * 自定义字符数组作为缓冲区,建议使用。
  51. * @param fromPath
  52. * @param toPath
  53. */
  54. public static void readWriteDemo_2(String fromPath, String toPath){
  55. FileReader fr = null;
  56. FileWriter fw = null;
  57. try {
  58. fr = new FileReader(fromPath);
  59. fw = new FileWriter(toPath);
  60. //注意和FileInputStream不同的是,这里读取的是字符,所以要新建字符数组做缓冲区。
  61. char[] buf = new char[1024];
  62. int len = 0;
  63. while((len = fr.read(buf)) != -1){
  64. fw.write(buf, 0, len);
  65. }
  66. } catch (FileNotFoundException e) {
  67. e.printStackTrace();
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. } finally {
  71. if(fr != null){
  72. try {
  73. fr.close();
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. if(fw != null){
  79. try {
  80. fw.close();
  81. } catch (IOException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. }
  86. }
  87. /**
  88. * 使用BufferedReader和BufferedWriter,建议使用。
  89. * @param fromPath
  90. * @param toPath
  91. */
  92. public static void readWriteDemo_3(String fromPath, String toPath){
  93. BufferedReader bufr = null;
  94. BufferedWriter bufw = null;
  95. try {
  96. bufr = new BufferedReader(new FileReader(fromPath));
  97. bufw = new BufferedWriter(new FileWriter(toPath));
  98. String line = null;
  99. while((line = bufr.readLine()) != null){
  100. bufw.write(line);
  101. bufw.newLine();
  102. bufw.flush();
  103. }
  104. } catch (FileNotFoundException e) {
  105. e.printStackTrace();
  106. } catch (IOException e) {
  107. e.printStackTrace();
  108. } finally {
  109. if(bufr != null){
  110. try {
  111. bufr.close();
  112. } catch (IOException e) {
  113. e.printStackTrace();
  114. }
  115. }
  116. if(bufw != null){
  117. try {
  118. bufw.close();
  119. } catch (IOException e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. }
  124. }
  125. }

其他字符流

字符打印流——PrintWriter(类比PrintStream)

构造函数可以接收四种类型的值。

  • 字符串路径(可以指定编码表);
  • File对象(可以指定编码表);
  • OutputStream(可以指定自动刷新);
  • Writer(可以指定自动刷新);
  1. public static void printWriterDemo() throws IOException {
  2. BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  3. PrintWriter out = new PrintWriter(new FileWriter("/usr/Prom/eclipse/testAll/src/FileFilter/out.txt"), true); //true表示自动刷新
  4. String line = null;
  5. while((line = bufr.readLine()) != null) {
  6. if("over".equals(line))
  7. break;
  8. out.println(line);
  9. }
  10. out.close();
  11. bufr.close();
  12. }

LineNumberReader

LineNumberReader是BufferedReader的子类,也是一个装饰类。它可以允许我们从文件的任一行读到任一行,还可以通过setLineNumber()方法改变当前行号。但是这个方法只是改变私有变量lineNumber的值,并不能改变文件物理的指针位置。

  1. public class LineNumberReaderDemo {
  2. public static void main(String[] args) throws IOException {
  3. FileReader fr = null;
  4. LineNumberReader lnr = null;
  5. int i;
  6. try{
  7. // create new reader
  8. fr = new FileReader("/usr/Prom/eclipse/testAll/src/FileFilter/test.txt");
  9. lnr = new LineNumberReader(fr);
  10. // set current line number
  11. lnr.setLineNumber(100);
  12. System.out.println("setLineNumber(100) is invoked");
  13. // get current line number
  14. i = lnr.getLineNumber();
  15. System.out.println("Current line number: "+i);
  16. String line = null;
  17. while((line = lnr.readLine()) != null) {
  18. System.out.println(lnr.getLineNumber()+":"+line);
  19. }
  20. }catch(Exception e){
  21. // if any error occurs
  22. e.printStackTrace();
  23. }finally{
  24. // closes the stream and releases system resources
  25. if(fr!=null)
  26. fr.close();
  27. if(lnr!=null)
  28. lnr.close();
  29. }
  30. }
  31. }

打印结果为:

  1. setLineNumber(100) is invoked
  2. Current line number: 100
  3. 101:abcde
  4. 102:fghij
  5. 103:klmno

以下实现了从任一行读到任一行的功能:

  1. public class Ex7 {
  2. public void dataReader(String nameFile, int start, int finish) {
  3. if (start > finish) {
  4. System.out.println("Error start or finish!");
  5. return;
  6. }
  7. InputStream inputStream = null;
  8. LineNumberReader reader = null;
  9. try {
  10. inputStream = new FileInputStream(new File(nameFile));
  11. reader = new LineNumberReader(
  12. new InputStreamReader(inputStream));
  13. int lines = getTotalLines(new File(nameFile));
  14. if (start < 0 || finish < 0 || finish > lines || start > lines) {
  15. System.out.println("Line not found!");
  16. return;
  17. }
  18. String line = reader.readLine();
  19. lines = 0;
  20. while (line != null) {
  21. lines++;
  22. if(lines >= start && lines <= finish){
  23. System.out.println(line);
  24. }
  25. line = reader.readLine();
  26. }
  27. inputStream.close();
  28. reader.close();
  29. } catch (FileNotFoundException e) {
  30. e.printStackTrace();
  31. } catch (IOException e) {
  32. System.err.println("IO Error");
  33. System.exit(0);
  34. }
  35. }
  36. private int getTotalLines(File file) throws IOException{
  37. FileReader in = new FileReader(file);
  38. LineNumberReader reader = new LineNumberReader(in);
  39. String line = reader.readLine();
  40. int lines = 0;
  41. while (line != null) {
  42. lines++;
  43. line = reader.readLine();
  44. }
  45. reader.close();
  46. in.close();
  47. return lines;
  48. }
  49. public static void main(String[] args) {
  50. new Ex7().dataReader("/usr/Prom/eclipse/testAll/src/FileFilter/data.txt", 2, 4);
  51. System.out.println();
  52. new Ex7().dataReader("/usr/Prom/eclipse/testAll/src/FileFilter/data.txt",3,8);
  53. }
  54. }

转换流——InputStreamReader 、OutputStreamWriter

InputStreamReader 、OutputStreamWriter要InputStream或OutputStream作为参数,实现从字节流到字符流的转换。

构造函数如下:

  1. InputStreamReader(InputStream); //通过构造函数初始化,使用的是本系统默认的编码表GBK。
  2. InputStreamReader(InputStream,String charSet); //通过该构造函数初始化,可以指定编码表。
  3. OutputStreamWriter(OutputStream); //通过该构造函数初始化,使用的是本系统默认的编码表GBK。
  4. OutputStreamwriter(OutputStream,String charSet); //通过该构造函数初始化,可以指定编码表。

例子如下:

  • 将键盘录入的信息写入到一个文本文件中。
  1. public class InputStreamReaderDemo {
  2. public static void main(String[] args) {
  3. String toPath = "/usr/Prom/eclipse/testAll/src/IO/to.txt";
  4. inputStreamReaderDemo_1(toPath);
  5. }
  6. public static void inputStreamReaderDemo_1(String toPath) {
  7. BufferedReader bufr = null;
  8. BufferedWriter bufw = null;
  9. try {
  10. //将字节流转化为字符流。
  11. bufr = new BufferedReader(new InputStreamReader(System.in));
  12. bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath)));
  13. String line = null;
  14. while((line = bufr.readLine()) != null) {
  15. if("over".equals(line)){
  16. break;
  17. }
  18. bufw.write(line.toUpperCase());
  19. bufw.newLine();
  20. bufw.flush();
  21. }
  22. } catch (FileNotFoundException e1) {
  23. e1.printStackTrace();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. } finally {
  27. if(bufr != null) {
  28. try {
  29. bufr.close();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. if(bufw != null) {
  35. try {
  36. bufw.close();
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  42. }
  43. }
  • 将一个文本文件内容显示在控制台上。其实这个功能用前面的FileInputStrem和FileOutPutStrem或者FileWriter和FileReader可以实现,先读到缓冲区中,再将缓冲区转化成字符串打印出来,可以看前面具体的例子。
    但是前面的方式不能指定编码类型。
  1. public class OutputStreamWriterDemo {
  2. public static void main(String[] args) {
  3. String toPath = "/usr/Prom/eclipse/testAll/src/IO/to.txt";
  4. outputStreamWriterDemo(toPath);
  5. }
  6. public static void outputStreamWriterDemo(String fromPath) {
  7. BufferedReader bufr = null;
  8. BufferedWriter bufw = null;
  9. try {
  10. //将字节流转化为字符流。
  11. //相比上面的程序,改变了这两行,并且加上使用“GBK”编码的限制。
  12. bufr = new BufferedReader(new InputStreamReader(new FileInputStream(fromPath)));
  13. bufw = new BufferedWriter(new OutputStreamWriter(System.out, "GBK"));
  14. String line = null;
  15. while((line = bufr.readLine()) != null) {
  16. bufw.write(line.toUpperCase());
  17. bufw.newLine();
  18. bufw.flush();
  19. }
  20. } catch (FileNotFoundException e1) {
  21. e1.printStackTrace();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } finally {
  25. if(bufr != null) {
  26. try {
  27. bufr.close();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. if(bufw != null) {
  33. try {
  34. bufw.close();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40. }
  41. }
  • 将一个文本文件中的内容以“GBK”编码的格式复制到另一个文本文件中。同样的,这个功能用前面的FileInputStrem和FileOutPutStrem或者FileWriter和FileReader可以实现,但是前面的方式不能指定编码类型。
  1. public class ReadAndWriterDemo {
  2. public static void main(String[] args) {
  3. String fromPath = "/usr/Prom/eclipse/testAll/src/IO/from.txt";
  4. String toPath = "/usr/Prom/eclipse/testAll/src/IO/to.txt";
  5. readAndWriterDemo(fromPath, toPath);
  6. }
  7. public static void readAndWriterDemo(String fromPath, String toPath) {
  8. BufferedReader bufr = null;
  9. BufferedWriter bufw = null;
  10. try {
  11. //将字节流转化为字符流。
  12. //相比上面的程序,改变了这两行,并且加上使用“GBK”编码的限制。
  13. bufr = new BufferedReader(new InputStreamReader(new FileInputStream(fromPath), "GBK"));
  14. bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath), "GBK"));
  15. String line = null;
  16. while((line = bufr.readLine()) != null) {
  17. bufw.write(line.toUpperCase());
  18. bufw.newLine();
  19. bufw.flush();
  20. }
  21. } catch (FileNotFoundException e1) {
  22. e1.printStackTrace();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. } finally {
  26. if(bufr != null) {
  27. try {
  28. bufr.close();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. if(bufw != null) {
  34. try {
  35. bufw.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. }
  42. }

三、磁盘操作——File

File 类可以用于表示文件和目录的信息,但是它不表示文件的内容。

基本操作

文件或文件夹的创建

主要涉及到三个方法:

  • createNewFile():创建文件,这句话后,才真正在磁盘上创建了文件。
  • mkdir()://创建目录,如果新建的目录的上级目录不存在会报异常不能成功创建文件夹。
  • mkdirs()://创建目录,如果新建的目录的上级目录不存在则会将目录与上级目录一起创建。
  1. public static void createFile() throws IOException {
  2. //创建了file对象并不是创建了真实的文件,执行这句话后,如果文件不存在,并没有创建
  3. File file = new File("/usr/Prom/eclipse/testAll/src/FileTest/createFile.txt");
  4. File dir = new File("/usr/Prom/eclipse/testAll/src/FileTest/dir");
  5. File dir_1 = new File("/usr/Prom/eclipse/testAll/src/FileTest/dir_1/a.txt");
  6. if(!file.exists())
  7. file.createNewFile(); //创建文件,这句话后,才真正在磁盘上创建了文件
  8. if(!dir.exists())
  9. dir.mkdir(); //创建目录,如果新建的目录的上级目录不存在会报异常不能成功创建文件夹
  10. if(!dir_1.exists())
  11. dir_1.mkdirs(); //创建目录,如果新建的目录的上级目录不存在则会将目录与上级目录一起创建。
  12. }

判断文件或文件夹属性

isFile()和isDirectory()分别用于判断是不是文件和是不是文件夹,canRead(),canWrite(),isHidden(),分别用于判断文件是否可读,可写,是否隐藏。

  1. public static void judgeFile(File file) {
  2. file.setReadable(true); //设置文件可读
  3. file.setWritable(false); //设置文件不可写
  4. System.out.println(file.isFile()); //判断是不是文件
  5. System.out.println(file.isDirectory()); //判断是不是路径
  6. System.out.println(file.isHidden()); //判断是不是隐藏文件
  7. System.out.println(file.canRead()); //判断是不是可读
  8. System.out.println(file.canWrite()); //判断是不是可写
  9. }

文件或文件夹的删除

删除一个文件比较简单,直接判断文件是否存在,如果存在的话就删除,如果文件不存在可以不用操作。但是删除一个文件夹比较麻烦,我们不能够直接的删除一个文件夹,删除文件夹时必须保证该文件夹为空,也就是说文件夹里面的文件和文件夹要全部被删除之后才能够删除该文件夹。

递归删除一个文件或路径

  1. /**
  2. * 删除文件或路径,参数为File
  3. * @param file
  4. */
  5. public static void removeFiles(File file) {
  6. File[] files = file.listFiles();
  7. for(File f : files) {
  8. if(f.isDirectory())
  9. removeFiles(f);
  10. else
  11. System.out.println(f+":"+f.delete());
  12. }
  13. System.out.println(file+":"+file.delete());
  14. }
  15. /**
  16. * 删除文件或路径,参数为路径的字符串表示
  17. * @param dir
  18. */
  19. public static void deleteFiles(String dir) {
  20. File file = new File(dir);
  21. if(!file.exists())
  22. return;
  23. if(file.isFile())
  24. System.out.println(file+":"+file.delete());
  25. else if(file.isDirectory()) {
  26. File[] files = file.listFiles();
  27. for(File f : files) {
  28. System.out.print(":"+f.getAbsolutePath());
  29. deleteFiles(f.getAbsolutePath());
  30. }
  31. }
  32. System.out.println(file+":"+file.delete());
  33. }

和流的联合使用

将一个文件中的内容复制到另一个文件中。

  1. public class FileTest {
  2. public static void main(String[] args) throws IOException {
  3. String fromPath = "/usr/Prom/eclipse/testAll/src/IO/from.txt";
  4. String toPath = "/usr/Prom/eclipse/testAll/src/IO/to.txt";
  5. readWriteDemo(fromPath, toPath);
  6. }
  7. public static void readWriteDemo(String fromPath, String toPath) throws IOException{
  8. File fileFrom = new File(fromPath);
  9. File fileTo = new File(toPath);
  10. if(!fileFrom.exists())
  11. fileFrom.createNewFile();
  12. if(!fileTo.exists())
  13. fileTo.createNewFile();
  14. FileReader fr = null;
  15. FileWriter fw = null;
  16. try {
  17. fr = new FileReader(fileFrom);
  18. fw = new FileWriter(fileTo);
  19. //注意和FileInputStream不同的是,这里读取的是字符,所以要新建字符数组做缓冲区。
  20. char[] buf = new char[1024];
  21. int len = 0;
  22. while((len = fr.read(buf)) != -1){
  23. fw.write(buf, 0, len);
  24. }
  25. } catch (FileNotFoundException e) {
  26. e.printStackTrace();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. } finally {
  30. if(fr != null){
  31. try {
  32. fr.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. if(fw != null){
  38. try {
  39. fw.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. }

文件过滤器

在java中,专门提供了文件过滤器接口.

  1. public interface FilenameFilter    accept(File dirs,String name)
  2. public interface FileFilter       accept(File pathname);

下面看具体的应用。

需要注意list方法和listFiles方法的两点区别:

  • 返回值类型不同:前者为String数组,后者为File对象数组
  • 数组中元素内容不同:前者为string类型的【文件名】(包含后缀名),后者为File对象类型的【完整路径】。
    因此,遍历文件夹中所有文件,包括子文件夹中的文件时,必须用listFiles()方法
  1. /**
  2. * 后缀名过滤
  3. */
  4. public static void fileFilterDemo() {
  5. File dir = new File("/usr/Prom/eclipse/testAll/src/FileFilter/11");
  6. if(!dir.exists())
  7. dir.mkdirs();
  8. //list方法的参数不能为FileFlter
  9. File[] fileList = dir.listFiles(new FileFilter() {
  10. @Override
  11. public boolean accept(File pathname) {
  12. return !pathname.isHidden();
  13. }
  14. });
  15. for(File f : fileList) {
  16. System.out.println(f);
  17. }
  18. }
  19. /**
  20. * 隐藏文件过滤
  21. */
  22. public static void fileNameFilterDemo() {
  23. File dir = new File("/usr/Prom/eclipse/testAll/src/FileFilter/11");
  24. if(!dir.exists())
  25. dir.mkdirs();
  26. //使用listFiles方法也行
  27. String[] fileList = dir.list(new FilenameFilter() {
  28. @Override
  29. public boolean accept(File dir, String name) {
  30. return name.endsWith(".java");
  31. }
  32. });
  33. for(String f : fileList) {
  34. System.out.println(f);
  35. }
  36. }

File和Properties

Properties继承自Hashtable,属于Map体系,主要用于生产配置文件与读取配置文件的信息。它可以和IO流结合,从流中读取配置文件的信息加载到Properties对象中,在对象中完成对配置文件中信息的修改后再通过流将信息写入到文件中,相当于是一个中间的操作过程。Properties中的键和值都是字符串类型。

看一下具体的例子:

  1. public static void main(String[] args) throws IOException {
  2. String filePath = "/usr/Prom/eclipse/testAll/src/FileFilter/test.properties";
  3. //创建File对象,配置文件的后缀名一般也叫properties
  4. File file = new File(filePath);
  5. if(!file.exists())
  6. file.createNewFile();
  7. creatProperties(file);
  8. readProperties(file);
  9. }
  10. //读取配置文件的信息
  11. public static void readProperties(File file) throws IOException{
  12. if(!file.exists())
  13. return;
  14. //创建Properties对象
  15. Properties properties = new Properties();
  16. //加载配置文件信息到Properties中
  17. properties.load(new FileReader(file));
  18. //遍历
  19. Set<Entry<Object, Object>> entrys = properties.entrySet();
  20. for(Entry<Object, Object> entry :entrys){
  21. System.out.println("键:"+ entry.getKey() +" 值:"+ entry.getValue());
  22. }
  23. //修改狗娃的密码
  24. properties.setProperty("狗娃", "007");
  25. //把修改后的Properties写回配置文件
  26. properties.store(new FileWriter(file), "info");
  27. }
  28. //保存配置文件文件的信息。
  29. public static void creatProperties(File file) throws IOException{
  30. if(!file.exists())
  31. return;
  32. //创建Properties
  33. Properties properties = new Properties();
  34. properties.setProperty("狗娃", "123");
  35. properties.setProperty("狗剩","234");
  36. properties.setProperty("铁蛋","345");
  37. //第一个参数是一个输出流对象,第二参数是使用一个字符串描述这个配置文件的信息。
  38. properties.store(new FileWriter(file), "info");
  39. }

另一个例子:定义功能,获取一个应用程序运行的次数,如果超过3次,给出使用次数已到请注册的提示。并不要在运行
程序。

  1. public class GetCounts {
  2. public static void main(String[] args) throws IOException {
  3. String filePath = "/usr/Prom/eclipse/testAll/src/FileFilter/times.properties";
  4. getCounts(filePath);
  5. }
  6. public static void getCounts(String filePath) throws IOException {
  7. File file = new File(filePath);
  8. if(!file.exists()){
  9. //如果配置文件不存在,则创建该配置文件
  10. file.createNewFile();
  11. }
  12. //创建Properties对象。
  13. Properties properties = new Properties();
  14. //把配置文件的信息加载到properties中
  15. properties.load(new FileInputStream(file));
  16. FileOutputStream fileOutputStream = new FileOutputStream(file);
  17. int count = 0; //定义该变量是用于保存软件的运行次数的。
  18. //读取配置文件的运行次数
  19. String value = properties.getProperty("count");
  20. if(value!=null){
  21. count = Integer.parseInt(value);
  22. }
  23. //判断使用的次数是否已经达到了三次,
  24. if(count==3){
  25. System.out.println("你已经超出了试用次数,请购买正版软件!!");
  26. System.exit(0);
  27. }
  28. count++;
  29. System.out.println("你已经使用了本软件第"+count+"次");
  30. properties.setProperty("count",count+"");
  31. //使用Properties生成一个配置文件
  32. properties.store(fileOutputStream,"runtime");
  33. fileOutputStream.close();
  34. }
  35. }

流和File综合练习

实现两个函数,一个实现文件切割功能,一个实现文件合并功能。

  1. private static final int SIZE = 1024 * 1024;
  2. public static void main(String[] args) throws IOException {
  3. File file = new File("/usr/Prom/eclipse/testAll/src/FileFilter/fate.mp3");
  4. File dir = new File("/usr/Prom/eclipse/testAll/src/");
  5. if(!file.exists())
  6. file.createNewFile();
  7. if(!dir.exists())
  8. dir.mkdirs();
  9. spiliteFile(file);
  10. mergeFile(dir);
  11. }
  12. /**
  13. * 切割文件
  14. * @param file
  15. * @throws IOException
  16. */
  17. public static void spiliteFile(File file) throws IOException {
  18. if(!file.exists())
  19. return;
  20. // 用读取流关联源文件。
  21. FileInputStream fis = new FileInputStream(file);
  22. // 定义一个1M的缓冲区。
  23. byte[] buf = new byte[SIZE];
  24. // 创建目的。
  25. FileOutputStream fos = null;
  26. int len = 0;
  27. int count = 1;
  28. /*
  29. * 切割文件时,必须记录住被切割文件的名称,以及切割出来碎片文件的个数。 以方便于合并。
  30. * 这个信息为了进行描述,使用键值对的方式。用到了properties对象
  31. */
  32. Properties prop = new Properties();
  33. File dir = new File("/usr/Prom/eclipse/testAll/src");
  34. if (!dir.exists())
  35. dir.mkdirs();
  36. while ((len = fis.read(buf)) != -1) {
  37. fos = new FileOutputStream(new File(dir, (count++) + ".part"));
  38. fos.write(buf, 0, len);
  39. fos.close();
  40. }
  41. //将被切割文件的信息保存到prop集合中。
  42. prop.setProperty("partcount", count+"");
  43. prop.setProperty("filename", file.getName());
  44. fos = new FileOutputStream(new File(dir,count+".properties"));
  45. //将prop集合中的数据存储到文件中。
  46. prop.store(fos, "save file info");
  47. fos.close();
  48. fis.close();
  49. }
  50. /**
  51. * 合并文件
  52. * @param dir
  53. * @throws IOException
  54. */
  55. public static void mergeFile(File dir) throws IOException {
  56. /*
  57. * 获取指定目录下的配置文件对象。
  58. */
  59. File[] files = dir.listFiles(new SuffixFilter(".properties"));
  60. if(files.length != 1)
  61. throw new RuntimeException(dir+",该目录下没有properties扩展名的文件或者不唯一");
  62. //记录配置文件对象。
  63. File confile = files[0];
  64. //获取该文件中的信息
  65. Properties prop = new Properties();
  66. FileInputStream fis = new FileInputStream(confile);
  67. prop.load(fis);
  68. String filename = prop.getProperty("filename");
  69. int count = Integer.parseInt(prop.getProperty("partcount"));
  70. //获取该目录下的所有碎片文件
  71. File[] partFiles = dir.listFiles(new SuffixFilter(".part"));
  72. if(partFiles.length!=(count-1)){
  73. throw new RuntimeException(" 碎片文件不符合要求,个数不对!应该"+count+"个");
  74. }
  75. //将碎片文件和流对象关联 并存储到集合中。
  76. ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
  77. for(int x=0; x<partFiles.length; x++){
  78. al.add(new FileInputStream(partFiles[x]));
  79. }
  80. //将多个流合并成一个序列流。
  81. Enumeration<FileInputStream> en = Collections.enumeration(al);
  82. SequenceInputStream sis = new SequenceInputStream(en);
  83. FileOutputStream fos = new FileOutputStream(new File(dir,filename));
  84. byte[] buf = new byte[1024];
  85. int len = 0;
  86. while((len=sis.read(buf))!=-1){
  87. fos.write(buf,0,len);
  88. }
  89. fos.close();
  90. sis.close();
  91. }
  92. /**
  93. * 后缀名过滤器
  94. * @author adamhand
  95. */
  96. static class SuffixFilter implements FilenameFilter{
  97. private String suffix;
  98. public SuffixFilter(String suffix) {
  99. this.suffix = suffix;
  100. }
  101. public boolean accept(File dir, String name) {
  102. return name.endsWith(suffix);
  103. }
  104. }

四、对象操作

序列化

序列化就是将一个对象转换成字节序列,方便存储和传输。

  • 序列化:ObjectOutputStream.writeObject()
  • 反序列化:ObjectInputStream.readObject()

不会对静态变量进行序列化,因为序列化只是保存对象的状态,静态变量属于类的状态。

Serializable

序列化的类需要实现 Serializable 接口,它只是一个标准,没有任何方法需要实现,但是如果不去实现它的话而进行序列化,会抛出异常。

  1. public static void main(String[] args) throws IOException, ClassNotFoundException {
  2. A a1 = new A(123, "abc");
  3. String objectFile = "file/a1";
  4. ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
  5. objectOutputStream.writeObject(a1);
  6. objectOutputStream.close();
  7. ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
  8. A a2 = (A) objectInputStream.readObject();
  9. objectInputStream.close();
  10. System.out.println(a2);
  11. }
  12. private static class A implements Serializable {
  13. private int x;
  14. private String y;
  15. A(int x, String y) {
  16. this.x = x;
  17. this.y = y;
  18. }
  19. @Override
  20. public String toString() {
  21. return "x = " + x + " " + "y = " + y;
  22. }
  23. }

transient

transient 关键字可以使一些属性不会被序列化。

ArrayList 中存储数据的数组 elementData 是用 transient 修饰的,因为这个数组是动态扩展的,并不是所有的空间都被使用,因此就不需要所有的内容都被序列化。通过重写序列化和反序列化方法,使得可以只序列化数组中有内容的那部分数据。

  1. private transient Object[] elementData;

五、网络操作

Java 中的网络支持:

  • InetAddress:用于表示网络上的硬件资源,即 IP 地址;
  • URL:统一资源定位符;
  • Sockets:使用 TCP 协议实现网络通信;
  • Datagram:使用 UDP 协议实现网络通信。

InetAddress

没有公有的构造函数,只能通过静态方法来创建实例。

  1. InetAddress.getByName(String host);
  2. InetAddress.getByAddress(byte[] address);

URL

可以直接从 URL 中读取字节流数据。

  1. public static void main(String[] args) throws IOException {
  2. URL url = new URL("http://www.baidu.com");
  3. /* 字节流 */
  4. InputStream is = url.openStream();
  5. /* 字符流 */
  6. InputStreamReader isr = new InputStreamReader(is, "utf-8");
  7. /* 提供缓存功能 */
  8. BufferedReader br = new BufferedReader(isr);
  9. String line;
  10. while ((line = br.readLine()) != null) {
  11. System.out.println(line);
  12. }
  13. br.close();
  14. }

openConnection()方法会返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
每次调用此 URL 的协议处理程序的 openConnection 方法都打开一个新的连接。如果 URL 的协议(例如,HTTP 或 JAR)存在属于以下包或其子包之一的公共、专用 URLConnection 子类:java.lang、java.io、java.util、java.net,返回的连接将为该子类的类型。例如,对于 HTTP,将返回 HttpURLConnection,对于 JAR,将返回 JarURLConnection。

  1. public class URLConnDemo
  2. {
  3. public static void main(String [] args)
  4. {
  5. try
  6. {
  7. URL url = new URL("http://www.baidu.com");
  8. URLConnection urlConnection = url.openConnection();
  9. HttpURLConnection connection = null;
  10. if(urlConnection instanceof HttpURLConnection)
  11. {
  12. connection = (HttpURLConnection) urlConnection;
  13. }
  14. else
  15. {
  16. System.out.println("请输入 URL 地址");
  17. return;
  18. }
  19. BufferedReader in = new BufferedReader(
  20. new InputStreamReader(connection.getInputStream()));
  21. String urlString = "";
  22. String current;
  23. while((current = in.readLine()) != null)
  24. {
  25. urlString += current;
  26. }
  27. System.out.println(urlString);
  28. }catch(IOException e)
  29. {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

TCP——Sockets

  • ServerSocket:服务器端类
  • Socket:客户端类
  • 服务器和客户端通过 InputStream 和 OutputStream 进行输入输出。



下面是一个上传图片的案例:

  1. /**
  2. * 上传任务
  3. */
  4. public class UploadTask implements Runnable {
  5. private static final int _2MB = 1024 * 1024 * 2;
  6. private Socket s;
  7. public UploadTask(Socket s) {
  8. this.s = s;
  9. }
  10. @Override
  11. public void run() {
  12. int count = 0;
  13. String ip = s.getInetAddress().getHostAddress();
  14. System.out.println(ip + "connected");
  15. try{
  16. // 读取客户端发来的数据。
  17. InputStream in = s.getInputStream();
  18. // 将读取到数据存储到一个文件中。
  19. File dir = new File("/usr/Prom/eclipse/testAll/src/TCP/pic");
  20. if (!dir.exists()) {
  21. dir.mkdirs();
  22. }
  23. File file = new File(dir, ip + ".jpeg");
  24. //如果文件已经存在于服务端
  25. while(file.exists()){
  26. file = new File(dir,ip+"("+(++count)+").jpeg");
  27. }
  28. FileOutputStream fos = new FileOutputStream(file);
  29. byte[] buf = new byte[1024];
  30. int len = 0;
  31. while ((len = in.read(buf)) != -1) {
  32. fos.write(buf, 0, len);
  33. if(file.length() > _2MB){
  34. System.out.println(ip+"文件体积过大");
  35. fos.close();
  36. s.close();
  37. System.out.println(ip+"...."+file.delete());
  38. return ;
  39. }
  40. }
  41. // 获取socket输出流, 将上传成功字样发给客户端。
  42. OutputStream out = s.getOutputStream();
  43. out.write("上传成功".getBytes());
  44. fos.close();
  45. s.close();
  46. }catch(IOException e){
  47. }
  48. }
  49. }
  1. /**
  2. * 上传客户端
  3. */
  4. public class UploadPicClient {
  5. public static void main(String[] args) throws IOException{
  6. //1,创建客户端socket。
  7. Socket s = new Socket("192.168.10.128",10006);
  8. //2,读取客户端要上传的图片文件。
  9. FileInputStream fis = new FileInputStream("/usr/Prom/eclipse/testAll/src/TCP/naruto.jpeg");
  10. //3,获取socket输出流,将读到图片数据发送给服务端。
  11. OutputStream out = s.getOutputStream();
  12. byte[] buf = new byte[1024];
  13. int len = 0;
  14. while((len=fis.read(buf))!=-1){
  15. out.write(buf,0,len);
  16. }
  17. //告诉服务端说:这边的数据发送完毕。让服务端停止读取。
  18. s.shutdownOutput();
  19. //读取服务端发回的内容。
  20. InputStream in = s.getInputStream();
  21. byte[] bufIn = new byte[1024];
  22. int lenIn = in.read(buf);
  23. String text = new String(buf,0,lenIn);
  24. System.out.println(text);
  25. fis.close();
  26. s.close();
  27. }
  28. }
  1. /**
  2. * 上传服务端
  3. */
  4. public class UploadPicServer {
  5. public static void main(String[] args) throws IOException {
  6. //创建tcp的socket服务端。
  7. ServerSocket ss = new ServerSocket(10006);
  8. while(true){
  9. Socket s = ss.accept();
  10. new Thread(new UploadTask(s)).start();
  11. }
  12. }
  13. }

UDP——Datagram

  • DatagramSocket:通信类
  • DatagramPacket:数据包类
    使用UDP实现发送和接受端:
  1. public class Send {
  2. public static void main(String[] args) throws IOException {
  3. System.out.println("send starts");
  4. //1.建立udpsocket服务。使用DatagramSocket对象
  5. DatagramSocket ds = new DatagramSocket();
  6. //2.建立流从键盘读取数据
  7. BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  8. String line = null;
  9. while((line = bufr.readLine()) != null) {
  10. byte[] buf = line.getBytes();
  11. //3.将要发送的数据封装到数据包中。1000是绑定的本地端口。
  12. DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.10.128"), 10000);
  13. //4.发送数据包
  14. ds.send(dp);
  15. if(line.equals("886"))
  16. break;
  17. }
  18. //5.关闭服务
  19. ds.close();
  20. }
  21. }
  1. public class Receive {
  2. public static void main(String[] args) throws IOException {
  3. System.out.println("receive starts");
  4. //1,建立udp socket服务。注意绑定端口
  5. DatagramSocket ds = new DatagramSocket(10000);
  6. while(true){
  7. //2,创建数据包。
  8. byte[] buf = new byte[1024];
  9. DatagramPacket dp = new DatagramPacket(buf,buf.length);
  10. //3,使用接收方法将数据存储到数据包中。
  11. ds.receive(dp);//阻塞式的。
  12. //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
  13. String ip = dp.getAddress().getHostAddress();
  14. int port = dp.getPort();
  15. String text = new String(dp.getData(),0,dp.getLength());
  16. System.out.println(ip+":"+port+":"+text);
  17. }
  18. //5,关闭资源。
  19. // ds.close();
  20. }
  21. }

练习:模拟浏览器(客户端)和Tomcat服务器(服务端)

  1. public class MyBrowser {
  2. public static void main(String[] args) throws IOException{
  3. Socket s = new Socket("192.168.10.128",8080);
  4. //模拟浏览器,给tomcat服务端发送符合http协议的请求消息。
  5. PrintWriter out = new PrintWriter(s.getOutputStream(),true);
  6. out.println("GET /myweb/1.html HTTP/1.1");
  7. out.println("Accept: */*");
  8. out.println("Host: 192.168.10.128:8080");
  9. out.println("Connection: close");
  10. out.println();
  11. out.println();
  12. InputStream in = s.getInputStream();
  13. byte[] buf = new byte[1024];
  14. int len = in.read(buf);
  15. String str =new String(buf,0,len);
  16. System.out.println(str);
  17. s.close();
  18. //http://192.168.10.128:8080/myweb/1.html
  19. }
  20. }
  1. public class MyTomcat {
  2. public static void main(String[] args) throws IOException {
  3. ServerSocket ss = new ServerSocket(8080);
  4. Socket s = ss.accept();
  5. System.out.println(s.getInetAddress().getHostAddress()+".....connected");
  6. InputStream in = s.getInputStream();
  7. byte[] buf = new byte[1024];
  8. int len = in.read(buf);
  9. String text = new String(buf,0,len);
  10. System.out.println(text);
  11. //给客户端一个反馈信息。
  12. PrintWriter out = new PrintWriter(s.getOutputStream(),true);
  13. out.println("<font color='red' size='7'>欢迎光临</font>");
  14. s.close();
  15. ss.close();
  16. }
  17. }

补充

网络结构:

  • C/S client/server
    • 特点:
      该结构的软件,客户端和服务端都需要编写。
      可发成本较高,维护较为麻烦。
    • 好处:
      客户端在本地可以分担一部分运算。
  • B/S browser/server
    • 特点:
      该结构的软件,只开发服务器端,不开发客户端,因为客户端直接由浏览器取代。
      开发成本相对低,维护更为简单。
    • 缺点:所有运算都要在服务端完成。

六、NIO

综述

新的输入/输出 (NIO) 库是在 JDK 1.4 中引入的,弥补了原来的 I/O 的不足,提供了高速的、面向块的 I/O。

nio 底层就是 epoll 是同步非阻塞的。

在NIO中有几个比较关键的概念:Channel(通道),Buffer(缓冲区),Selector(选择器)。可以将NIO 中的Channel同传统IO中的Stream来类比,但是要注意,传统IO中,Stream是单向的,比如InputStream只能进行读取操作,OutputStream只能进行写操作。而Channel是双向的,既可用来进行读操作,又可用来进行写操作。

Buffer(缓冲区),是NIO中非常重要的一个东西,在NIO中所有数据的读和写都离不开Buffer。在NIO中,读取的数据只能放在Buffer中。同样地,写入数据也是先写入到Buffer中。

Selector可以说它是NIO中最关键的一个部分,Selector的作用就是用来轮询每个注册的Channel,一旦发现Channel有注册的事件发生,便获取事件然后进行处理。

流与块

I/O 与 NIO 最重要的区别是数据打包和传输的方式,I/O 以流的方式处理数据,而 NIO 以块的方式处理数据。

面向流的 I/O 一次处理一个字节数据:一个输入流产生一个字节数据,一个输出流消费一个字节数据。为流式数据创建过滤器非常容易,链接几个过滤器,以便每个过滤器只负责复杂处理机制的一部分。不利的一面是,面向流的 I/O 通常相当慢。

面向块的 I/O 一次处理一个数据块,按块处理数据比按流处理数据要快得多。但是面向块的 I/O 缺少一些面向流的 I/O 所具有的优雅性和简单性。

I/O 包和 NIO 已经很好地集成了,java.io.* 已经以 NIO 为基础重新实现了,所以现在它可以利用 NIO 的一些特性。例如,java.io.* 包中的一些类包含以块的形式读写数据的方法,这使得即使在面向流的系统中,处理速度也会更快。

通道与缓冲区

1. 通道

通道 Channel 是对原 I/O 包中的流的模拟,可以通过它读取和写入数据。

通道与流的不同之处在于,流只能在一个方向上移动(一个流必须是 InputStream 或者 OutputStream 的子类),而通道是双向的,可以用于读、写或者同时用于读写。

通道包括以下类型:

  • FileChannel:从文件中读写数据;
  • DatagramChannel:通过 UDP 读写网络中数据;
  • SocketChannel:通过 TCP 读写网络中数据;
  • ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。

2. 缓冲区

发送给一个通道的所有数据都必须首先放到缓冲区中,同样地,从通道中读取的任何数据都要先读到缓冲区中。也就是说,不会直接对通道进行读写数据,而是要先经过缓冲区,如下图所示:



缓冲区实质上是一个数组,但它不仅仅是一个数组。缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程。

缓冲区包括以下类型:

  • ByteBuffer
  • CharBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer

缓冲区状态变量

  • capacity:最大容量;
  • position:当前已经读写的字节数;
  • limit:还可以读写的字节数。

状态变量的改变过程举例:

① 新建一个大小为 8 个字节的缓冲区,此时 position 为 0,而 limit = capacity = 8。capacity 变量不会改变,下面的讨论会忽略它。



② 从输入通道中读取 5 个字节数据写入缓冲区中,此时 position 为 5,limit 保持不变。



③ 在将缓冲区的数据写到输出通道之前,需要先调用 flip() 方法,这个方法将 limit 设置为当前 position,并将 position 设置为 0。



④ 从缓冲区中取 4 个字节到输出缓冲中,此时 position 设为 4。



⑤ 最后需要调用 clear() 方法来清空缓冲区,此时 position 和 limit 都被设置为最初位置。



文件 NIO 实例

以下展示了使用 NIO 快速复制文件的实例:

  1. public static void fastCopy(String src, String dist) throws IOException {
  2. /* 获得源文件的输入字节流 */
  3. FileInputStream fin = new FileInputStream(src);
  4. /* 获取输入字节流的文件通道 */
  5. FileChannel fcin = fin.getChannel();
  6. /* 获取目标文件的输出字节流 */
  7. FileOutputStream fout = new FileOutputStream(dist);
  8. /* 获取输出字节流的文件通道 */
  9. FileChannel fcout = fout.getChannel();
  10. /* 为缓冲区分配 1024 个字节 */
  11. ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
  12. while (true) {
  13. /* 从输入通道中读取数据到缓冲区中 */
  14. int r = fcin.read(buffer);
  15. /* read() 返回 -1 表示 EOF */
  16. if (r == -1) {
  17. break;
  18. }
  19. /* 切换读写 */
  20. buffer.flip();
  21. /* 把缓冲区的内容写入输出文件中 */
  22. fcout.write(buffer);
  23. /* 清空缓冲区 */
  24. buffer.clear();
  25. }
  26. }

选择器

NIO 常常被叫做非阻塞 IO,主要是因为 NIO 在网络通信中的非阻塞特性被广泛使用。

NIO 实现了 IO 多路复用中的 Reactor 模型,一个线程 Thread 使用一个选择器 Selector 通过轮询的方式去监听多个通道 Channel 上的事件,从而让一个线程就可以处理多个事件。

通过配置监听的通道 Channel 为非阻塞,那么当 Channel 上的 IO 事件还未到达时,就不会进入阻塞状态一直等待,而是继续轮询其它 Channel,找到 IO 事件已经到达的 Channel 执行。

因为创建和切换线程的开销很大,因此使用一个线程来处理多个事件而不是一个线程处理一个事件,对于 IO 密集型的应用具有很好地性能。

应该注意的是,只有套接字 Channel 才能配置为非阻塞,而 FileChannel 不能,为 FileChannel 配置非阻塞也没有意义。

用单线程处理一个Selector,然后通过Selector.select()方法来获取到达事件,在获取了到达事件之后,就可以逐个地对这些事件进行响应处理:



1. 创建选择器

  1. Selector selector = Selector.open();

2. 将通道注册到选择器上

  1. ServerSocketChannel ssChannel = ServerSocketChannel.open();
  2. ssChannel.configureBlocking(false);
  3. ssChannel.register(selector, SelectionKey.OP_ACCEPT);

通道必须配置为非阻塞模式,否则使用选择器就没有任何意义了,因为如果通道在某个事件上被阻塞,那么服务器就不能响应其它事件,必须等待这个事件处理完毕才能去处理其它事件,显然这和选择器的作用背道而驰。

在将通道注册到选择器上时,还需要指定要注册的具体事件,主要有以下几类:

  • SelectionKey.OP_CONNECT
  • SelectionKey.OP_ACCEPT
  • SelectionKey.OP_READ
  • SelectionKey.OP_WRITE

它们在 SelectionKey 的定义如下:

  1. public static final int OP_READ = 1 << 0;
  2. public static final int OP_WRITE = 1 << 2;
  3. public static final int OP_CONNECT = 1 << 3;
  4. public static final int OP_ACCEPT = 1 << 4;

可以看出每个事件可以被当成一个位域,从而组成事件集整数。例如:

  1. int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;

3. 监听事件

  1. int num = selector.select();

使用 select() 来监听到达的事件,它会一直阻塞直到有至少一个事件到达。

4. 获取到达的事件

  1. Set<SelectionKey> keys = selector.selectedKeys();
  2. Iterator<SelectionKey> keyIterator = keys.iterator();
  3. while (keyIterator.hasNext()) {
  4. SelectionKey key = keyIterator.next();
  5. if (key.isAcceptable()) {
  6. // ...
  7. } else if (key.isReadable()) {
  8. // ...
  9. }
  10. keyIterator.remove();
  11. }

5. 事件循环

因为一次 select() 调用不能处理完所有的事件,并且服务器端有可能需要一直监听事件,因此服务器端处理事件的代码一般会放在一个死循环内。

  1. while (true) {
  2. int num = selector.select();
  3. Set<SelectionKey> keys = selector.selectedKeys();
  4. Iterator<SelectionKey> keyIterator = keys.iterator();
  5. while (keyIterator.hasNext()) {
  6. SelectionKey key = keyIterator.next();
  7. if (key.isAcceptable()) {
  8. // ...
  9. } else if (key.isReadable()) {
  10. // ...
  11. }
  12. keyIterator.remove();
  13. }
  14. }

套接字 NIO 实例

  1. public class NIOServer {
  2. public static void main(String[] args) throws IOException {
  3. Selector selector = Selector.open();
  4. ServerSocketChannel ssChannel = ServerSocketChannel.open();
  5. ssChannel.configureBlocking(false);
  6. ssChannel.register(selector, SelectionKey.OP_ACCEPT);
  7. ServerSocket serverSocket = ssChannel.socket();
  8. InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
  9. serverSocket.bind(address);
  10. while (true) {
  11. selector.select();
  12. Set<SelectionKey> keys = selector.selectedKeys();
  13. Iterator<SelectionKey> keyIterator = keys.iterator();
  14. while (keyIterator.hasNext()) {
  15. SelectionKey key = keyIterator.next();
  16. if (key.isAcceptable()) {
  17. ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
  18. // 服务器会为每个新连接创建一个 SocketChannel
  19. SocketChannel sChannel = ssChannel1.accept();
  20. sChannel.configureBlocking(false);
  21. // 这个新连接主要用于从客户端读取数据
  22. sChannel.register(selector, SelectionKey.OP_READ);
  23. } else if (key.isReadable()) {
  24. SocketChannel sChannel = (SocketChannel) key.channel();
  25. System.out.println(readDataFromSocketChannel(sChannel));
  26. sChannel.close();
  27. }
  28. keyIterator.remove();
  29. }
  30. }
  31. }
  32. private static String readDataFromSocketChannel(SocketChannel sChannel) throws IOException {
  33. ByteBuffer buffer = ByteBuffer.allocate(1024);
  34. StringBuilder data = new StringBuilder();
  35. while (true) {
  36. buffer.clear();
  37. int n = sChannel.read(buffer);
  38. if (n == -1) {
  39. break;
  40. }
  41. buffer.flip();
  42. int limit = buffer.limit();
  43. char[] dst = new char[limit];
  44. for (int i = 0; i < limit; i++) {
  45. dst[i] = (char) buffer.get(i);
  46. }
  47. data.append(dst);
  48. buffer.clear();
  49. }
  50. return data.toString();
  51. }
  52. }
  1. public class NIOClient {
  2. public static void main(String[] args) throws IOException {
  3. Socket socket = new Socket("127.0.0.1", 8888);
  4. OutputStream out = socket.getOutputStream();
  5. String s = "hello world";
  6. out.write(s.getBytes());
  7. out.close();
  8. }
  9. }

内存映射文件

内存映射文件 I/O 是一种读和写文件数据的方法,它可以比常规的基于流或者基于通道的 I/O 快得多。

向内存映射文件写入可能是危险的,只是改变数组的单个元素这样的简单操作,就可能会直接修改磁盘上的文件。修改数据与将数据保存到磁盘是没有分开的。

下面代码行将文件的前 1024 个字节映射到内存中,map() 方法返回一个 MappedByteBuffer,它是 ByteBuffer 的子类。因此,可以像使用其他任何 ByteBuffer 一样使用新映射的缓冲区,操作系统会在需要时负责执行映射。

  1. MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

对比

NIO 与普通 I/O 的区别主要有以下两点:

  • NIO 是非阻塞的;
  • NIO 面向块,I/O 面向流。

七、参考资料

Java NIO:NIO概述
Java IO流学习总结一:输入输出流
NIO 入门
Java NIO浅析

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注