36.5 字符流写数据的5种方式
package myCharStream.Demo2; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; //write方法演示 public class Demo02 { public static void main(String[] args) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt")); // osw.write(97); // //void slush() 刷新流 // osw.flush(); // osw.write(98); osw.flush(); // osw.write(99); // osw.close(); //自带刷新, 后面接着写数据会报错 //写入字符数组数据 // char[] chs = {'a', 'b', 'c', 'd', 'e'}; // osw.write(chs); //写入部分数组数据 // osw.write(chs, 1, 3); //一次写入一个字符串 // osw.write("abcdefg"); //写入字符串的部分 osw.write("anceghj", 1, 3); osw.close(); } }
36.6 字符流读数据的两种方式
package myCharStream.Demo2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; //读数据 public class Demo03 { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt")); // //一次读一个字符数据 // int ch; // while ((ch = isr.read()) != -1) { // System.out.print((char) ch); // } //一次读一个字符数组数据 char[] chs = new char[1024]; int len; while ((len = isr.read(chs)) != -1) { System.out.print(new String(chs, 0, len)); } isr.close(); } }
案例:复制java文件
package myCharStream.Demo2; import java.io.*; import java.util.Objects; public class Demo04 { public static void main(String[] args) throws IOException { //读对象 InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\itcast\\demo01.java")); //写对象 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\itcast\\new_demo01.java")); //两种方式 // //1.一次读写一个字符数据 // int ch; // while ((ch = isr.read()) != -1) { // osw.write(ch); // } //2.一次读写一个字符数组数据 char[] chs = new char[1024]; int len; while ((len = isr.read(chs)) != -1) { osw.write(chs, 0, len); } osw.close(); isr.close(); } }
案例二:案例一改进版
package myCharStream.Demo03; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Demo01 { public static void main(String[] args) throws IOException { //根据数据源创建字符输入流对象 FileReader fr = new FileReader("D:\\itcast\\demo01.java"); FileWriter fw = new FileWriter("D:\\itcast\\new_demo.java"); // //读写数据 // int ch; // while((ch= fr.read())!=-1){ // fw.write(ch); // } char[] chs = new char[1024]; int len; while ((len = fr.read(chs)) != -1) { fw.write(chs, 0, len); } //释放资源 fw.close(); fr.close(); } }
36.7 字符缓冲流
package myCharStream.Demo03; import java.io.*; public class Demo02 { public static void main(String[] args) throws IOException { // FileWriter fw = new FileWriter("nw.txt"); // BufferedWriter bw = new BufferedWriter(fw); BufferedWriter bw = new BufferedWriter(new FileWriter("nw.txt")); bw.write("abcedf"); bw.close(); BufferedReader br = new BufferedReader(new FileReader("nw.txt")); int ch; while((ch=br.read())!=-1){ System.out.print((char) ch); } // char[] chs = new char[1024]; // int len; // while ((len = br.read(chs)) != -1) { // System.out.print(new String(chs, 0, len)); // } } }
案例
package myCharStream.Demo03; import java.io.*; public class Demo03 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("nw.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("new_nw.txt")); int ch; while ((ch = br.read()) != -1) { bw.write(ch); } // char[] chs = new char[1024]; // int len; // while ((len = br.read(chs)) != -1) { // bw.write(chs, 0, len); // } br.close(); bw.close(); } }
36.8 字符缓冲流特有功能
package myCharStream.Demo04; import java.io.*; public class Demo01 { public static void main(String[] args) throws IOException { // BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt")); // //写数据 // for (int i = 0; i < 10; i++) { // bw.write("hello" + i); bw.write("\r\n"); // bw.newLine(); //写一行,换一行,刷一行 // bw.flush(); // } // // //释放资源 // bw.close(); //创建字符缓冲流入流 BufferedReader br = new BufferedReader(new FileReader("bw.txt")); // String line = br.readLine(); // System.out.println(line); // //再读一行 // line = br.readLine(); // System.out.println(line); //循环改进 String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } }
案例:
package myCharStream.Demo04; import java.io.*; public class Demo02 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java")); BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\itcast\\new_demo.java")); //读写数据,复制文件 String line; while((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); //写一行,换一行,刷一行 } br.close(); bw.close(); } }
36.9 IO流小结
案例:集合到文件
package myCharStream.Demo05; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; //案例:集合数据写入文件 public class Demo01 { public static void main(String[] args) throws IOException { //创建ArrayList集合 ArrayList<String> array = new ArrayList<>(); //集合中添加字符串 array.add("hello"); array.add("world"); array.add("java"); //创建字符缓冲输出流对象 BufferedWriter bw = new BufferedWriter(new FileWriter("array.txt")); //遍历集合,到文件 for (String s : array) { bw.write(s); bw.newLine(); bw.flush(); } //释放资源 bw.close(); } }
案例:文件到集合
package myCharStream.Demo05; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; //案例文本文件中数据写入集合 public class Demo02 { public static void main(String[] args) throws IOException { //创建字符缓冲输入流对象 BufferedReader br = new BufferedReader(new FileReader("array.txt")); //创建ArrayList集合对象 ArrayList<String> array = new ArrayList<>(); //读数据 String line; while ((line = br.readLine()) != null) { array.add(line); } //释放资源 br.close(); //遍历集合,查看数据 for (String s : array) { System.out.println(s); } } }
案例:点名器
package myCharStream.Demo05; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class Demo03 { public static void main(String[] args) throws IOException { //创建字符缓冲输入流对象 BufferedReader br = new BufferedReader(new FileReader("D:itcast\\names.txt")); //创建ArrayList集合对象 ArrayList<String> array = new ArrayList<>(); String line; while((line=br.readLine())!=null){ array.add(line); } //释放资源 br.close(); //使用random产生随机数 Random r = new Random(); int index = r.nextInt(array.size()); //把产生的随机数作为索引取值 String name = array.get(index); //输出 System.out.println(name); } }
案例:文件到集合改进版
package myCharStream.Demo06; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Demo01 { public static void main(String[] args) throws IOException { //创建集合 ArrayList<Student> array = new ArrayList<>(); //创建学生对象 Student s1 = new Student("01", "林青霞", 30, "西安"); Student s2 = new Student("02", "张曼玉", 35, "武汉"); Student s3 = new Student("03", "王祖贤", 33, "郑州"); //把学生对象添加到集合中 array.add(s1); array.add(s2); array.add(s3); //创建字符缓冲输出流对象 BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt")); //遍历集合,得到每个学生对象 for (Student s : array) { //拼接学生 StringBuilder sb = new StringBuilder(); sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); //写数据 bw.write(sb.toString()); bw.newLine(); bw.flush(); } //释放资源 bw.close(); } }
案例:文件到集合改进版
package myCharStream.Demo06; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class Demo02 { public static void main(String[] args) throws IOException { //创建字符缓冲输入流对象 BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\student.txt")); //创建ArrayList集合对象 ArrayList<Student> array = new ArrayList<>(); //调用字符缓冲输入流对象的方法读数据 String line; while((line=br.readLine())!=null){ //读取的数据写入数组 String[] strArray = line.split(","); //创建学生对象 Student s = new Student(); //给学生赋值 s.setSid(strArray[0]); s.setName(strArray[1]); s.setAge(Integer.parseInt(strArray[2])); s.setAddress(strArray[3]); //学生对象添加到集合 array.add(s); } //释放资源 br.close(); //遍历集合查看数据 for(Student s : array){ System.out.println(s.getSid()+","+s.getName()+","+s.getAge()+","+s.getAddress()); } } }
案例:集合到文件
package TestDemo; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class Demo01 { public static void main(String[] args) throws IOException { //创建TreeSet集合 TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //成绩排序 int num = s2.getSum() - s1.getSum(); //次要条件 int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num; int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2; int num4 = num3 == 0 ? s1.getName().compareTo(s2.getName()) : num3; return num4; } }); //键盘录入学生数据 for (int i = 0; i < 5; i++) { Scanner sc = new Scanner(System.in); System.out.println("请录入第" + (i + 1) + "个学生信息:"); System.out.println("姓名:"); String name = sc.nextLine(); System.out.println("语文成绩:"); int chinese = sc.nextInt(); System.out.println("数学成绩:"); int math = sc.nextInt(); System.out.println("英语成绩:"); int english = sc.nextInt(); //创建学生对象,并赋值 Student s = new Student(); s.setName(name); s.setChinese(chinese); s.setMath(math); s.setEnglish(english); //学生添加到集合 ts.add(s); } //创建字符缓冲流对象 BufferedWriter bw = new BufferedWriter(new FileWriter("ts.txt")); //遍历集合,得到每一个学生对象 for (Student s : ts) { //拼接数据 StringBuilder sb = new StringBuilder(); sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish()).append(",").append(s.getSum()); //调用字符缓冲输出流对象的方法写数据 bw.write(sb.toString()); bw.newLine(); bw.flush(); } //释放资源 bw.close(); } }
案例:复制单级文件夹
package TestDemo; import java.io.*; public class Demo02 { public static void main(String[] args) throws IOException { //创建数据源目录File对象 File srcFolder = new File("D:\\itcast"); //获取数据源目录File对象的名称 String srcFolderName = srcFolder.getName(); //创建目的地目录File对象 File destFolder = new File("D:\\new_itcast"); //判断目的地目录是否存在,不存在则创建 if(!destFolder.exists()){ destFolder.mkdir(); } //获取数据源目录下所有文件的File数组 File[] listFiles = srcFolder.listFiles(); //遍历File数组 for(File srcFile:listFiles){ String srcFilename = srcFile.getName(); File destFile = new File(destFolder,srcFilename); //复制文件 copyFile(srcFile,destFile); } } private static void copyFile(File srcFile, File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] bys = new byte[1024]; int len; while((len=bis.read())!=-1){ bos.write(bys,0,len); } bos.close(); bis.close(); } }
案例:复制多级文件夹
package TestDemo; import java.io.*; public class Demo03 { public static void main(String[] args) throws IOException { //创建数据源File对象 File srcFile = new File("D:\\itcast"); //创建目的地File对象 File destFile = new File("D:\\new_itcast"); //判断目的地目录是否存在,不存在则创建 if (!destFile.exists()) { destFile.mkdir(); } //复制文件夹 copyFolder(srcFile, destFile); } //复制文件夹 private static void copyFolder(File srcFile, File destFile) throws IOException { //判断数据源是否为目录 if (srcFile.isDirectory()) { String srcFileName = srcFile.getName(); //得到目录的字符串表示 File newFolder = new File(destFile, srcFileName); //封装成新的路径名 if (!newFolder.exists()) { //目的地子文件夹不存在 newFolder.mkdir(); //则创建 } //获取数据源File下所有文件或目录的File数组 File[] fileArray = srcFile.listFiles(); for (File file : fileArray) { copyFolder(file, newFolder); } } else { //是文件 File newFile = new File(destFile, srcFile.getName()); copyFile(srcFile, newFile); } } private static void copyFile(File srcFile, File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] bys = new byte[1024]; int len; while ((len = bis.read()) != -1) { bos.write(bys, 0, len); } bos.close(); bis.close(); } }
36.10 复制文件的异常处理
package TestDemo; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; //复制文件 加入异常处理 public class Demo04 { public static void main(String[] args) { } //抛出处理 public static void method1() throws IOException { FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } fw.close(); fr.close(); } //try...catch...finally public static void method2() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("fr.txt"); fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } //JDK7的改进方案 public static void method3() { try (FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt");) { char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } //自动释放资源,不需要close } //JDK9改进方案 有啥用???还是要抛出 public static void method4() throws IOException { FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); try (fr; fw) { char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } //自动释放资源,不需要close } }
37 特殊操作流
37.1 标准输入输出流
package myOtherStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; //标准输入流 public class Demo01 { public static void main(String[] args) throws IOException { //标准输入流,数据来自键盘输入 // InputStream is = System.in; //字节读数据 // int by; // while ((by = is.read()) != -1) { // System.out.println((char) by); // } // //如何把字节流转换为字符流?:转换流 // InputStreamReader isr = new InputStreamReader(is); // //使用字符流能不能够实现一次读取一行数据?:这是字符缓冲输入流的特有方法 // BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请输入一个字符串:"); String line = br.readLine(); System.out.println("你输入的字符串是:" + line); System.out.println("请输入一个整数:"); int i = Integer.parseInt(br.readLine()); System.out.println("你输入的整数是:" + i); //自己实现键盘录入数据太麻烦了,所以java就提供了一个类供我们使用 Scanner sc = new Scanner(System.in); } }
标准输出流:
package myOtherStream; import java.io.PrintStream; //标准输出流 public class Demo02 { public static void main(String[] args) { //public static final PrintStream out:标准输出流 PrintStream ps = System.out; //能够方便地打印各种数据值 // ps.print("hello"); // ps.print(100); // ps.println("world"); // ps.println(200); //System.out的本质是一个字节输出流 System.out.println("hello"); System.out.println(100); } }
37.2 打印流
package myOtherStream; import java.io.FileNotFoundException; import java.io.PrintStream; //字节打印流 public class Demo03 { public static void main(String[] args) throws FileNotFoundException { PrintStream ps = new PrintStream("ps.txt"); //写数据 //字节输出流有的方法 ps.write(97); //a //使用特有方法写数据 ps.print(97); //97 ps.println(98); //释放文件 ps.close(); } }
字符打印流
package myOtherStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; //字符打印流 public class Demo04 { public static void main(String[] args) throws IOException { // PrintWriter pw = new PrintWriter("pw.txt"); // pw.write("hello"); // pw.write("\r\n"); // pw.flush(); // pw.write("world"); // pw.flush(); // pw.println("hello"); // pw.flush(); // pw.println("world"); // pw.flush(); PrintWriter pw = new PrintWriter(new FileWriter("pw.txt"), true); //true实现自动刷新 pw.println("hello"); pw.println("world"); pw.close(); } }
案例:复制java文件
package myOtherStream; import java.io.*; //案例:复制文件 public class Demo05 { public static void main(String[] args) throws IOException { /* //根据数据源创建字符输入流对象 BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java")); //根据目的地创建字符输出流对象 BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\itcast\\copy.java")); //读写数据,复制文件 String line; while((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //释放资源 bw.close(); br.close(); */ BufferedReader br = new BufferedReader(new FileReader("D:\\itcast\\Demo01.java")); PrintWriter pw = new PrintWriter(new FileWriter("D:\\itcast\\new_copy.java"), true); //读写数据,复制文件 String line; while((line=br.readLine())!=null){ pw.println(line); } //释放资源 pw.close(); br.close(); } }
37.3 对象序列化流
package myOtherStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; //对象序列化流 public class Demo06 { public static void main(String[] args) throws IOException { //对象序列化流 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt")); //创建对象 Student s = new Student("林青霞", 18); //序列化对象 oos.writeObject(s); //NotSerializableException //释放资源 oos.close(); } }
package myOtherStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; //对象的反序列化流 public class Demo07 { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\itcast\\oos.txt")); //readObject Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); //释放资源 ois.close(); } }
package myOtherStream; import java.io.*; public class Demo08 { public static void main(String[] args) throws IOException, ClassNotFoundException { write(); read(); } //反序列化 private static void read() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\itcast\\oos.txt")); Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } //序列化 private static void write() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\itcast\\oos.txt")); Student s = new Student("林青霞", 18); oos.writeObject(s); oos.close(); } }
37.4 Properties
package myOtherStream; import java.util.Properties; import java.util.Set; //Properties作为Map集合的使用 public class Demo09 { public static void main(String[] args) { //创建集合对象 // Properties<String,String> prop = new Properties(); Properties prop = new Properties(); //存储元素 prop.put("01", "林青霞"); prop.put("02", "张曼玉"); prop.put("03", "王祖贤"); //遍历集合 Set<Object> keySet = prop.keySet(); for (Object key : keySet) { Object value = prop.get(key); System.out.println(key + "," + value); } } }
Properties特有方法
package myOtherStream; import java.util.Properties; import java.util.Set; //Properties特有方法 public class Demo10 { public static void main(String[] args) { //创建集合对象 Properties prop = new Properties(); prop.setProperty("01", "林青霞"); //接收String类型 ,put是Object类型 prop.setProperty("02", "张曼玉"); prop.setProperty("03", "王祖贤"); //根据键获取值 // System.out.println(prop.getProperty("01")); // System.out.println(prop.getProperty("04")); // System.out.println(prop); //获取键 Set<String> names = prop.stringPropertyNames(); for (String key : names) { //String类型,上个例子是Object类型 // System.out.println(key); String value = prop.getProperty(key); System.out.println(key + "," + value); } } }
Properties和IO流相结合的方法
package myOtherStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; //集合中的数据保存到文件 public class Demo11 { public static void main(String[] args) throws IOException { //把集合在中的数据保存到文件 myStore(); //把文件中的数据加载到集合 myLoad(); } private static void myLoad() throws IOException { Properties prop = new Properties(); //load加载 FileReader fr = new FileReader("D:\\itcast\\fw.txt"); prop.load(fr); fr.close(); System.out.println(prop); } private static void myStore() throws IOException { Properties prop = new Properties(); prop.setProperty("01", "林青霞"); prop.setProperty("02", "张曼玉"); prop.setProperty("03", "王祖贤"); FileWriter fw = new FileWriter("D:\\itcast\\fw.txt"); prop.store(fw, null); //null指的是描述信息 fw.close(); } }
案例:游戏次数
package myOtherStream; import java.util.Random; import java.util.Scanner; public class GuessNumber { private GuessNumber() { } public static void start() { Random r = new Random(); int number = r.nextInt(100) + 1; while (true) { Scanner sc = new Scanner(System.in); System.out.println("请输入你要猜的数字:"); int guessNumber = sc.nextInt(); //比较 if (guessNumber > number) { System.out.println("你猜的数字大了"); } else if (guessNumber < number) { System.out.println("你猜的数字小了"); } else { System.out.println("恭喜你猜对了!"); break; } } } }
package myOtherStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; public class Demo12 { public static void main(String[] args) throws IOException { Properties prop = new Properties(); FileReader fr = new FileReader("D:itcast\\fw.txt"); prop.load(fr); //文件fr数据加载到集合prop fr.close(); //通过Properties集合获取到玩游戏的次数 String count = prop.getProperty("count"); int number = Integer.parseInt(count); //判断是否到3次 if (number >= 3) { System.out.println("你的游戏次数已经用完!"); } else { GuessNumber.start(); number++; prop.setProperty("count", String.valueOf(number)); FileWriter fw = new FileWriter("D:\\itcast\\fw.txt"); prop.store(fw, null); fw.close(); } } }