Java——IO流_字节流_结点流_文件读取、写出

来源:互联网 发布:淘宝专业版全屏店招 编辑:程序博客网 时间:2024/05/11 13:34

步骤

1、建立联系
2、选择流
3、操作 数组大小+read、write
4、释放资源

文件读入

代码:

package io.byteIO;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;/** * 文件的读取 * 1、建立联系   File对象 * 2、选择流        文件输入流  InputStream  FileInputStream * 3、读取操作   byte[] arr = new byte[1024]; + read + 读取大小   *      输出 * 4、释放资源:关闭 * @author yangzheng */public class Demo1 {    public static void main(String[] args) {        //建立file对象        File file = new File("E:/Java/Java_Code/何为高手.txt");        //选择流        InputStream is = null;  //提高作用域        try {            is = new FileInputStream(file);            //缓冲数组            byte[] arr = new byte[10];            int len = 0; //接受实际读取大小            //循环读取            while (-1 != (len = is.read(arr))) {                //输出  字节数组转化为字符串                String str = new String(arr, 0, len);                System.out.print(str);            }        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("文件不存在");        } catch (IOException e) {            e.printStackTrace();            System.out.println("文件读取失败");        } finally{            try {                //释放资源                is.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();                System.out.println("关闭文件输入流失败");            }        }    }}

截图:
这里写图片描述
可见,乱码了。日后解决。。。

文件写出

代码:

package io.byteIO;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;/** * 文件输入流 * @author yangzheng * */public class Demo2 {    public static void main(String[] args) {        File file = new File("E:/Java/Java_Code/何为菜鸟.txt");        OutputStream os = null;        try {            os = new FileOutputStream(file,true); //true表示以追加形式写出文件            String str = new String("计算机初学者\r\n");            //字符串转化为字节数组            byte[] arr = str.getBytes();            os.write(arr);            os.flush();//强制刷新出去,        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("文件不存在");        } catch (IOException e) {            e.printStackTrace();            System.out.println("文件写出失败");        } finally {            try {                os.close();            } catch (IOException e) {                e.printStackTrace();                System.out.println("关闭文件输入流失败");            }        }    }}

截图:

这里写图片描述

0 0
原创粉丝点击