• Java学习笔记之----I/O(输入/输出)二


     

    【今日】 

    孩儿立志出乡关,学不成名誓不还。

    文件输入/输出流

    程序运行期间,大部分数据都在内存中进行操作,当程序结束或关闭时,这些数据将消失。如果需要将数据永久保存,可使用文件输入/输出流与指定的文件建立连接,将需要的数据永久保存到文件中。

    一    FilelnputStream与FileOutputStream类

    文件字节流

    FileInputStream类与FileOutputStream类都用来操作磁盘文件。如果用户的文件读取需求比较简单,则可以使用FileInputStream类,该类继承自InputStream类。FileOutputStream类与 FilelnputStream类对应,提供了基本的文件写入能力。FileOutputStream类是OutputStream类的子类。
    FileInputStream类常用的构造方法如下:
    😶‍🌫️FileInputStream(String name)
    😶‍🌫️FileInputStream(File file)

     第一个构造方法使用给定的文件名name创建一个 FilelnputStream对象,第二个构造方法使用File对象创建 FileInputStream对象。第一个构造方法比较简单,但第二个构造方法允许在把文件连接输入流之前对文件做进一步分析。
    FileOutputStream类有与FileInputStream类相同的参数构造方法,创建一个FileOutputStream对象时,可以指定不存在的文件名,但此文件不能是一个已被其他程序打开的文件。

     【代码块】输出流

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileNotFoundException;
    4. import java.io.FileOutputStream;
    5. import java.io.IOException;
    6. public class Demo {
    7. public static void main(String[] args) {
    8. File f = new File("word.txt"); //在MyProject下创建文本word.txt
    9. FileOutputStream out = null; //赋予空值
    10. try {
    11. out = new FileOutputStream(f);
    12. String str = "你见过凌晨4点的洛杉矶吗?";
    13. byte b[] = str.getBytes();//字符串转换为字节数组
    14. try {
    15. out.write(b);
    16. } catch (IOException e) {
    17. // TODO 自动生成的 catch 块
    18. e.printStackTrace();
    19. }
    20. } catch (FileNotFoundException e) {
    21. e.printStackTrace();
    22. }finally {
    23. if(out !=null) {
    24. try {
    25. out.close();
    26. } catch (IOException e) {
    27. // TODO 自动生成的 catch 块
    28. e.printStackTrace();
    29. }
    30. }
    31. }
    32. }
    33. }

    还没运行前可以看到左侧的项目中并没有word.txt项目。 

     【运行刷新】

    当我们反复向这个文件中写值的时候,它会覆盖前面的内容。

    如果我们将out = new FileOutputStream(f);

    改为out = new FileOutputStream(f,true):文件输出流,在文件末尾追加内容。

    改为out = new FileOutputStream(f,true):文件输出流,替换内容。

    【代码】输入流

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileInputStream;
    4. import java.io.FileNotFoundException;
    5. import java.io.FileOutputStream;
    6. import java.io.IOException;
    7. public class Demo {
    8. public static void main(String[] args) {
    9. File f = new File("word.txt"); //在MyProject下创建文本word.txt
    10. FileOutputStream out = null; //赋予空值
    11. try {
    12. out = new FileOutputStream(f,false);
    13. String str = "你见过凌晨4点的洛杉矶吗?";
    14. byte b[] = str.getBytes();//字符串转换为字节数组
    15. try {
    16. out.write(b);
    17. } catch (IOException e) {
    18. // TODO 自动生成的 catch 块
    19. e.printStackTrace();
    20. }
    21. } catch (FileNotFoundException e) {
    22. e.printStackTrace();
    23. }finally {
    24. if(out !=null) {
    25. try {
    26. out.close();
    27. } catch (IOException e) {
    28. // TODO 自动生成的 catch 块
    29. e.printStackTrace();
    30. }
    31. }
    32. }
    33. FileInputStream in = null;
    34. try {
    35. in = new FileInputStream(f);//输入流读取文件
    36. byte b2[] = new byte[1024];//创建缓冲区
    37. in.read(b2);//将文件信息读入缓存数组中
    38. System.out.println("文本中的内容是:"+new String(b2));
    39. } catch (IOException e) {
    40. e.printStackTrace();
    41. }finally {
    42. if(in!=null) {
    43. try {
    44. in.close();
    45. } catch (IOException e) {
    46. e.printStackTrace();
    47. }
    48. }
    49. }
    50. }
    51. }

    【运行结果】

    观察运行结果我们可以发现输出文本内容后,后面还跟了一串空格,这是因为我们创建的缓冲区字节数是1024远远大于这些汉字所占用的字节,如何去除这些空格呢?

    我们可以这样做:

    这样做是因为in.read()可以返回所读取的数组的总长度,在让它从索引0到len进行输出就可以 去除空格,看一下运行结果:

    我们也可以直接对文本的内容进行修改,只用输入流进行输出:

    我们先在word.txt里面写入歌词:

    【运行的代码】

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileInputStream;
    4. import java.io.IOException;
    5. public class Demo {
    6. public static void main(String[] args) {
    7. File f = new File("word.txt"); //在MyProject下创建文本word.txt
    8. FileInputStream in = null;
    9. try {
    10. in = new FileInputStream(f);//输入流读取文件
    11. byte b2[] = new byte[1024];//创建缓冲区
    12. int len = in.read(b2);//读入缓冲区的总字节数
    13. System.out.println("文本中的内容是:\n"+new String(b2,0,len));
    14. } catch (IOException e) {
    15. e.printStackTrace();
    16. }finally {
    17. if(in!=null) {
    18. try {
    19. in.close();
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. }
    23. }
    24. }
    25. }
    26. }

     【运行结果】

    二   FileReader和 FileWriter 类 

    文件字符流

         使用FileOutputStream类向文件中写入数据与使用FileInputStream类从文件中将内容读出来,都存在一点不足,即这两个类都只提供了对字节或字节数组的读取方法。由于汉字在文件中占用两个字节,如果使用字节流,读取不好可能会出现乱码现象,此时采用字符流FileReader类或 FileWriter类即可避免这种现象。
         FileReader类和 FileWriter类对应了 FilelnputStream类和 FileOutputStream类。FileReader类顺序地读取文件,只要不关闭流,每次调用read(方法就顺序地读取源中其余的内容,直到源的末尾或流被关闭。

     【代码】输出流

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileWriter;
    4. import java.io.IOException;
    5. public class Demo {
    6. public static void main(String[] args) {
    7. File f = new File("word.txt");
    8. FileWriter fw = null;
    9. try {
    10. fw = new FileWriter(f);
    11. String str ="只是一场烟火散落的尘埃";
    12. fw.write(str);
    13. } catch (IOException e) {
    14. e.printStackTrace();
    15. }finally {
    16. if(fw!=null) {
    17. try {
    18. fw.close();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. }
    25. }

    【运行结果】 

    【代码】输入流

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileReader;
    4. import java.io.IOException;
    5. public class Demo {
    6. public static void main(String[] args) {
    7. File f = new File("word.txt");
    8. FileReader fr = null;
    9. try {
    10. fr = new FileReader(f);
    11. char ch[] = new char[1024];
    12. int len = fr.read(ch);
    13. System.out.println("文本内容为:"+new String(ch,0,len));
    14. } catch (IOException e) {
    15. e.printStackTrace();
    16. }finally {
    17. if(fr!=null) {
    18. try {
    19. fr.close();
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. }
    23. }
    24. }
    25. }
    26. }

    【运行结果】 

    带缓存的输入/输出流

    首先我们了解一下什么是缓冲区:

    我们要将一推箱子由A运到B地,如果我们派人一次一次的去搬运,是十分慢的。如果直接用货车运输,那么方便许多。这里货车就充当了缓冲区的功能。

       缓存是I/O的一种性能优化。缓存流为I1O流增加了内存缓存区,使得在流上执行skip)、mark()和reset()方法都成为可能。

     一   BufferedInputStream与 BufferedOutputStream类

    缓冲字节流

    BufferedInputStream 类可以对所有InputStream类进行带缓存区的包装以达到性能的优化。BufferedInputStream类有两个构造方法:
    1.BufferedInputStream(InputStream in)
    2.BufferedInputStream(InputStream in,int size)

    第一种形式的构造方法创建了一个有32个字节的缓存区。

    第二种形式的构造方法按指定的大小来创建缓存区。

    一个最优的缓存区的大小,取决于它所在的操作系统、可用的内存空间以及机器配置。从构造方法可以看出,BufferedInputStream对象位于InputStream类对象之后。

    BufferedInputStream读取文件过程 

          使用 BufferedOutputStream类输出信息和仅用OutputStream类输出信息完全一样,只不过BufferedOutputStream有一个flush)方法用来将缓存区的数据强制输出完。BufferedOutputStream类也有两个构造方法:

    BufferedOutputStream(OutputStream in)。
    BufferedOutputStream(OutputStream in,int size)。

    第一种构造方法创建一个有32个字节的缓存区。

    第二种构造方法以指定的大小来创建缓存区。

    缓冲输入流

    不使用缓存区效果:

    【代码】

    1. package mt;
    2. import java.io.File;
    3. import java.io.FileInputStream;
    4. import java.io.IOException;
    5. public class Demo {
    6. public static void main(String[] args) {
    7. File f = new File("D:\\FlashCenter\\歌词.txt");
    8. FileInputStream in = null;
    9. long start = System.currentTimeMillis();//获取流开始的毫秒值
    10. try {
    11. in = new FileInputStream(f);
    12. byte b[] = new byte[1024];//缓冲区字节数组(这个缓冲区与Buffered不同)
    13. while(in.read()!=-1) {//当有值时循环输出
    14. }
    15. long end = System.currentTimeMillis();//获取流结束的毫秒值
    16. System.out.println("运行经历的毫秒数:"+(end-start));
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }finally {
    20. if(in !=null) {
    21. try {
    22. in.close();
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. }
    28. }
    29. }

    【 运行效果】

     

     

    使用缓冲流效果:

    【代码】

    1. package mt;
    2. import java.io.BufferedInputStream;
    3. import java.io.File;
    4. import java.io.FileInputStream;
    5. import java.io.IOException;
    6. public class Demo {
    7. public static void main(String[] args) {
    8. File f = new File("D:\\FlashCenter\\歌词.txt");
    9. FileInputStream in = null;
    10. BufferedInputStream bi = null;
    11. long start = System.currentTimeMillis();//获取流开始的毫秒值
    12. try {
    13. in = new FileInputStream(f);
    14. bi = new BufferedInputStream(in);//将文件字节流包装成缓冲字节流
    15. byte b[] = new byte[1024];//缓冲区字节数组(这个缓冲区与Buffered不同)
    16. while(bi.read()!=-1) {//当有值时循环输出
    17. }
    18. long end = System.currentTimeMillis();//获取流结束的毫秒值
    19. System.out.println("运行经历的毫秒数:"+(end-start));
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. }finally {
    23. if(in !=null) {
    24. try {
    25. in.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. if(bi!=null) {
    31. try {
    32. bi.close();
    33. } catch (IOException e) {
    34. e.printStackTrace();
    35. }
    36. }
    37. }
    38. }
    39. }

    【 运行效果】

    从运行效果来看,可以看出大大的提高了运行的效率。 

     缓冲输出流

    【代码】

    1. package mt;
    2. import java.io.BufferedOutputStream;
    3. import java.io.File;
    4. import java.io.FileOutputStream;
    5. import java.io.IOException;
    6. public class Demo2 {
    7. public static void main(String[] args) {
    8. File f =new File("word.txt");
    9. FileOutputStream out = null;
    10. BufferedOutputStream bo = null;
    11. try {
    12. out = new FileOutputStream(f);
    13. bo = new BufferedOutputStream(out);//包装文件输出流
    14. String str = "天生我才必有用,千金散尽还复来!";
    15. byte b[] = str.getBytes();
    16. bo.write(b);//这里也能够提高效率
    17. //使用缓冲字节流输出时,要多进行刷新操作。
    18. bo.flush();//刷新。强制将缓存区数据写入文件,即使缓冲区没有写满。
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }finally {
    22. try {
    23. out.close();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. }
    29. }

     【运行结果】

    总结:

     无论BufferedInputStream与 BufferedOutputStream类,在这里都有提高运行效率的结果。

     二   BufferedReader与BufferedWriter类

    缓冲字符流

    BufferedReader类与BufferedWriter类分别继承Reader类与Writer类。这两个类同样具有内部事机制,并能够以行为单位进行输入/输出。 

    BufferedReader类常用的方法如下:
    read0方法:读取单个字符。
    readLine()方法:读取一个文本行,并将其返回为字符串。若无数据可读,则返回null。

    BufferedWriter类中的方法都返回void。常用的方法如下:
    write(String s,int offint len)方法:写入字符串的某一部分。
    flush()方法:刷新该流的缓存。
    newLine(方法:写入一个行分隔符。
    在使用BufferedWriter类的Write()方法时,数据并没有立刻被写入输出流,而是首先进入缓存区中如果想立刻将缓存区中的数据写入输出流,一定要调用flush)方法。

    缓冲字符输出流代码实列: 

    1. package mt;
    2. import java.io.BufferedWriter;
    3. import java.io.File;
    4. import java.io.FileWriter;
    5. import java.io.IOException;
    6. public class Demo {
    7. public static void main(String[] args) {
    8. File f = new File("word.txt");
    9. FileWriter fw = null;
    10. BufferedWriter bw = null;
    11. try {
    12. fw = new FileWriter(f);
    13. bw = new BufferedWriter(fw);//将文件字符输出流包装成缓存字符流
    14. String str1 = "世界那么大";
    15. String str2 = "我想去看看";
    16. bw.write(str1);//第一行
    17. bw.newLine();//创建新行
    18. bw.write(str2);//第二行
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }finally {//要注意流关闭的顺序,先创建的后关闭
    22. if(bw!=null) {
    23. try {
    24. bw.close();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. if(fw!=null) {
    30. try {
    31. fw.close();
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. }
    37. }
    38. }

    运行效果: 

    缓冲字符流输入代码实列: 

    1. package mt;
    2. import java.io.BufferedReader;
    3. import java.io.File;
    4. import java.io.FileReader;
    5. import java.io.IOException;
    6. public class Demo {
    7. public static void main(String[] args) {
    8. File f = new File("word.txt");
    9. FileReader fr = null;
    10. BufferedReader br = null;
    11. try {
    12. fr = new FileReader(f);
    13. br = new BufferedReader(fr);
    14. String tmp = null;
    15. int i = 1;
    16. while((tmp = br.readLine())!=null) {//循环读取文件中的内容
    17. System.out.println("第"+i+"行:"+tmp);
    18. i++;
    19. }
    20. br.readLine();//读一行
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }finally {
    24. if(br!=null) {
    25. try {
    26. br.close();
    27. } catch (IOException e) {
    28. e.printStackTrace();
    29. }
    30. }
    31. }if(fr!=null) {
    32. try {
    33. fr.close();
    34. } catch (IOException e) {
    35. e.printStackTrace();
    36. }
    37. }
    38. }
    39. }

     运行效果: 

    文本内容:

    输出效果:

     

    总结:

    BufferedReader与BufferedWriter类除了提高效率以外,它还可以以行为单位,来对字符数据进行操作。比如:BufferedReader的readLine()方法,BufferedWriter的newLine()方法。

    数据的输入/输出流

    数据输入/输出流(DataInputStream类与DataOutputStream类)允许应用程序以与机器无关的方式从底层输入流中读取基本Java数据类型。也就是说,当读取一个数据时,不必再关心这个数值应当是哪种字节。

    一   DataInputStream类与DataOutputStream类

    DatalnputStream类与DataOutputStream类的构造方法如下。
    DataInputStream(InputStream in):使用指定的基础InputStream对象创建一个 DataInputStream对象。
    DataOutputStream(OutputStream out):创建一个新的数据输出流,将数据写入指定基础输出流。

         DataOutputStream类提供了将字符串、double数据、int数据、boolean数据写入文件的方法。其中,将字符串写入文件的方法有3种,分别是writeBytes(String s)、writeChars(String s)、writeUTF(Strings)。由于Java中的字符是Unicode编码,是双字节的,writeBytes0方法只是将字符串中的每一个字符的低字节内容写入目标设备中;而writeCharsO方法将字符串中的每一个字符的两个字节的内容都写到目标设备中;writeUTFO方法将字符串按照UTF编码后的字节长度写入目标设备,然后才是每一个字节的UTF编码。
    DataInputStream类只提供了一个readUTF0方法返回字符串。这是因为要在一个连续的字节流读取一个字符串,如果没有特殊的标记作为一个字符串的结尾,并且不知道这个字符串的长度,就无法知道读取到什么位置才是这个字符串的结束。DataOutputStream类中只有writeUTFO方法向目标设备中写入字符串的长度,所以也能准确地读回写入字符串。

     API中的部分方法:

    输入流:

    输出流: 

     

    代码实列:

    1. package mt;
    2. import java.io.DataInputStream;
    3. import java.io.DataOutputStream;
    4. import java.io.File;
    5. import java.io.FileInputStream;
    6. import java.io.FileOutputStream;
    7. import java.io.IOException;
    8. public class Demo {
    9. public static void main(String[] args) {
    10. File f = new File("word.txt");
    11. FileOutputStream out = null;
    12. DataOutputStream dos = null;
    13. try {
    14. out = new FileOutputStream(f);
    15. dos = new DataOutputStream(out);//将文件流包装为数据流
    16. dos.writeUTF("这是写入字符串数据。"); //写入字符串数据
    17. dos.writeDouble(3.14); //写入浮点型数据
    18. dos.writeBoolean(false); //写入布尔类型
    19. dos.writeInt(123); //写入整型数据
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. }finally {
    23. if(out!=null) {
    24. try {
    25. out.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. if(dos!=null) {
    31. try {
    32. dos.close();
    33. } catch (IOException e) {
    34. e.printStackTrace();
    35. }
    36. }
    37. }
    38. }
    39. }

    我们运行以后发现运行结果为乱码:

    这是因为通过数据输出流写入文本的是字节码,我们想要得到里面的数据就需要用数据输入流将里面的数据读出来。然后通过对应的方法进行解析得到结果。 

    我们添加上数据的输入流在来进行:

    代码如下:

    1. package mt;
    2. import java.io.DataInputStream;
    3. import java.io.DataOutputStream;
    4. import java.io.File;
    5. import java.io.FileInputStream;
    6. import java.io.FileOutputStream;
    7. import java.io.IOException;
    8. public class Demo {
    9. public static void main(String[] args) {
    10. File f = new File("word.txt");
    11. FileOutputStream out = null;
    12. DataOutputStream dos = null;
    13. try {
    14. out = new FileOutputStream(f);
    15. dos = new DataOutputStream(out);//将文件流包装为数据流
    16. dos.writeUTF("这是写入字符串数据。"); //写入字符串数据
    17. dos.writeDouble(3.14); //写入浮点型数据
    18. dos.writeBoolean(false); //写入布尔类型
    19. dos.writeInt(123); //写入整型数据
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. }finally {
    23. if(out!=null) {
    24. try {
    25. out.close();
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. if(dos!=null) {
    31. try {
    32. dos.close();
    33. } catch (IOException e) {
    34. e.printStackTrace();
    35. }
    36. }
    37. }
    38. DataInputStream di = null;
    39. FileInputStream in = null;
    40. try {
    41. in = new FileInputStream(f);
    42. di = new DataInputStream(in);
    43. System.out.println("readUTF()读取数据:"+di.readUTF());
    44. System.out.println("readdouble()读取数据:"+di.readDouble());
    45. System.out.println("readBoolean()读取数据:"+di.readBoolean());
    46. System.out.println("readInt()读取数据:"+di.readInt());
    47. } catch (IOException e) {
    48. e.printStackTrace();
    49. }finally {
    50. if(in!=null) {
    51. try {
    52. in.close();
    53. } catch (IOException e) {
    54. e.printStackTrace();
    55. }
    56. }
    57. if(di!=null) {
    58. try {
    59. di.close();
    60. } catch (IOException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. }
    65. }
    66. }

     运行结果:

     Thank!

  • 相关阅读:
    Git Gui使用技巧
    应广单片机使用IHRC校准ILRC--附带产物随机数产生器
    对象存储,从单机到分布式的演进
    [附源码]java毕业设计高考志愿填报系统
    Kinetics400/600/700数据集免费下载
    全景环视AVM标定
    【Linux开发】如何在Ubuntu系统创建新用户,并且用MobaXterm连接linux服务器,创建session?
    UML图 - 类图(Class Diagram)
    十大排序——4.堆排序
    java 枚举
  • 原文地址:https://blog.csdn.net/2301_77599154/article/details/132651214