工作小记

IO流小练习-System.in输入类名自动创建类

2020-05-28  本文已影响0人  叫子非鱼啊

练习要求:

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

实现效果

模板内容

public class @class@ {
    public @type@ @property@;
    public @class@() {
    }
    public void set@Uproperty@(@type@  @property@){
        this.@property@ = @property@;
    }
      
    public @type@  get@Uproperty@(){
        return this.@property@;
    }
}

java实现方法

思路:

package iotest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * 自动创建有一个属性的类文件。
 * 通过控制台,获取类名,属性名称,属性类型,根据一个模板文件,
 * 自动创建这个类文件,并且为属性提供setter和getter
 * @author lxh96
 *
 */
public class TestStream {
    public static String className;
    public static String propertyName;
    public static String propertyType;
    public static String propertyUpper;
    
    public static void main(String[] args) {
        
        // 通过System.in读取字符串  赋值给相应的字段
        Scanner s = new Scanner(System.in);
        System.out.println("请输入类名:");
        className = s.nextLine();
        System.out.println("请输入属性名称");
        propertyName = s.nextLine();
        System.out.println("请输入属性类型");
        propertyType = s.nextLine();
        // 将属性首字母大写,用作替换getter和setter方法名
        propertyUpper = propertyName.substring(0,1).toUpperCase()+propertyName.substring(1);
        
        
        File f = new File("E:\\temp\\template.txt"); // 模板文件对象
        File f2 = new File("E:\\temp\\"+className+".java"); // 生成文件路径对象
        
        
        try(
                BufferedReader br = new BufferedReader(new FileReader(f));
                BufferedWriter bw = new BufferedWriter(new FileWriter(f2));
        ){
            StringBuffer sb = new StringBuffer();
            while (true) {
                String line = br.readLine(); // 读取模板每行的数据
                if (line == null) {
                    break;
                }
                sb.append(replace(line)+"\n"); // 用console输入的关键词替换模板中的关键字 并拼接
            }
            System.out.println(sb);  
            bw.write(sb.toString());  // 输出到新的文件中
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

    /**
     * 替换模板中的关键字
     * @param line
     * @return
     */
    private static String replace(String line) {
        return line.replace("@class@", className).replace("@type@", propertyType)
                .replace("@property@", propertyName).replace("@Uproperty@", propertyUpper);
    }

}

上一篇 下一篇

猜你喜欢

热点阅读