Java中的I/O流

一、File类

1.介绍

代表磁盘上的文件或目录,基于java.io包下的类

2.使用

File f = new File("文件路径");

补充
对于文件路径有两种:
①相对路径:相对于当前位置的路径(在idea中:当前工程下的文件(与src同级的文件))
②绝对路径:盘符:/文件夹/文件/…(一直到你想选择的文件为止)

3.常用方法

判断文件是否存在
f.exists();
获取文件的名字
f.getName();
获取路径---这里的路径是创建File对象时写的路径
f.getPath();
获取绝对路径
f.getAbsolutePath();
删除文件
f.delete();
创建文件,文件不存在时才创建成功
f.createNewFile();

创建目录的方法

File f = new File(D:\\java\\test\\test_01);
创建当前目录 上一次目录test存在的情况
f.mkdir();
如果上一级目录不存在想一次性创建
f.mkdirs();

获取目录下的所有文件名称(子目录下的文件内容获取不到)

file.listFiler();//返回的是一个数组

4.案例

查询指定目录下的所有文件名称包括子目录下的文件名称

public static void main(String[] agrs){
	paint(new File("指定目录路径"));
}
public static void paint(File file){
	File[] files = file.listFiles();
	if(files != null){
		for(File f : files){
			if(f.isDirectory()){// 判断是否为目录
				System.out.println(f.getName() + "---");
				print(f);// 进行方法迭代
			}
			// 不是目录的情况
			System.out.println(f.getName());
		}
	}
}

二、字符编码

常见的字符编码

①ASCII(ascii):占一个字节,不能表示汉字
②ISO-8859-1:占一个字节,不能表示汉字
③UTF-8:一种针对于Unicode的可变长度的字符编码,中文:表示三个字节,英文:表示一个字节

三、编码和解码

1.编码String–>byte[]

public static void main(String[] agrs) throws UnsupportedEncodingException{
	String str = "熊大";
	byte[] bytes = str.getBytes("utf-8");
	StringBuiler sb = new StringBuilder();
	for(int i = 0;i < bytes.length; i++){
		if(i == bytes.length - 1){
			sb.append(bytes[i]).append("]");
		}else {
			sb.append(bytes[i]).append(",");
		}
	}
	System.out.println(sb);
	//[-25,-122,-118,-27,-92,-89]
}

通俗易懂的说,就是将我们看得懂的文字变成了一些看不懂的数字,这就是编码

2.解码

bytes[]—>String

public static void main(String[] agrs) throws UnsupportedEncodingException{
	byte[] bytes = new byte[]{-25,-122,-118,-27,-92,-89};
	String str = new String(bytes,"utf-8");
	System.out.println(str);// 熊大
}

这里就是将一些看不懂的数字变成我们看的懂得文字
注意:以什么编码的就要用什么解码,不然会出现乱码的情况

3.案例

模拟在表单中输入的是中文,在服务器上看见的是乱码的情况

public static void main(String[] agrs) throws UnsupportedEncodingException{
	String str = "乌蝇哥";
	// 编码使用utf-8
	byte[] bytes = str.getBytes("utf-8");
	// 服务器默认解码方式:iso-8859-1
	String s = new String(bytes,"iso-8859-1"):
	System.out.println(s);// 控制台看到的是乱码
}

解决

public static void main(String[] agrs) throws UnsupportedEncodingException{
	String str = "乌蝇哥";
	byte[] bytes = str.getBytes("utf-8");
	String s = new String(bytes,"iso-8859-1"):
	System.out.println(s);// 控制台看到的是乱码
	// ==================================
	byte[] bytes2 = s.getBytes("iso-8859-1");
	String newStr = new String(bytes2,"utf-8");
	System.out.println(newStr);// 这样就可以看到正常的显示
	// ==================================
}

四、流

1.介绍

流是指一连串流动的数据单元,是以先进先出方式发送信息的通道

2.分类

流动方向:分为输入流输出流.
数据传输单位:分为字节流字符流,即每次传递一个字节(byte)或一个字符(char)
功能上划分:分为节点流处理流,节点流功能单一,处理流功能更强

3.四大基流

字节流字符流
输入流InputStreamReader
输入流OutputStreamWriter

站在控制台(程序)的角度看输入输出

输入:进入控制台(程序)中
输出:控制台(程序)中出去

操作流的步骤模板:

1.确认源(操作的文件对象)
2.创建IO流对象
3.具体的IO操作
4.关闭流资源

