自复制函数的实现
来源:互联网 发布:网络虚假信息 编辑:程序博客网 时间:2024/05/16 15:04
自复制函数是指,通过执行自身的代码,将代码自身打印出来或者是输出到一个文件中。这非常有意思,那么针对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
- 自复制函数的实现
- 字符串复制函数的实现
- 字符串的复制strcpy的使用以及自实现
- 写一个函数,实现字符串的复制
- 字符串复制函数strcpy的实现算法
- 字符串复制和比较函数的实现
- 用函数调用实现字符串的复制
- C++复制构造函数的实现
- 实现内存复制函数
- 自实现字符串函数
- 自实现strcpy函数
- strcpy()函数自实现
- strlen()函数自实现
- strcmp()函数自实现
- strstr()函数自实现
- atoi()函数自实现
- pow()函数自实现
- 自实现睡眠函数
- 关于layer弹出框出现layer is not underfined的问题
- eclipse修改黑色背景
- java中String对象是一个引用对象
- 如何屏蔽iframe中内容的右键菜单
- mac下安装与配置MySQL
- 自复制函数的实现
- JMeter--复杂的逻辑控制器
- SdutAcm-OJ平台 谁是最强的女汉子(java)
- Apache HTTP Server与Tomcat 的三种连接方式介绍
- Android Listview加载不同布局,ViewHolder类型转换异常!!!
- 【入门篇】Activiti流程资源文件下载保存到本地
- shell读取ini配置文件
- 致和闺蜜同撩一个男生的人
- 。。