自复制函数的实现

自复制函数是指,通过执行自身的代码,将代码自身打印出来或者是输出到一个文件中。这非常有意思,那么针对java,可以分两种情况来处理,一种是将自身输出,输出非常巧妙,通过构造一个string数组,将代码自身放置到这个string数组中,然后通过填充某些空白行来实现输出。

public class test
{
    public static void main(String[] args)
    {
        char q = 34;      // Quotation mark character
        String[] l = {    // Array of source code
                "public class test",
                "{",
                "  public static void main(String[] args)",
                "  {",
                "    char q = 34;      // Quotation mark character",
                "    String[] l = {    // Array of source code",
                "    ",
                "    };",
                "    for(int i = 0; i < 6; i++)           // Print opening code",
                "        System.out.println(l[i]);",
                "    for(int i = 0; i < l.length; i++)    // Print string array",
                "        System.out.println(l[6] + q + l[i] + q + ',');",
                "    for(int i = 7; i < l.length; i++)    // Print this code",
                "        System.out.println(l[i]);",
                "  }",
                "}",
        };
        for(int i = 0; i < 6; i++)           // Print opening code
            System.out.println(l[i]);
        for(int i = 0; i < l.length; i++)    // Print string array
            System.out.println(l[6] + q + l[i] + q + ',');
        for(int i = 7; i < l.length; i++)    // Print this code
            System.out.println(l[i]);
    }
}
上述代码很巧妙,直接输出就行了,如果想直接输出代码自身,上述方法可以参考。

如果是要将代码自身输出到文件,那么通过对文件进行处理即可。

public class T
{
    public static void main(String[] args) throws IOException
    {
        String s = "大家好";
        File file=new File("/Users/sunwangdong/desktop/out.txt");
        file.createNewFile();   #输入文件为本代码所保存的代码
        InputStreamReader r=new InputStreamReader(new FileInputStream("/Users/sunwangdong/desktop/Algorithm/src/com/print/T.java"), Charset.forName("utf-8"));
        OutputStreamWriter w=new OutputStreamWriter(new FileOutputStream(file), Charset.forName("utf-8"));   #注意,这里用utf-8支持中文输入
        int c;
        while ((c=r.read())!=-1)    #一行一行读取文件即可,然后将其输出到需要保存的文件中
        { 
            w.write(c);
            w.flush();
        }
        w.close();
        r.close();
    }
}
其实这也非常巧妙,用inputstreamreader和outputstreamwriter就可以完成上述操作。

此题可以好好琢磨,会收到意想不到的效果。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值