IO流学习笔记
通过Buffered复制文件
package javaBase.io; import java.io.*; //通过字符流复制文件 public class FileCopyReadWrite { public static void main(String[] args) { copy(); } public static void copy(){ BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader("original.java")); bw = new BufferedWriter(new FileWriter("original_copy.java")); String str = null; while((str = br.readLine())!=null){ bw.write(str); bw.newLine();//readLine()不返回任何行终止符 bw.flush(); } } catch (IOException e) { throw new RuntimeException("read_write error !"); }finally{ try { if(br!=null) br.close(); } catch (IOException e) { throw new RuntimeException("read error !"); } try { if(bw!=null)//不判断的话可能会报空指针的错误 bw.close(); } catch (IOException e) { throw new RuntimeException("write error !"); } } } }
自定义一个BufferedReader 实现readLine()方法
package javaBase.io; import java.io.*; //自定义一个BufferedReader来模拟实现readLine方法 class MyBufferedReader { private FileReader fr; public MyBufferedReader(FileReader fr){//构造方法 this.fr = fr; } public String myReadLine() throws IOException{ //定义一个临时容器来存放一行的数据,源码使用字符数组 //这里用StringBuilder(可变字符序列,非线程安全),最终都是要转成String返回的 StringBuilder sb = new StringBuilder(); int ch = 0; while((ch = fr.read())!= -1){ if(ch == '\r') continue; if(ch =='\n') return sb.toString(); else sb.append((char)ch); } if(sb.length()!=0)//最后一行若是没有换行符的处理 return sb.toString(); return null; } public void myClose() throws IOException{ fr.close(); } } class MyReadLine{ public static void main(String[] args) throws IOException { MyBufferedReader mybr = new MyBufferedReader(new FileReader("original.java")); String str = null; while((str = mybr.myReadLine())!=null){ System.out.println(str); } mybr.myClose(); } }
字节流读取写入操作
package javaBase.io.stream; import java.io.*; //想要处理图片,视频等非文本数据,得用字节流 public class FileOutPutStreamDemo { public static void main(String[] args) throws IOException{ writeFile(); readFile(); } public static void readFile() throws IOException { FileInputStream fi = new FileInputStream("original.java"); byte[] buff = new byte[1024*2];//缓冲,用available()数据太大可能出现内存溢出 int len = 0; while((len = fi.read(buff))!=-1){//len是读入缓冲区字节总数 System.out.println(new String(buff,0,len));//String类的构造方法之一 } fi.close(); } public static void writeFile() throws IOException{ FileOutputStream fo = new FileOutputStream("original.java"); fo.write("abcde".getBytes());//字符串转byte[], toCharArray()是转char[] fo.close(); } }
字节流复制图片
package javaBase.io.stream; import java.io.*; public class CopyPic { public static void main(String[] args) { copyFile(); } public static void copyFile() { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("E:\\Admin\\workspace\\itHeima\\man.jpg"); fos = new FileOutputStream( "E:\\Admin\\workspace\\itHeima\\man_copy.jpg"); byte[] buff = new byte[1024 * 4]; int len = 0; while ((len = fis.read(buff)) != -1) { fos.write(buff, 0, len);// 写入有效数据 } } catch (IOException e) { throw new RuntimeException("读写失败"); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { throw new RuntimeException("读失败"); } try { if (fos != null) fos.close(); } catch (IOException e) { throw new RuntimeException("写失败"); } } } }
通过键盘录入数据,每输入一行结束就转换为大写打印出来
遇到over结束
package javaBase.io.stream; import java.io.*; //通过键盘录入数据,每输入一行结束就转换为大写打印出来 //遇到over结束 public class SystemInDemo { public static void main(String[] args) throws IOException { //streamInLine(); castInLine();// } /** * 字节流字符流转换 */ public static void castInLine() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//键盘录入标准写法 String str = null; while((str =br.readLine())!=null){ if("over".equalsIgnoreCase(str)) break;//定义键盘录入结束标记,否则按CTRL+C System.out.println(str.toUpperCase()); } br.close(); } /** * 字节流方法 */ public static void streamInLine() throws IOException { InputStream in = System.in; StringBuilder sb = new StringBuilder(); while (true) { int ch = in.read(); if (ch == '\r') continue; if (ch == '\n') { String s = sb.toString(); if ("over".equalsIgnoreCase(s)) {// 字符串的比较 break; } System.out.println(s.toUpperCase()); sb.delete(0, sb.length());// 每打印一次就清空缓冲 } else // 必须有,不然在没有输入over的情况下每次清空sb后都会执行下面的语句,sb开头都带'\n' sb.append((char) ch); } } }
printWriter
package javaBase.io.others; import java.io.*; /* * PrintWriter 构造函数接收参数: * 1,字符串路径 * 2,File对象 * 3,字节输出流outputstream * 4,Writer(PrintStream没有) */ public class PrintWriterDemo { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out,true);//TRUE会对println自动刷缓冲 // PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);//File同样可以 String line = null; while((line = in.readLine())!=null){ if("over".equals(line)) break; out.println(line); } in.close(); out.close(); } }
Piped管道流
package javaBase.io; import java.io.*; /* * 读取管道流 */ class ReadThread implements Runnable{ private PipedInputStream in; ReadThread(PipedInputStream in){ this.in = in; } @Override public void run() { byte[] buff = new byte[1024]; try { System.out.println("读取之前"); int len = in.read(buff); System.out.println("读好了"); String str = new String(buff,0,len); System.out.println(str); in.close(); } catch (IOException e) { throw new RuntimeException("管道读取异常"); } } } /* * 写入管道流 */ class WriteThread implements Runnable{ private PipedOutputStream out ; public WriteThread(PipedOutputStream out) { this.out = out; } @Override public void run() { try { System.out.println("写线程休息4秒"); Thread.sleep(4000);//interruption异常不是IO异常 out.write("write some thing.....".getBytes());//字符串转字节数组 out.close(); } catch (Exception e) { throw new RuntimeException("管道写入异常"); } } } public class PipedStreamDemo { public static void main(String[] args) throws IOException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(); in.connect(out);//out作为in 的输入 WriteThread write = new WriteThread(out); ReadThread read = new ReadThread(in); new Thread(write).start(); new Thread(read).start(); } }