java中级--IO2--

笔记

最大区别:
File f = new File("d:/test");

System.out.println(f);
System.out.println(f.getName());

直接输出f 是打印全路径,和f.getAbsolutePath()效果一样。
如果输出f.getName() 则是输出全路径的最后一个子项,(文件或目录)

===================

习题:序列化数组

准备一个长度是10,类型是Hero的数组,使用10个Hero对象初始化该数组

然后把该数组序列化到一个文件heros.lol

接着使用ObjectInputStream 读取该文件,并转换为Hero数组,验证该数组中的内容,是否和序列化之前一样

package stream;
     
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
   
import charactor.Hero;
     
public class TestStream {
     
    public static void main(String[] args) {
        //创建Hero数组
        Hero hs[] =new Hero[10];
        for (int i = 0; i < hs.length; i++) {
            hs[i] = new Hero("hero:" +i);
        }
        File f =new File("d:/heros.lol");
  
        try(
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos =new ObjectOutputStream(fos);
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois =new ObjectInputStream(fis);
        ) {
            //把数组序列化到文件heros.lol
            oos.writeObject(hs);
            Hero[] hs2 = (Hero[]) ois.readObject();
            System.out.println("查看中文件中反序列化出来的数组中的每一个元素:");
            for (Hero hero : hs2) {
                System.out.println(hero.name);
            }
                
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
             
    }
}

System.out 是常用的在控制台输出数据的
System.in 可以从控制台输入数据

题目2-自动创建类

自动创建有一个属性的类文件。
通过控制台,获取类名,属性名称,属性类型,根据一个模板文件,自动创建这个类文件,并且为属性提供setter和getter

package stream;
 
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
 
public class TestStream {
 
    public static void main(String[] args) {
        // 接受客户输入
        Scanner s = new Scanner(System.in);
        System.out.println("请输入类的名称:");
        String className = s.nextLine();
        System.out.println("请输入属性的类型:");
        String type = s.nextLine();
        System.out.println("请输入属性的名称:");
        String property = s.nextLine();
        String Uproperty = toUpperFirstLetter(property);
         
        // 读取模版文件
        File modelFile = new File("E:\\project\\j2se\\src\\Model.txt");
        String modelContent = null;
        try (FileReader fr = new FileReader(modelFile)) {
            char cs[] = new char[(int) modelFile.length()];
            fr.read(cs);
            modelContent = new String(cs);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }      
         
        //替换
         
        String fileContent = modelContent.replaceAll("@class@", className);
        fileContent = fileContent.replaceAll("@type@", type);
        fileContent = fileContent.replaceAll("@property@", property);
        fileContent = fileContent.replaceAll("@Uproperty@", Uproperty);
        String fileName = className+".java";
         
        //替换后的内容
        System.out.println("替换后的内容:");
        System.out.println(fileContent);
        File file = new File("E:\\project\\j2se\\src",fileName);
 
        try(FileWriter fw =new FileWriter(file);){
            fw.write(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        System.out.println("文件保存在:" + file.getAbsolutePath());
    }
     
    public static String toUpperFirstLetter(String str){
        char upperCaseFirst =Character.toUpperCase(str.charAt(0));
        String rest = str.substring(1);
        return upperCaseFirst + rest;
         
    }
}

综合练习

题目1-复制文件

需要留意的是,read会返回实际的读取数量,有可能实际的读取数量小于缓冲的大小,那么把缓冲中的数据写出到目标文件的时候,就只应该写出部分数据。

package stream;
  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
     
public class TestStream {
    /**
     *
     * @param srcPath 源文件
     * @param destPath 目标文件
     */
    public static void copyFile(String srcPath, String destPath){
          
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
          
        //缓存区,一次性读取1024字节
        byte[] buffer = new byte[1024];
  
        try (
                FileInputStream fis = new FileInputStream(srcFile);
                FileOutputStream fos = new FileOutputStream(destFile);             
        ){
            while(true){
                //实际读取的长度是 actuallyReaded,有可能小于1024
                int actuallyReaded = fis.read(buffer);
                //-1表示没有可读的内容了
                if(-1==actuallyReaded)
                    break;
                fos.write(buffer, 0, actuallyReaded);
                fos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
          
    }
      
    /**
     *
     * @param srcPath 源文件夹
     * @param destPath 目标文件夹
     */
    public static void copyFolder(String srcPath, String destPath){
          
    }
      
    public static void main(String[] args) {
          
        copyFile("d:/lol.txt", "d:/lol2.txt");
         
    }
}

题目2-复制文件夹

package stream;
  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
     
public class TestStream {
     
    /**
     *
     * @param srcPath 源文件
     * @param destPath 目标文件
     */
    public static void copyFile(String srcPath, String destPath){
          
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
          
        //缓存区,一次性读取1024字节
        byte[] buffer = new byte[1024];
  
        try (
                FileInputStream fis = new FileInputStream(srcFile);
                FileOutputStream fos = new FileOutputStream(destFile);
        ){
            while(true){
                //实际读取的长度是 actuallyReaded,有可能小于1024
                int actuallyReaded = fis.read(buffer);
                //-1表示没有可读的内容了
                if(-1==actuallyReaded)
                    break;
                fos.write(buffer, 0, actuallyReaded);
                fos.flush();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          
    }
      
    /**
     *
     * @param srcPath 源文件夹
     * @param destPath 目标文件夹
     */
    public static void copyFolder(String srcPath, String destPath){
          
        File srcFolder = new File(srcPath);
        File destFolder = new File(destPath);
        //源文件夹不存在
        if(!srcFolder.exists())
            return;
        //源文件夹不是一个文件夹
        if(!srcFolder.isDirectory())
            return;
        //目标文件夹是一个文件
        if(destFolder.isFile())
            return;
        //目标文件夹不存在
        if(!destFolder.exists())
            destFolder.mkdirs();
 
        //遍历源文件夹
        File[] files=  srcFolder.listFiles();
        for (File srcFile : files) {
            //如果是文件,就复制
            if(srcFile.isFile()){
                File newDestFile = new File(destFolder,srcFile.getName());
                copyFile(srcFile.getAbsolutePath(), newDestFile.getAbsolutePath());
            }
            //如果是文件夹,就递归
            if(srcFile.isDirectory()){
                File newDestFolder = new File(destFolder,srcFile.getName());
                copyFolder(srcFile.getAbsolutePath(),newDestFolder.getAbsolutePath());
            }
        }
    }
    public static void main(String[] args) {
        copyFolder("d:/LOLFolder", "d:/LOLFolder2");
    }
}

题目3--查找文件内容

package stream;
 
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
public class TestStream {
 
    /**
     * @param file 查找的目录
     * @param search 查找的字符串
     */
    public static void search(File file, String search) {
        if (file.isFile()) {
            if(file.getName().toLowerCase().endsWith(".java")){
                String fileContent = readFileConent(file);
                if(fileContent.contains(search)){
                    System.out.printf("找到子目标字符串%s,在文件:%s%n",search,file);
                }
            }
        }
        if (file.isDirectory()) {
            File[] fs = file.listFiles();
            for (File f : fs) {
                search(f, search);
            }
        }
    }
     
    public static String readFileConent(File file){
        try (FileReader fr = new FileReader(file)) {
            char[] all = new char[(int) file.length()];
            fr.read(all);
            return new String(all);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
 
    }
 
    public static void main(String[] args) {
        File folder =new File("e:\\project");
        search(folder,"Magic");
    }
}

posted @ 2018-05-04 13:30  Pororo  阅读(266)  评论(0编辑  收藏  举报