自复制函数是指,通过执行自身的代码,将代码自身打印出来或者是输出到一个文件中。这非常有意思,那么针对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就可以完成上述操作。
此题可以好好琢磨,会收到意想不到的效果。