java intermediate --IO2--

Exercise: Serialize Arrays

Prepare an array of length 10 and type Hero, and initialize the array with 10 Hero objects

Then serialize the array to a file heroes.lol

Then use ObjectInputStream to read the file and convert it to a Hero array to verify that the contents of the array are the same as before serialization

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 is commonly used to output data in the console.
System.in can input data from the console

Topic 2 - Automatic class creation

A class file with one property is automatically created.
Through the console, get the class name, property name, property type, automatically create the class file according to a template file, and provide setters and getters for properties

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;
         
    }
}

Combined training

Topic 1 - Copying files

It should be noted that read will return the actual number of reads. It is possible that the actual number of reads is less than the size of the buffer. When writing the data in the buffer to the target file, only part of the data should be written.

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");
         
    }
}

Topic 2 - Copying Folders

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");
    }
}

Topic 3--Finding file contents

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");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253641&siteId=291194637