对于字节流和字符流的使用选择

操作音频、视频、图片等二进制的文件就使用字节流
有中文的就使用字符流

常用的方法
InputStream:

// ① 从输入流中读取**一个字节**数据并返回该字节数据,如果到达流的末尾,则返回 -1
abstract int read();

// ②从输入流中读取多个字节数据,并存储在缓冲区数组 buff 中。
// 返回已读取的字节数量,如果已到达流的末尾,则返回 -1
int read(byte[] buff);

// ③关闭此输入流并释放与该流关联的所有系统资源。InputStream 的 close 方法不执行任何操作
void close();  

OutputStream:

// ①将指定的一个字节数据b写入到输出流中。
abstract void write(int b);

// ②把数组buff中所有字节数据写入到输出流中。
write(byte[] buff);

// ③把数组buff中从索引off 开始的len 个字节写入此输出流中。
write(byte[] b, int off,int len);

// ④关闭此输出流并释放与此流有关的所有系统资源。
void close();

4.使用

①子节输入流 + 字节输出流

FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        // 1.确认目标流 + 创建流通道 输入:
        fis = new FileInputStream(new File("img/大话西游.jpg"));

        // 输出:
        fos = new FileOutputStream(new File("大话西游copy.jpg"));

        // 3.具体操作
        byte[] bytes = new byte[1024];
        int len;
        while ((len = fis.read(bytes)) != - 1){
            fos.write(bytes,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4.关闭流
        try {
            if(fos != null){
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

②字符输入流 + 字符输出流

Reader fr = null;
    FileWriter fw = null;
    try {
        // 1. 确认目标 + 2. 创建流通道 字符输入流
        fr = new FileReader(new File("新建文本文档.txt"));

        // 字符输出流
        fw = new FileWriter(new File("新建文本文档02.txt"));
        // 3.具体操作
        char[] chars = new char[1024];
        int len;
        while((len = fr.read(chars)) != -1){
            fw.write(chars,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4.关闭流操作
        try {
            if (fw != null){
                fw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fr != null) {
                fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
   }
}

补充
为什么要使用String(byte x,int x, int x)这个构造器?
当我设置一次性读取的字节是3(一般设置为1024),如果读取到最后只读了2个,那么最后一个的位置就还是上次留下来的数字,因为每次read(),读取到的内容都会存放到bytes中,所以使用这个构造器是为了获取到几个字节就输出几个,这样就不会出现以上的问题了。

五、缓冲流

1.介绍

节点流的功能都比较单一,性能较低。处理流,也称之为包装流,相对于节点流更高级,在节点流外又套了一个流
②有了包装流之后,我们只关心包装流的操作即可,比如只需要关闭包装流即可,无需在关闭节点流。
③根据四大基流都有各自的包装流:
BufferedInputStream / BufferedOutputStream.
BufferedReader / BufferedWriter.
④缓冲流内置了一个默认大小为8192个字节或字符**(8KB)的缓存区**,缓冲区的作用用来减少磁盘的IO操作

2.方法

BufferedReader 继承于Reader,实现对文本型文件进行高效(一次读取一行)的读取。在BufferedReader 维护了一个缓冲区,一次可以存储文件中的一个行。提供了特有的方法
readLine() : 一次读取一行
BufferedWriter 继承Writer,实现对文本型文件进行高效的写入,提供了特有方法
newLine() : 写入一个换行。
flush():刷新,管道可能会残留一些数据,每读一次就刷新一下,保持数据完美流出或流入

3.使用

缓冲字节流:

//1.
File f = new File("G:\\java\\test\\图片02.jpg");
File f2 = new File("图片02copy.jpg");
//2.管道
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//3.
byte[] bytes = new byte[1024];
int len;
  try {
      bis = new BufferedInputStream(new FileInputStream(f));
      bos = new BufferedOutputStream(new FileOutputStream(f2));
      while (((len = bis.read(bytes)) != -1)){
          bos.write(bytes, 0, len);
          bos.flush();//刷新
      }
  } catch (IOException e) {
      e.printStackTrace();
  }finally {
      try {
          if (bos != null)
              bos.close();
          if (bis != null)
              bis.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

缓冲字符流:

BufferedReader br = null;
    try {
        //1.目标 管道
        br = new BufferedReader(new FileReader("g:\\java\\test\\a.txt"));
        
        //2.操作
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(br != null)
                br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值