java学习笔记:输入输出流学习

输入流:
从外部流入内存叫输入流,
主要包括InputStream和Reader

输出流:
从内存输出到外部,

主要包括OutputStream和Writer

InputStream用法

package com.pw.stream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class Test { public static void main(String[] args) { //读取F盘下的test.txt文件 File file = new File("F:\test.txt"); InputStream is = null; try { //因为InputStream是抽象类,所以用他的子类来实例化 is = new FileInputStream(file); //计算文件的总字节数 int count = is.available(); //循环内一次读取的字节 int l = 0; //当前读取的总字节数 int sum = 0; //拼接文本 String output = ""; //一次读取的字节数 byte[] buffer = new byte[2048]; //read方法读到文件结尾返回-1 while ((l = is.read(buffer)) != -1) { //累加读取的总字节数 System.out.println("length:" + l); sum += l; //输入当前读取的文本内容 String temp = new String(buffer, 0, l); System.out.println(temp); //计算当前的读取的比例 System.out.println((sum * 100 / count) + "%"); //累加总文本 output += temp; } //输出总文本 System.out.println(output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 切记关闭输入流!!! try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }

OutputStream用法

package com.pw.stream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Test2 { public static void main(String[] args) { OutputStream os = null; try { os=new FileOutputStream("F:\test2.txt"); String value="the god forgot to give me wings, so i used my dream to fly."; os.write(value.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }