通过流可以读写文件,流是一组有序列的数据序列,以先进先出方式发送信息的通道。

输入/输出流抽象类有两种:InputStream/OutputStream字节输入流和Reader/Writer字符输入流。

一、字节流

1.InputStream类

int read():从输入流中读取下一个字节,并返回该字节对应的整型数字 0-255。

int read(byte[ ] b):从输入流中读取多个字节,并将字节存放到数组b[ ]中,返回读到的字节个数,即数组长度。

int read(byte[ ] b ,int off ,int len):从输入流中读取多个字节,并将字节存放到数组b[ ]中,从数组的off位置处开始存放,len是读到的字节个数。

2.OutputStream类

字节流输入步骤:

1.引用相关类;

2.创建FileInputStream类对象;

3.读取文本文件;

4.关闭流。

字节流输出步骤:

1.引用相关类;

2.创建FileOutputStream类对象;

3.写入文本文件;

4.关闭流。

案例:

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class FileTest2 {
  6. public static void main(String[] args) {
  7. // 创建目录
  8. File dir = new File("d:/eclipseWJ/HelloWorld/FileTest2");
  9. dir.mkdirs();
  10. // 创建文件
  11. File file = new File("d:/eclipseWJ/HelloWorld/FileTest2/test2.txt");
  12.  
  13. FileOutputStream fos = null;
  14. FileInputStream fis = null;
  15. try {
    if(!file.exists())
  16. file.createNewFile();
  17.  
  18. fos = new FileOutputStream(file,true); // 在文件原有的内容上追加
    fos = new FileOutputStream(file); // 直接覆盖文件原有的内容
  19. String str = "学习Java!";
  20. byte[] words = str.getBytes();
  21. fos.write(words, 0, words.length);
  22.  
  23. // 创建输入流对象
  24. fis = new FileInputStream(file);
  25. int data;
  26. while ((data = fis.read()) != -1) {
  27. System.out.print((char) data);
  28. }
  29.  
  30. } catch (FileNotFoundException e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. } catch (IOException e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. } finally {
  37. // 关闭输入流
  38. try {
  39. fos.close();
  40. fis.close();
  41. } catch (IOException e) {
  42. // TODO Auto-generated catch block
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. }

案例:将file1中的内容复制到file2

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class FileCopy {
  6. public static void main(String[] args) {
  7. File dir = new File("D:/eclipseWJ/HelloWorld/filecopy");
  8. File file1 = new File("D:/eclipseWJ/HelloWorld/filecopy/file1.txt");
  9. File file2 = new File("d:/eclipseWJ/HelloWorld/filecopy/file2.txt");
  10. dir.mkdirs();
  11. FileInputStream fis = null;
  12. FileOutputStream fos = null;
  13. try {
    if(!file1.exists())
  14. file1.createNewFile();
    if(!file2.exists())
  15. file2.createNewFile();
  16. fos = new FileOutputStream(file1);
  17. String str = "HelloWorld";
  18. byte[] words = str.getBytes();
  19. fos.write(words, 0, str.length());
  20. fos.close();
  21. fis = new FileInputStream(file1);
  22. fos = new FileOutputStream(file2, true);
  23. int len;
  24. byte[] word = new byte[1024];
  25. while ((len = fis.read(word)) != -1) { // 读取到的字节存到数组word[]中,追加存储
  26. fos.write(word,0,len);
  27. }
  28. fis.close();
  29. fis = new FileInputStream(file2);
  30. int data;
  31. while ((data = fis.read()) != -1) {
  32. System.out.print((char)data);
  33. }
  34.  
  35. } catch (IOException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. } finally {
  39. try {
  40. fis.close();
  41. fos.close();
  42. } catch (IOException e) {
  43. // TODO Auto-generated catch block
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48. }

二、字符流

1.Reader类

Reader类常用方法:

int read():从输入流中读取下一个字符,并返回该字符对应的整型数字 0-65535。

int read(char[ ] c):从输入流中读取多个字符,并将字符存放到数组b[ ]中,返回读到的字符个数,即数组长度。

int read(char[ ] c ,int off ,int len):从输入流中读取多个字符,并将字符存放到数组b[ ]中,从数组的off位置处开始存放,len是读到的字符个数。

子类InputStreamReader常用构造方法:

InputStreamReader(InputStream in):参数是一个字节流对象,将一个字节流包装成字符流,读取内容按本地平台默认编码

InputStreamReader(InputStream in ,String charserName):参数是一个字节流对象和字符集编码,先将字节流包装成字符流,然后再按照这个字符集编码来读取到内容。

步骤:

1.创建FileInputStream类对象(字节流);

2.创建InputStreamReader类对象,并将FileInputStream类对象字符集编码名字作为构造函数的参数(字符流);

3.创建BufferedReader类对象,并将InputStreamReader类对象作为构造函数的参数(字符流);

4.读取文本。

代码示例(较为综合):

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class InputStreamReaderDemo {
  6.  
  7. public static void main(String[] args) {
  8. // TODO Auto-generated method stub
  9. File file = new File("D:\\eclipseWJ\\HelloWorld\\Chapter\\File3.txt");
  10. InputStream is = null;
  11. Reader isr = null;
  12. BufferedReader br = null;
  13. try {
  14. is = new FileInputStream(file);
  15. isr = new InputStreamReader(is,"UTF-8");
  16. br = new BufferedReader(isr);
  17. StringBuffer bf = new StringBuffer();
  18. String line = null;
  19. if((line = br.readLine())!=null) {
  20. bf.append(line);
  21. }
  22. System.out.println(bf);
  23. } catch (FileNotFoundException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. } catch (IOException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. } finally {
  30. try {
  31. br.close();
  32. isr.close();
  33. } catch (IOException e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. }
  37.  
  38. }
  39. }
  40. }

文本文件读取类FileReader是InputStreamReader的子类:

构造方法:

FileReader(File file)

FileReader(String pathName)

FileReader只能按照本地平台的字符编码来读,不能通过用户特定的字符集编码来读。

本地平台字符集编码获得:String encoding = System.getProperty("file.encoding");

使用FileReader类读取文本步骤:

1.引用相关类;

2.创建FileReader类对象;

3.读取文本文件;

4.关闭流。

代码示例:

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class FileReaderDemo {
  6. public static void main(String[] args) {
  7. FileReader filereader;
  8. try {
  9. filereader = new FileReader("d:/eclipseWJ/HelloWorld/FileTest2/test2.txt");
  10. StringBuffer sbf = new StringBuffer();
  11. char[] words = new char[1024];
  12. while(filereader.read(words)!=-1) { // while只执行一次
  13. sbf.append(words);
  14. }
  15. System.out.println(sbf);
  16.  
  17. } catch (FileNotFoundException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }
  25. }

BufferReader类:带有缓冲区的字符输入流

代码示例:

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class FileTestBuffer {
  6. public static void main(String[] args) {
  7. BufferedReader reader = null;
  8. try {
  9. // 创建目录
  10. File dir = new File("Chapter");
  11. dir.mkdirs();
  12.  
  13. // 创建文件
  14. File f = new File("D:\\eclipseWJ\\HelloWorld\\Chapter\\File1.txt");
  15. f.createNewFile();
  16.  
  17. // 写入文本
  18. FileWriter writer = new FileWriter(f); // 覆盖重写
    FileWriter writer = new FileWriter(f, true); // 追加
  19. BufferedWriter bufferedwriter = new BufferedWriter(writer);
  20. bufferedwriter.write("你好");
    bufferedwriter.flush(); //将缓冲区的内容全部写入文本
  21. bufferedwriter.close();
  22.  
  23. // 输出目录中的文件
  24. if (dir.isDirectory()) {
  25. String[] fileContents = dir.list();
  26. for (String i : fileContents)
  27. System.out.println(i);
  28. }
  29.  
  30. // 读出文件内容
  31. FileReader fileReader = new FileReader(f);
  32. reader = new BufferedReader(fileReader);
  33. String line = null;
  34. while ((line = reader.readLine()) != null)
  35. System.out.println(line);
  36. } catch (FileNotFoundException ex) {
  37. ex.printStackTrace();
  38. } catch (IOException ex) {
  39. ex.printStackTrace();
  40. }finally {
  41. try {
  42. reader.close();
  43. } catch (IOException e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. }
  47. }
  48. }
  49. }

2.Writer类

参考上述Reader类。

三、读写二进制文件

读取特定图片并完成该图片的复制

代码示例:

  1. package com.yh.filestring;
  2.  
  3. import java.io.*;
  4.  
  5. public class FIleImg {
  6.  
  7. public static void main(String[] args) {
  8. // TODO Auto-generated method stub
  9. FileInputStream fis = null;
  10. DataInputStream dis = null;
  11. FileOutputStream fos = null;
  12. DataOutputStream dos = null;
  13.  
  14. try {
  15. fis = new FileInputStream("D:\\eclipseWJ\\HelloWorld\\fish.jpg");
  16. dis = new DataInputStream(fis);
  17.  
  18. fos = new FileOutputStream("D:\\eclipseWJ\\HelloWorld\\newfish.jpg");
  19. dos = new DataOutputStream(fos);
  20.  
  21. int data;
  22. while ((data = dis.read()) != -1) {
  23. dos.write(data);
  24. }
  25. //dos.flush();
  26. } catch (FileNotFoundException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. } catch (IOException e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. } finally {
  33. try {
  34. dos.close();
  35. fos.close();
  36. dis.close();
  37. fis.close();
  38. } catch (IOException e) {
  39. // TODO Auto-generated catch block
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. }

四、序列化和反序列化

对象的序列化和反序列化

五、总结

1.类的继承关系总结:

InputStream类(字节流)—— FileInputStream类 —— DataInputStream类(读取二进制文件)

OutputStream类(字节流)—— FileOutputStream类 —— DataOutputStream类(写入二进制文件)

Reader类(字符流)—— InputStreamReader类(构造函数参数:一个字节流InputStream类对象和字符集编码名字)和BufferedReader类(构造函数参数:一个Reader对象,提供通用的缓冲方式文本读取,readLine读取一个文本行)—— FileReader类(构造函数参数:File类对象或完整路径,无法指定字符集编码)

Writer类(字符流)—— OutputStreamWriter类(构造函数参数:一个字节流OutputStream类对象和字符集编码名字)和BufferedWriter类(构造函数参数:一个Writer对象,提供通用的缓冲方式文本写入)—— FileWriter类(构造函数参数:File类对象或完整路径,无法指定字符集编码)

2.字节和字符的关系:

Java采用unicode来表示字符,java中的一个char是2个字节,一个中文或英文字符的unicode编码都占2个字节,但如果采用其他编码方式,一个字符占用的字节数则各不相同。

在 GB-2312 编码或 GBK 编码中,一个英文字母字符存储需要1个字节,一个汉子字符存储需要2个字节。

在UTF-8编码中,一个英文字母字符存储需要1个字节,一个汉字字符储存需要3到4个字节。

在UTF-16编码中,一个英文字母字符存储需要2个字节,一个汉字字符储存需要3到4个字节(Unicode扩展区的一些汉字存储需要4个字节)。

在UTF-32编码中,世界上任何字符的存储都需要4个字节。

3.flush()方法

在进行文件写入相关操作时,需要调用。

java输入/输出流的基本知识的更多相关文章

  1. 深入理解Java输入输出流

    Java.io包的File类,File类用于目录和文件的创建.删除.遍历等操作,但不能用于文件的读写. Java 对文件的写入和读取涉及到流的概念,写入为输出流,读取为输入流.如何理解流的概念呢?可以 ...

  2. Java输入/输出流体系

    在用java的io流读写文件时,总是被它的各种流能得很混乱,有40多个类,理清啦,过一段时间又混乱啦,决定整理一下!以防再忘 Java输入/输出流体系 1.字节流和字符流 字节流:按字节读取.字符流: ...

  3. java基础---->java输入输出流

    今天我们总结一下java中关于输入流和输出流的知识,博客的代码选自Thinking in java一书.我突然很想忘了你,就像从未遇见你. java中的输入流 huhx.txt文件的内容如下: I l ...

  4. Java 输入输出流 转载

    转载自:http://blog.csdn.net/hguisu/article/details/7418161 1.什么是IO Java中I/O操作主要是指使用Java进行输入,输出操作. Java所 ...

  5. Java输入输出流(一)——常用的输入输出流

    1.流的概念:在Java中,流是从源到目的地的字节的有序序列.Java中有两种基本的流--输入流(InputStream)和输出流(OutputStream). 根据流相对于程序的另一个端点的不同,分 ...

  6. java 输入输出流1 FileInputStrem&&FileOutStream

    通过文件输入流读取问价 package unit6; import java.io.FileInputStream; import java.io.FileNotFoundException; imp ...

  7. java输入输出流总结 转载

    一.基本概念 1.1 什么是IO?     IO(Input/Output)是计算机输入/输出的接口.Java中I/O操作主要是指使用Java进行输入,输出操作.     Java所有的I/O机制都是 ...

  8. java输入输出流(内容练习)

    1,编写一个程序,读取文件test.txt的内容并在控制台输出.如果源文件不存在,则显示相应的错误信息. package src; import java.io.File; import java.i ...

  9. Java输入输出流(转载)

    转自http://blog.csdn.net/hguisu/article/details/7418161 目录(?)[+] 1.什么是IO Java中I/O操作主要是指使用Java进行输入,输出操作 ...

随机推荐

  1. Flask搭建弹幕视频网站(1)

    说在前面 也不知道最后能不能完成网站,所以就想把这十多天来学习到的点点滴滴记录下来.学的越来越多,所谓全栈也是需要前端基础,越来越感受到压力,但是遇到一个问题就解决一个问题,慢慢习惯之后感觉也还行.说 ...

  2. webRTC中语音降噪模块ANS细节详解(四)

    上篇(webRTC中语音降噪模块ANS细节详解(三))讲了噪声的初始估计方法以及怎么算先验SNR和后验SNR. 本篇开始讲基于带噪语音和特征的语音和噪声的概率计算方法和噪声估计更新以及基于维纳滤波的降 ...

  3. php 变量和数据类型

    $ 定义变量: 变量来源数学是计算机语言中能存储计算结果或能表示值抽象概念.变量可以通过变量名访问.在指令式语言中,变量通常是可变的. php 中不需要任何关键字定义变量(赋值,跟Java不同,Jav ...

  4. windows桌面图标不显示,左右键无法使用的解决方法

    问题描述: 日常使用软件中,一返回桌面,桌面图标全部不显示,点击鼠标的左键,右键毫无反应 解决方法: 1. Ctrl+Shift+Esc呼出软仵管理器 2. 右键windows资管理器,点击属性 配图 ...

  5. WinForm训练一_改变窗体大小

    1 //引用系统命名空间 2 using System; 3 //项目命名空间 4 using System.Collections.Generic; 5 using System.Component ...

  6. [atARC113F]Social Distance

    (由于是实数范围,端点足够小,因此区间都使用中括号,且符号取等号) 定义$P(X)$表示$\forall 2\le i\le n,a_{i}-a_{i-1}\ge X$的概率,那么我们所求的也就是$P ...

  7. 1、使用ValueOperations操作redis(String字符串)

    文章来源:https://www.cnblogs.com/shiguotao-com/p/10559997.html 方法 c参数 s说明   void set(K key, V value); ke ...

  8. SpringCloud升级之路2020.0.x版-41. SpringCloudGateway 基本流程讲解(3)

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 我们继续分析上一节提到的 WebHandler.加入 Spring Cloud Sleut ...

  9. Sql server 删除重复记录的SQL语句

    原文地址:https://www.cnblogs.com/luohoufu/archive/2008/06/05/1214286.html 在项目开发过程中有个模块日清表页面数据重复,当时那个页面的数 ...

  10. Atcoder Grand Contest 013 E - Placing Squares(组合意义转化+矩阵快速幂/代数推导,思维题)

    Atcoder 题面传送门 & 洛谷题面传送门 这是一道难度 Cu 的 AGC E,碰到这种思维题我只能说:not for me,thx 然鹅似乎 ycx 把题看错了? 首先这个平方与乘法比较 ...