Can a program output a copy of itself

前端 未结 11 1151
萌比男神i
萌比男神i 2020-12-29 23:07

I think this might be a classic question but I am not aware of an answer. Can a program output a copy of itself, and, if so, is there a short program that does this?

11条回答
  •  清歌不尽
    2020-12-29 23:43

    It is possible in Java, but with some constraints.

    I have written a simple code in java which prints itself. You can use literals of C/C++ to use the same program. You can add anything you want inside this program, it will print itself completely.

    Conditions

    1. Java file should not be inside any package

    2. Folder structure should not contain any folders with spaces in its name

    3. Compilation target should be default or same folder where java file resides

      import java.io.FileInputStream;
      import java.net.URL;
      
      
      public class PrintYourself {
      
          public static void main(String[] args) {
              // TODO Auto-generated method stub
              URL location = PrintYourself.class.getProtectionDomain().getCodeSource().getLocation();
              String path=location.getFile();
              path=path.replace("/bin", "/src");
              System.out.println(path);
      
              try{
                  FileInputStream st=new FileInputStream(path+"PrintYourself.java");
                  int i=0;
                  while((i=st.read())!=-1){
                      System.out.print((char)i);
                  }
                  st.close();
              }
              catch(Exception e){
                  System.out.println(e);
              }
      
          }
      }
      

提交回复
热议问题