Java基础IO学习一(文件输入输出流FileInputStream与FileOutputStream的使用)

    xiaoxiao2025-07-07  8

    借用几张图片来说明IO体系(图片来自 http://blog.csdn.net/zhangerqing/article/details/8466532 ) 基于字节的IO操作 基于字符的IO操作 文件输出流的基本使用

    package com.cvicse.io.demo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 文件输出流 FileOutputStream * @author 13169 * */ public class OutputStreamDemo01 { public static void main(String[] args) { //1.定义输出文件的路径 File file = new File("E:"+File.separator+"IODemo"+File.separator+"my.txt"); //2.创建文件目录 if(!file.getParentFile().exists()) { //如果文件目录不存在 file.getParentFile().mkdirs(); //创建目录 } //3.使用OutputStream 和其子类进行实例化 OutputStream output = null; try { output = new FileOutputStream(file); //输出内容 String str = "好好学习,天天向上"; //将字符串变为字节数组 byte[] bytes = str.getBytes(); //4.进行输出文件 output.write(bytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //关闭输出流 资源操作一定要进行关闭 try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } }

    字节数组读取

    package com.cvicse.io.demo; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * 文件输入流 FileInputStream 表示向程序中输入 * 全部数据读取 * @author 13169 * */ public class InputStreamDemo01 { public static void main(String[] args) throws Exception { //1.定义输出文件的路径 File file = new File("E:"+File.separator+"IODemo"+File.separator+"my.txt"); //2.文件存在 if(file.exists()) { //3.使用InputStream输入流 读取文件 InputStream input = new FileInputStream(file); //准备一个1024字节的数组 byte[] data =new byte[1024]; //4.将内容保存到字节数组中 int len = input.read(data); //5.关闭输入流 input.close(); //输出读取到的数据 System.out.println("["+new String(data,0,len)+"]"); } } }

    单个字节读取或部份字节读取

    package com.cvicse.io.demo; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * 文件输出流 FileInputStream 单个字节读取 * @author 13169 * */ public class InputStreamDemo02 { public static void main(String[] args) throws Exception { /** * 读取单个字节:返回读取的字节内容,如果已经没有内容,返回-1 * public abstract int read() throws IOException * * 将读取的数据保存到字节数组中:返回读取的数据长度,但是如果读取到结尾了,返回-1 * public int read(byte[] b)throws IOException * * 从输入流读取len字节的数据到一个字节数组。 尝试读取多达len个字节,但是如果读取到结尾了,返回-1。 实际读取的字节数作为整数返回。 * public int read(byte[] b,int off,int len) throws IOException */ //1.定义输出文件的路径 File file = new File("E:"+File.separator+"IODemo"+File.separator+"my.txt"); //2.文件存在 if(file.exists()) { //3.使用InputStream输入流 读取文件 InputStream input = new FileInputStream(file); //准备一个1024字节的数组 byte[] data =new byte[1024]; int foot = 0 ; //表示字节数组的操作角标 int temp = 0 ; //表示接收每次读取的字节数据 //如果读到的值不等于-1 while((temp =input.read())!=-1) { //将读取到的字节赋值给字节数组 data[foot++]=(byte)temp; } //5.关闭输入流 input.close(); //输出读取到的数据 System.out.println("["+new String(data)+"]"); } } }
    最新回复(0)