Java IO流
File
文件和目录(文件夹)路径名的抽象表示形式
构造方法
1 package io; 2 3 import java.io.File; 4 5 //记住File file = new File("E:\\demo\\a.txt"); 6 public class FileDemo { 7 public static void main(String[] args) { 8 File file = new File("E:\\demo\\a.txt"); 9 10 File file2 = new File("E:\\demo", "a.txt"); 11 12 File file3 = new File("e:\\demo"); 13 File file4 = new File(file3, "a.txt"); 14 } 15 16 }
创建
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 /* 7 *创建功能: 8 *public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了 9 *public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了 10 *public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来 11 */ 12 public class FileDemo { 13 public static void main(String[] args) throws IOException { 14 File file = new File("e:\\demo"); 15 System.out.println("mkdir:" + file.mkdir()); 16 17 File file2 = new File("e:\\demo\\a.txt"); 18 System.out.println("createNewFile:" + file2.createNewFile()); 19 20 File file7 = new File("e:\\aaa\\bbb\\ccc\\ddd"); 21 System.out.println("mkdirs:" + file7.mkdirs()); 22 23 File file8 = new File("e:\\sakura\\a.txt"); 24 System.out.println("mkdirs:" + file8.mkdirs()); 25 } 26 27 }
删除
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 /* 7 * 删除功能:public boolean delete() 需要注意: 8 * 1.如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下 9 * 2.Java中的删除不走回收站 10 * 3.要删除一个文件夹,请注意文件夹内不能包含文件或者文件夹 11 */ 12 public class FileDemo { 13 public static void main(String[] args) throws IOException { 14 //如果不指定绝对路径,那么默认在项目路径下 15 File file = new File("a.txt"); 16 System.out.println("createNewFile:" + file.createNewFile()); 17 File file2 = new File("aaa\\bbb\\ccc"); 18 System.out.println("mkdirs:" + file2.mkdirs()); 19 20 // 删除功能:删除a.txt这个文件 21 System.out.println("delete:" + file.delete()); 22 // 删除功能:删除ccc这个文件夹 23 System.out.println("delete:" + file2.delete()); 24 // 删除功能:删除aaa文件夹 25 File file5 = new File("aaa"); 26 System.out.println("delete:" + file5.delete()); 27 File file6 = new File("aaa\\bbb"); 28 System.out.println("delete:" + file6.delete()); 29 System.out.println("delete:" + file5.delete()); 30 } 31 32 }
重命名
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 /* 7 * 重命名功能:public boolean renameTo(File dest) 8 * 如果路径名相同,就是改名 9 * 如果路径名不同,就是改名并剪切 10 * 11 * 路径以盘符开始:绝对路径 c:\\a.txt 12 * 路径不以盘符开始:相对路径 a.txt 13 */ 14 public class FileDemo { 15 public static void main(String[] args) throws IOException { 16 File file = new File("林青霞.jpg"); 17 file.createNewFile(); 18 File newFile = new File("东方不败.jpg"); 19 System.out.println("renameTo:" + file.renameTo(newFile)); 20 21 File file2 = new File("东方不败.jpg"); 22 File newFile2 = new File("e:\\林青霞.jpg"); 23 System.out.println("renameTo:" + file2.renameTo(newFile2)); 24 } 25 26 }
判断
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class FileDemo { 7 public static void main(String[] args) throws IOException { 8 File file = new File("a.txt"); 9 file.createNewFile(); 10 System.out.println("isDirectory:" + file.isDirectory());// false 11 System.out.println("isFile:" + file.isFile());// true 12 System.out.println("exists:" + file.exists());// true 13 System.out.println("canRead:" + file.canRead());// true 14 System.out.println("canWrite:" + file.canWrite());// true 15 System.out.println("isHidden:" + file.isHidden());// false 16 } 17 18 }
获取
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 8 /* 9 * 获取功能: 10 * public String getAbsolutePath():获取绝对路径 11 * public String getPath():获取相对路径 12 * public String getName():获取名称 13 * public long length():获取长度即字节数 14 * public long lastModified():获取最后一次的修改时间,毫秒值 15 */ 16 public class FileDemo { 17 public static void main(String[] args) throws IOException { 18 File file = new File("demo\\a.txt"); 19 file.createNewFile(); 20 System.out.println("getAbsolutePath:" + file.getAbsolutePath()); 21 System.out.println("getPath:" + file.getPath()); 22 System.out.println("getName:" + file.getName()); 23 System.out.println("length:" + file.length()); 24 System.out.println("lastModified:" + file.lastModified()); 25 // 1416471971031 26 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 27 System.out.println(sdf.format(new Date(1416471971031L))); 28 } 29 30 }
list和listFiles
1 package io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class FileDemo { 7 public static void main(String[] args) throws IOException { 8 File file = new File("e:\\"); 9 // public String[] list():获取指定目录下的所有文件或者文件夹的名称数组 10 String[] strArray = file.list(); 11 for (String s : strArray) System.out.println(s); 12 13 System.out.println("------------"); 14 // public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组 15 File[] fileArray = file.listFiles(); 16 for (File f : fileArray) System.out.println(f.getName()); 17 } 18 19 }
递归
1 package io; 2 3 import java.io.File; 4 5 //把E:\\BaiduYunDownload目录下所有的jpg结尾的文件的绝对路径给输出在控制台 6 public class FileDemo { 7 public static void main(String[] args) { 8 File srcFolder = new File("E:\\BaiduYunDownload"); 9 getAllJavaFilePaths(srcFolder); 10 } 11 private static void getAllJavaFilePaths(File srcFolder) { 12 File[] fileArray = srcFolder.listFiles(); 13 for (File file : fileArray) { 14 if (file.isDirectory()) { 15 getAllJavaFilePaths(file); 16 } else { 17 if (file.getName().endsWith(".jpg")) { 18 System.out.println(file.getAbsolutePath()); 19 } 20 } 21 } 22 } 23 24 }
递归删除带内容的目录
1 package io; 2 3 import java.io.File; 4 5 public class FileDemo { 6 public static void main(String[] args) { 7 File srcFolder = new File("demo"); 8 deleteFolder(srcFolder); 9 } 10 private static void deleteFolder(File srcFolder) { 11 File[] fileArray = srcFolder.listFiles(); 12 if (fileArray != null) { 13 for (File file : fileArray) { 14 if (file.isDirectory()) { 15 deleteFolder(file); 16 } else { 17 System.out.println(file.getName() + "---" + file.delete()); 18 } 19 } 20 System.out.println(srcFolder.getName() + "---" + srcFolder.delete()); 21 } 22 } 23 24 }
IO流
输入输出是按照Java程序(而不是硬盘)为参照物而言的,输入流读取数据,输出流写出数据
字节流
字符流:为了方便操作文本数据(1个字符2个字节),Windows自带的记事本打开不乱码就用字符流
1 package io; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 /* 6 * IO流的分类: 7 * 流向: 8 * 输入流 读取数据 9 * 输出流 写出数据 10 * 数据类型: 11 * 字节流 12 * 字节输入流 读取数据 InputStream 13 * 字节输出流 写出数据 OutputStream 14 * 字符流 15 * 字符输入流 读取数据 Reader 16 * 字符输出流 写出数据 Writer 17 * 18 * 注意:如果没有明确说明按哪种分类来说,默认情况下是按照数据类型来分的 19 * 20 * 需求:向一个文本文件中输入一句话:"hello,IO" 21 */ 22 public class FileOutputStreamDemo { 23 public static void main(String[] args) throws IOException { 24 FileOutputStream fos = new FileOutputStream("fos.txt"); 25 fos.write("hello,IO".getBytes()); 26 fos.close(); 27 28 FileOutputStream fos2 = new FileOutputStream("fos2.txt"); 29 //public void write(int b):写一个字节 30 fos2.write(97); 31 //public void write(byte[] b):写一个字节数组 32 byte[] bys={97,98,99,100,101}; 33 fos2.write(bys); 34 //public void write(byte[] b,int off,int len):写一个字节数组的一部分 35 fos2.write(bys,1,3); 36 fos2.close(); 37 38 /* 39 数据的换行 40 Windows:\r\n Linux:\n Mac:\r 41 参数true表示把字节写入文件末尾处而不是开始处 42 */ 43 FileOutputStream fos3 = new FileOutputStream("fos3.txt", true); 44 for (int x = 0; x < 10; x++) { 45 fos3.write(("hello" + x).getBytes()); 46 fos3.write("\r\n".getBytes()); 47 } 48 fos3.close(); 49 } 50 51 }
异常处理
1 package io; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 public class FileOutputStreamDemo { 8 public static void main(String[] args) throws IOException { 9 FileOutputStream fos = null; 10 try { 11 fos = new FileOutputStream("fos4.txt"); 12 fos.write("java".getBytes()); 13 } catch (FileNotFoundException e) { 14 e.printStackTrace(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } finally { 18 if (fos != null) { 19 try { 20 fos.close(); 21 } catch (IOException e) { 22 e.printStackTrace(); 23 } 24 } 25 } 26 } 27 28 }
FileInputStream读取数据
1 package io; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 public class FileInputStreamDemo { 7 public static void main(String[] args) throws IOException { 8 FileInputStream fis = new FileInputStream("D:\\idea\\study\\src\\io\\FileOutputStreamDemo.java"); 9 int by; 10 while ((by = fis.read()) != -1) { 11 System.out.print((char) by); 12 } 13 fis.close(); 14 System.out.println("-----------------------------------------------"); 15 FileInputStream fis2 = new FileInputStream("D:\\idea\\study\\src\\io\\FileOutputStreamDemo.java"); 16 byte[] bys = new byte[1024]; 17 int len; 18 while ((len = fis2.read(bys)) != -1) { 19 System.out.print(new String(bys, 0, len)); 20 } 21 fis2.close(); 22 } 23 24 }
字节流复制文本
1 package io; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 public class FileInputStreamDemo { 8 public static void main(String[] args) throws IOException { 9 // 封装数据源 10 FileInputStream fis = new FileInputStream("fos.txt"); 11 // 封装目的地 12 FileOutputStream fos = new FileOutputStream("b.txt"); 13 int by ; 14 while ((by = fis.read()) != -1) { 15 fos.write(by); 16 } 17 fos.close(); 18 fis.close(); 19 } 20 }
字节缓冲流
1 package io; 2 3 import java.io.BufferedOutputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 public class BufferedOutputStreamDemo { 8 public static void main(String[] args) throws IOException { 9 BufferedOutputStream bos = new BufferedOutputStream( 10 new FileOutputStream("bos.txt")); 11 bos.write("hello".getBytes()); 12 bos.close(); 13 } 14 }
1 package io; 2 3 import java.io.BufferedInputStream; 4 import java.io.FileInputStream; 5 import java.io.IOException; 6 7 public class BufferedInputStreamDemo { 8 public static void main(String[] args) throws IOException { 9 //装饰者设计模式 10 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( 11 "bos.txt")); 12 byte[] bys = new byte[1024]; 13 int len; 14 while ((len = bis.read(bys)) != -1) { 15 System.out.print(new String(bys, 0, len)); 16 } 17 bis.close(); 18 } 19 }
字节流四种方式效率对比
1 package io; 2 3 import java.io.*; 4 /* 5 * 需求:把F:\经典电影\刺客信条.mp4复制到当前项目目录下的copy.mp4中 6 * 7 * 字节流四种方式复制文件: 8 * 基本字节流一次读写一个字节:共耗时:414996毫秒 9 * 基本字节流一次读写一个字节数组:共耗时:748毫秒 10 * 高效字节流一次读写一个字节:共耗时:1895毫秒 11 * 高效字节流一次读写一个字节数组:共耗时:127毫秒 12 */ 13 public class CopyMp4Demo { 14 public static void main(String[] args) throws IOException { 15 long start = System.currentTimeMillis(); 16 method4("F:\\经典电影\\刺客信条.mp4", "copy.mp4"); 17 long end = System.currentTimeMillis(); 18 System.out.println("共耗时:" + (end - start) + "毫秒"); 19 } 20 // 高效字节流一次读写一个字节数组 21 public static void method4(String srcString, String destString) 22 throws IOException { 23 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( 24 srcString)); 25 BufferedOutputStream bos = new BufferedOutputStream( 26 new FileOutputStream(destString)); 27 byte[] bys = new byte[1024]; 28 int len; 29 while ((len = bis.read(bys)) != -1) { 30 bos.write(bys, 0, len); 31 } 32 bos.close(); 33 bis.close(); 34 } 35 // 高效字节流一次读写一个字节 36 public static void method3(String srcString, String destString) 37 throws IOException { 38 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( 39 srcString)); 40 BufferedOutputStream bos = new BufferedOutputStream( 41 new FileOutputStream(destString)); 42 int by; 43 while ((by = bis.read()) != -1) { 44 bos.write(by); 45 } 46 bos.close(); 47 bis.close(); 48 } 49 // 基本字节流一次读写一个字节数组 50 public static void method2(String srcString, String destString) 51 throws IOException { 52 FileInputStream fis = new FileInputStream(srcString); 53 FileOutputStream fos = new FileOutputStream(destString); 54 byte[] bys = new byte[1024]; 55 int len; 56 while ((len = fis.read(bys)) != -1) { 57 fos.write(bys, 0, len); 58 } 59 fos.close(); 60 fis.close(); 61 } 62 // 基本字节流一次读写一个字节 63 public static void method1(String srcString, String destString) 64 throws IOException { 65 FileInputStream fis = new FileInputStream(srcString); 66 FileOutputStream fos = new FileOutputStream(destString); 67 int by; 68 while ((by = fis.read()) != -1) { 69 fos.write(by); 70 } 71 fos.close(); 72 fis.close(); 73 } 74 }
转换流
字符流=字节流+编码表
1 package io; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.OutputStreamWriter; 6 /* 7 * OutputStreamWriter(OutputStream out):根据默认编码把字节流的数据转换为字符流 8 * OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流 9 * 把字节流转换为字符流 10 * 字符流 = 字节流 +编码表 11 */ 12 public class OutputStreamWriterDemo { 13 public static void main(String[] args) throws IOException { 14 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( 15 "osw.txt"), "UTF-8"); // 指定UTF-8,不指定默认GBK 16 osw.write("中国"); 17 osw.close(); 18 } 19 }
1 package io; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 /* 7 * InputStreamReader(InputStream is):用默认的编码读取数据 8 * InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据 9 */ 10 public class InputStreamReaderDemo { 11 public static void main(String[] args) throws IOException { 12 InputStreamReader isr = new InputStreamReader(new FileInputStream( 13 "osw.txt"), "UTF-8"); 14 int ch; 15 while ((ch = isr.read()) != -1) { 16 System.out.print((char) ch); 17 } 18 isr.close(); 19 } 20 }
package io; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /* * OutputStreamWriter的方法: * public void write(int c):写一个字符 * public void write(char[] cbuf):写一个字符数组 * public void write(char[] cbuf,int off,int len):写一个字符数组的一部分 * public void write(String str):写一个字符串 * public void write(String str,int off,int len):写一个字符串的一部分 * * close()和flush()的区别? * 1.close()关闭流对象,关闭前刷新一次缓冲区,关闭后流对象不可用 * 2.flush()仅仅刷新缓冲区,刷新后流对象还可用 */ public class OutputStreamWriterDemo { public static void main(String[] args) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( "osw2.txt")); // osw.write('a'); // osw.write(97); // 为什么数据没有进去呢?原因是:字符 = 2字节,文件中数据存储的基本单位是字节。void flush() // char[] chs = {'a','b','c','d','e'}; // osw.write(chs); // osw.write(chs,1,3); // osw.write("sakura1027"); osw.write("sakura1027", 2, 3); osw.flush(); osw.close(); } }
1 package io; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 /* 7 * InputStreamReader的方法: 8 * int read():一次读取一个字符 9 * int read(char[] chs):一次读取一个字符数组 10 */ 11 public class InputStreamReaderDemo { 12 public static void main(String[] args) throws IOException { 13 InputStreamReader isr = new InputStreamReader(new FileInputStream( 14 "D:\\idea\\study\\src\\io\\OutputStreamWriterDemo.java")); 15 // int ch; 16 // while ((ch = isr.read()) != -1) { 17 // System.out.print((char) ch); 18 // } 19 20 char[] chs = new char[1024]; 21 int len; 22 while ((len = isr.read(chs)) != -1) { 23 System.out.print(new String(chs, 0, len)); 24 } 25 isr.close(); 26 } 27 28 }
字符流复制文本文件
1 package io; 2 3 import java.io.*; 4 5 public class CopyFileDemo { 6 public static void main(String[] args) throws IOException { 7 InputStreamReader isr = new InputStreamReader(new FileInputStream( 8 "a.txt")); 9 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( 10 "b.txt")); 11 // int ch; 12 // while ((ch = isr.read()) != -1) { 13 // osw.write(ch); 14 // } 15 16 char[] chs = new char[1024]; 17 int len; 18 while ((len = isr.read(chs)) != -1) { 19 osw.write(chs, 0, len); 20 // osw.flush(); 21 } 22 osw.close(); 23 isr.close(); 24 } 25 }
1 package io; 2 3 import java.io.*; 4 5 public class CopyFileDemo { 6 public static void main(String[] args) throws IOException { 7 FileReader fr = new FileReader("a.txt"); 8 FileWriter fw = new FileWriter("b.txt"); 9 10 // int ch; 11 // while ((ch = fr.read()) != -1) { 12 // fw.write(ch); 13 // } 14 15 char[] chs = new char[1024]; 16 int len; 17 while ((len = fr.read(chs)) != -1) { 18 fw.write(chs, 0, len); 19 } 20 fw.close(); 21 fr.close(); 22 } 23 }
字符缓冲输出流
1 package io; 2 3 import java.io.BufferedWriter; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 public class BufferedWriterDemo { 8 public static void main(String[] args) throws IOException { 9 // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( 10 // new FileOutputStream("bw.txt"))); 11 BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt")); 12 bw.write("hello"); 13 bw.write("world"); 14 bw.write("java"); 15 bw.flush(); 16 bw.close(); 17 } 18 }
字符缓冲输入流
1 package io; 2 3 import java.io.BufferedReader; 4 import java.io.FileReader; 5 import java.io.IOException; 6 7 public class BufferedReaderDemo { 8 public static void main(String[] args) throws IOException { 9 BufferedReader br = new BufferedReader(new FileReader("bw.txt")); 10 // int ch; 11 // while ((ch = br.read()) != -1) { 12 // System.out.print((char) ch); 13 // } 14 15 char[] chs = new char[1024]; 16 int len; 17 while ((len = br.read(chs)) != -1) { 18 System.out.print(new String(chs, 0, len)); 19 } 20 br.close(); 21 } 22 23 }
字符缓冲流复制文本文件
1 package io; 2 3 import java.io.*; 4 5 public class CopyFileDemo { 6 public static void main(String[] args) throws IOException { 7 BufferedReader br = new BufferedReader(new FileReader("a.txt")); 8 BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt")); 9 10 char[] chs = new char[1024]; 11 int len; 12 while ((len = br.read(chs)) != -1) { 13 bw.write(chs, 0, len); 14 bw.flush(); 15 } 16 bw.close(); 17 br.close(); 18 } 19 }
按行读取
1 package io; 2 3 import java.io.*; 4 5 public class BufferedDemo { 6 public static void main(String[] args) throws IOException { 7 // write(); 8 read(); 9 } 10 private static void read() throws IOException { 11 BufferedReader br = new BufferedReader(new FileReader("bw2.txt")); 12 String line = null; 13 while ((line = br.readLine()) != null) { 14 System.out.println(line); 15 } 16 br.close(); 17 } 18 private static void write() throws IOException { 19 BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt")); 20 for (int x = 0; x < 10; x++) { 21 bw.write("hello" + x); 22 // bw.write("\r\n"); 23 bw.newLine(); 24 bw.flush(); 25 } 26 bw.close(); 27 } 28 }
1 package io; 2 3 import java.io.*; 4 5 public class CopyFileDemo { 6 public static void main(String[] args) throws IOException { 7 BufferedReader br = new BufferedReader(new FileReader("a.txt")); 8 BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt")); 9 10 String line = null; 11 while ((line = br.readLine()) != null) { 12 bw.write(line); 13 bw.newLine(); 14 bw.flush(); 15 } 16 17 bw.close(); 18 br.close(); 19 } 20 21 }
操作基本数据类型的流
1 package io; 2 3 import java.io.*; 4 /* 5 * 可以读写基本数据类型的流 6 * 数据输入流:DataInputStream 7 * DataInputStream(InputStream in) 8 * 数据输出流:DataOutputStream 9 * DataOutputStream(OutputStream out) 10 */ 11 public class DataStreamDemo { 12 public static void main(String[] args) throws IOException { 13 // write(); 14 read(); 15 } 16 private static void read() throws IOException { 17 DataInputStream dis = new DataInputStream( 18 new FileInputStream("dos.txt")); 19 System.out.println(dis.readByte()); 20 System.out.println(dis.readShort()); 21 System.out.println(dis.readInt()); 22 System.out.println(dis.readLong()); 23 System.out.println(dis.readFloat()); 24 System.out.println(dis.readDouble()); 25 System.out.println(dis.readChar()); 26 System.out.println(dis.readBoolean()); 27 dis.close(); 28 } 29 private static void write() throws IOException { 30 DataOutputStream dos = new DataOutputStream(new FileOutputStream( 31 "dos.txt")); 32 dos.writeByte(10); 33 dos.writeShort(100); 34 dos.writeInt(1000); 35 dos.writeLong(10000); 36 dos.writeFloat(12.34F); 37 dos.writeDouble(12.56); 38 dos.writeChar('a'); 39 dos.writeBoolean(true); 40 dos.close(); 41 } 42 43 }
内存操作流
1 package io; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.IOException; 6 /* 7 * 内存操作流:用于处理临时存储信息的,程序结束数据就从内存中消失 8 * 字节数组: 9 * ByteArrayInputStream 10 * ByteArrayOutputStream 11 * 字符数组: 12 * CharArrayReader 13 * CharArrayWriter 14 * 字符串: 15 * StringReader 16 * StringWriter 17 */ 18 public class ByteArrayStreamDemo { 19 public static void main(String[] args) throws IOException { 20 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 21 for (int x = 0; x < 10; x++) { 22 baos.write(("hello" + x+" ").getBytes()); 23 } 24 // 并不需要close() 25 byte[] bys = baos.toByteArray(); 26 ByteArrayInputStream bais = new ByteArrayInputStream(bys); 27 int by; 28 while ((by = bais.read()) != -1) { 29 System.out.print((char) by); 30 } 31 } 32 }
打印流
1 package io; 2 3 import java.io.FileWriter; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 /* 7 * 打印流 8 * 字节流打印流 PrintStream 9 * 字符打印流 PrintWriter 10 * 11 * 打印流的特点: 12 * 1.只能写数据而不能读取数据,即只能操作目的地,不能操作数据源 13 * 2.可以操作任意类型的数据 14 * 3.如果启动了自动刷新,能够自动刷新 15 * 4.可以直接操作文本文件的 16 * 哪些流对象可以直接操作文本文件? 17 * FileInputStream FileOutputStream 18 * FileReader FileWriter 19 * PrintStream PrintWriter 20 * 流对象的构造方法同时有File类型和String类型的参数可以直接操作文本文件 21 */ 22 public class PrintWriterDemo { 23 public static void main(String[] args) throws IOException { 24 PrintWriter pw = new PrintWriter("pw.txt"); 25 pw.write("hello"); 26 pw.write("world"); 27 pw.write("java"); 28 pw.close(); 29 30 PrintWriter pw2 = new PrintWriter(new FileWriter("pw2.txt"), true); 31 pw2.println("hello"); 32 pw2.println(true); 33 pw2.println(100); 34 pw2.close(); 35 } 36 37 }
标准输入输出流
1 package io; 2 3 import java.io.PrintStream; 4 /* 5 * 标准输入输出流 6 * System类中的两个成员变量: 7 * public static final InputStream in 标准输入流。 8 * public static final PrintStream out 标准输出流。 9 * 10 * InputStream is = System.in; 11 * PrintStream ps = System.out; 12 */ 13 public class SystemOutDemo { 14 public static void main(String[] args) { 15 System.out.println("helloworld"); 16 PrintStream ps = System.out; 17 ps.println("helloworld"); 18 ps.println(); 19 } 20 21 }
1 package io; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 /* 7 * System.in 标准输入流,是从键盘获取数据的 8 * 9 * 键盘录入数据: 10 * 1.main方法的args接收参数 11 * 2.Scanner(JDK1.5以后) 12 * Scanner sc = new Scanner(System.in); 13 * String s = sc.nextLine(); 14 * int x = sc.nextInt() 15 * 3.通过字符缓冲流包装标准输入流实现 16 * BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 17 */ 18 public class SystemInDemo { 19 public static void main(String[] args) throws IOException { 20 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 21 System.out.println(br.readLine()); 22 System.out.println(Integer.parseInt(br.readLine())); 23 } 24 25 }
随机访问流
1 package io; 2 3 import java.io.IOException; 4 import java.io.RandomAccessFile; 5 /* 6 * 随机访问流: 7 * RandomAccessFile类不属于流,是Object类的子类 8 * 但它融合了InputStream和OutputStream的功能,支持对文件的随机访问读取和写入 9 * 10 * public RandomAccessFile(String name,String mode):第一个参数是文件路径,第二个参数是操作文件的模式 11 */ 12 public class RandomAccessFileDemo { 13 public static void main(String[] args) throws IOException { 14 // write(); 15 read(); 16 } 17 private static void read() throws IOException { 18 RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw"); 19 int i = raf.readInt(); 20 System.out.println(i); 21 // 文件指针可以通过getFilePointer方法读取,并通过seek方法设置 22 System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); 23 24 char ch = raf.readChar(); 25 System.out.println(ch); 26 System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); 27 28 String s = raf.readUTF(); 29 System.out.println(s); 30 System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); 31 32 raf.seek(4); 33 ch = raf.readChar(); 34 System.out.println(ch); 35 } 36 private static void write() throws IOException { 37 RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw"); 38 raf.writeInt(100); 39 raf.writeChar('a'); 40 raf.writeUTF("中国"); 41 raf.close(); 42 } 43 44 }
合并流
1 package io; 2 3 import java.io.*; 4 /* 5 * a.txt+b.txt -- c.txt 6 */ 7 public class SequenceInputStreamDemo { 8 public static void main(String[] args) throws IOException { 9 InputStream s1 = new FileInputStream("a.txt"); 10 InputStream s2 = new FileInputStream("b.txt"); 11 SequenceInputStream sis = new SequenceInputStream(s1, s2); 12 BufferedOutputStream bos = new BufferedOutputStream( 13 new FileOutputStream("Copy.java")); 14 byte[] bys = new byte[1024]; 15 int len; 16 while ((len = sis.read(bys)) != -1) { 17 bos.write(bys, 0, len); 18 } 19 bos.close(); 20 sis.close(); 21 } 22 23 }
1 package io; 2 3 import java.io.*; 4 import java.util.Enumeration; 5 import java.util.Vector; 6 /* 7 * a.txt+b.txt+c.txt -- d.txt 8 */ 9 public class SequenceInputStreamDemo { 10 public static void main(String[] args) throws IOException { 11 Vector<InputStream> v = new Vector<>(); 12 InputStream s1 = new FileInputStream("a.txt"); 13 InputStream s2 = new FileInputStream("b.txt"); 14 InputStream s3 = new FileInputStream("c.txt"); 15 v.add(s1); 16 v.add(s2); 17 v.add(s3); 18 Enumeration<InputStream> en = v.elements(); 19 SequenceInputStream sis = new SequenceInputStream(en); 20 BufferedOutputStream bos = new BufferedOutputStream( 21 new FileOutputStream("Copy.java")); 22 byte[] bys = new byte[1024]; 23 int len; 24 while ((len = sis.read(bys)) != -1) { 25 bos.write(bys, 0, len); 26 } 27 bos.close(); 28 sis.close(); 29 } 30 31 }
序列化流
1 package io; 2 3 import java.io.Serializable; 4 /* 5 * NotSerializableException:未序列化异常 6 * 7 * java.io.InvalidClassException: Person;local class incompatible: 8 * stream classdesc serialVersionUID = -2071565876962058344, 9 * local class serialVersionUID = 2354112110978210568 10 */ 11 public class Person implements Serializable { 12 private static final long serialVersionUID = -2071565876962058344L; 13 private String name; 14 private transient int age; 15 16 public Person() { 17 super(); 18 } 19 public Person(String name, int age) { 20 super(); 21 this.name = name; 22 this.age = age; 23 } 24 public String getName() { 25 return name; 26 } 27 public void setName(String name) { 28 this.name = name; 29 } 30 public int getAge() { 31 return age; 32 } 33 public void setAge(int age) { 34 this.age = age; 35 } 36 @Override 37 public String toString() { 38 return "Person [name=" + name + ", age=" + age + "]"; 39 } 40 }
1 package io; 2 3 import java.io.*; 4 /* 5 * 序列化流:把对象按照流一样的方式存入文本文件或者在网络中传输 对象 -- 流数据(ObjectOutputStream) 6 * 反序列化流:把文本文件中的流对象数据或者网络中的流对象数据还原成对象 流数据 -- 对象(ObjectInputStream) 7 */ 8 public class ObjectStreamDemo { 9 public static void main(String[] args) throws IOException, 10 ClassNotFoundException { 11 // write(); 12 read(); 13 } 14 private static void read() throws IOException, ClassNotFoundException { 15 ObjectInputStream ois = new ObjectInputStream(new FileInputStream( 16 "oos.txt")); 17 Object obj = ois.readObject(); 18 ois.close(); 19 System.out.println(obj); 20 } 21 private static void write() throws IOException { 22 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( 23 "oos.txt")); 24 Person p = new Person("林青霞", 27); 25 oos.writeObject(p); 26 oos.close(); 27 } 28 29 }
Properties
Properties类表示了一个持久的属性集,Properties可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串
1 package io; 2 3 import java.util.Properties; 4 import java.util.Set; 5 /* 6 * public Object setProperty(String key,String value):添加元素 7 * public String getProperty(String key):获取元素 8 * public Set<String> stringPropertyNames():获取所有的键的集合 9 */ 10 public class PropertiesDemo { 11 public static void main(String[] args) { 12 Properties prop = new Properties(); 13 prop.put("001", "hello"); 14 prop.put("002", "world"); 15 prop.put("003", "java"); 16 Set<Object> set = prop.keySet(); 17 for (Object key : set) { 18 Object value = prop.get(key); 19 System.out.println(key + "---" + value); 20 } 21 22 prop.setProperty("004","sakura1027"); 23 Set<String> set2=prop.stringPropertyNames(); 24 for(String key:set2){ 25 String value=prop.getProperty(key); 26 System.out.println(key + "---" + value); 27 } 28 } 29 30 }
1 package io; 2 3 import java.io.*; 4 import java.util.Properties; 5 /* 6 * public void load(Reader reader):把文件中的数据读取到Properties集合中 7 * public void store(Writer writer,String comments):把Properties集合中的数据存储到文件 8 */ 9 public class PropertiesDemo { 10 public static void main(String[] args) throws IOException { 11 myLoad(); 12 // myStore(); 13 } 14 private static void myStore() throws IOException { 15 Properties prop = new Properties(); 16 prop.setProperty("林青霞", "27"); 17 prop.setProperty("刘晓曲", "18"); 18 Writer w = new FileWriter("name.txt"); 19 prop.store(w, "helloworld"); 20 w.close(); 21 } 22 private static void myLoad() throws IOException { 23 Properties prop = new Properties(); 24 Reader r = new FileReader("name.txt"); 25 prop.load(r); 26 r.close(); 27 System.out.println("prop:" + prop); 28 } 29 30 }