LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Interesting Java question (https://www.linuxquestions.org/questions/programming-9/interesting-java-question-201785/)

deveraux83 07-06-2004 12:47 PM

Interesting Java question
 
A friend of mine who's a compsci recently presented to me a past question on Java which I thought was really interesting. I don't do java but I do C++ and since the two are closely related I tried to have a bash at it but failed. Neways, thought u guys might like to give it a shot (only if u're interested) and if u do pls post ur thoughts as I would be very interested to hear them.

Question: Write a Java code that when compiled into a program and executed will display the same output as running cat %source file%

Komakino 07-06-2004 01:39 PM

Code:

import java.io.*;

class myReader{
  public static void main(String args[]){
    if(args.length < 1){
        System.out.println("Usage: java myReader <filename>");
        System.exit(0);
    }
    try{
    BufferedReader br = new BufferedReader(
        new InputStreamReader(new FileInputStream(args[0])));
    String tmp = br.readLine();
    while(tmp!=null){
          System.out.println(tmp);
          tmp = br.readLine();
    }
    }catch(FileNotFoundException fnfe){

    }catch(IOException ioe){

    }
  }
}

Is that what you want?

Save it as myReader.java, compile and then run with:
java myReader <filename>
which prints out the file as does:
cat <filename>

deveraux83 07-06-2004 01:45 PM

Ok errmm, sorry, I forgot to mention, you can't use File I/O ..sorry, silly me.

Komakino 07-06-2004 01:48 PM

Ahhhh yes, well that changes things slightly!

moeminhtun 07-07-2004 02:10 AM

Man! seems like you have to write your own Java decompiler.

Jose Muņiz 07-07-2004 11:28 PM

Well LMAO at least it doesn't use IO eh? :P

Code:

class Cat
{
    public static void main(String args[])
    {
      if(args.length < 1)
      {
          System.out.println("Usage: java Cat <filename>");
          System.exit(0);
        }
        Runtime.getRuntime().exec("cat " + args[0])
    }
}


csfalcon 07-08-2004 01:06 PM

that's the classic "self reproducing" program, I have seen the code of such a program in an old language. The most common application of this kind of programs is virus that reproduces itself.


All times are GMT -5. The time now is 10:52 PM.