1

I am currently learning to develop in Java and am interested in creating Java classes that other users can import into their program and use. Yes, I know my example class is simple and stupid but I want to learn the concept and start making more complex classes that people can import into their projects.

I created a simple "Logger" class that when called logs both text to the console and to a text file for readability. You can call this class by using the following commands...

Logger Logger = new Logger();
Logger.create();
Logger.log("This text will be logged to the console and log.log");

See below for the Logger class.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Logger {
        FileWriter fw;
        BufferedWriter br;
        File file = new File("log.log");
        boolean fileExists = file.exists();
        public void log(String message) {
            try {
                fw = new FileWriter(file, true);
                br = new BufferedWriter(fw);
                Calendar cal = Calendar.getInstance();

                int hour = cal.get(Calendar.HOUR_OF_DAY);
                if(hour > 12)
                    hour = hour - 12;

                int minute = cal.get(Calendar.MINUTE);
                int second = cal.get(Calendar.SECOND);
                int millis = cal.get(Calendar.MILLISECOND);

                int ampm = cal.get(Calendar.AM_PM); 
                String ampmString;
                if(ampm == 1)
                    ampmString = "PM";
                else
                    ampmString = "AM";

                String now = String.format("%02d:%02d:%02d.%03d %s", hour, minute, second, millis, ampmString);

                System.out.println(now + " - " + message);
                br.write(now + " - " + message);

                br.newLine();
                br.close();
            } catch (Exception err) {
                System.out.println("Error");
            }

        }
        public void create() {
            try {
                fw = new FileWriter(file, true);
                br = new BufferedWriter(fw);
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-YYYY");
                String dateString = sdf.format(new Date());
                if(file.length() != 0)
                    br.newLine();
                System.out.println("Log: " + file.getAbsolutePath());
                br.write("--------------------" + dateString + "--------------------");
                br.newLine();
                br.close();
            } catch (Exception err) {
                System.out.println("Error");
            }
        }
    }

The issue I am having is in order to use this class I have to add it to every single project I create and want to use this. Is there a way I can add an import like, mydomain.Logger.*; and be able to access this class and the methods it contains?

My question, What is the best way to allow anyone to import/use my Logger class in the simplest way? What steps do I need to take to allow them to do this?

Dev
  • 119
  • 1
  • 1
  • 11
  • 1
    Since you are new to Java, I would point out that there are couple of standard logging libraries that do what you have outlined here. It's great that you are writing code to learn, but be careful of reinventing the wheel. If you use log4j or slf4j, the odds are very high that you can get any other 3rd party libraries to write to error log files along side your code. – jalynn2 Jul 25 '13 at 17:05
  • @jalynn2 I understand that. I was just messing around with this idea and this was the simplest thing I could think off. Thanks for the suggestions. :) – Dev Jul 25 '13 at 17:09

4 Answers4

2

Compile your class into a JAR file, and then add that jar to the classpath of each project. This is the standard Java approach to reusing classes.

jalynn2
  • 6,397
  • 2
  • 16
  • 15
  • Is there no way I can do something like this? `import org.apache.commons.lang.StringEscapeUtils;` But using my domain like, `import com.mydomain.Logger;`? – Dev Jul 25 '13 at 16:59
  • 1
    Yes, you can `import com.mydomain.Logger;` and the compile will find it in the jar file. If you are using an IDE like Eclipse, add the jar file to the project dependencies. – jalynn2 Jul 25 '13 at 17:02
1

Each class has a package. You declare it on the top of your file. For your class this could be i.e. package com.mydomain;. (Your example does not declare a package so the default is assigned - think "none"). Packages correspond to actual folders e.g. you should place your Logger.java in the path com/mydomain/ in your file system to match a package declaration like the one above.

Now if you create a class in the same package you could use your Logger class by just declaring a variable like in your example. No imports necessary.

If you create the new class in a different package i.e. com.otherdomain (this means that it would actually be in a different folder in the file system) then you would have to use an import statement like this: import com.mydomain.Logger; or import com.mydomain.*; otherwise the compiler would show an error and wouldn't let you use your Logger class.

If you would like to let other people use your class you would probably ship your binary version (i.e. the compiled Logger.class) not the source. And you would probably put that file in a jar (this is a zipped file structure more or less).

If then I wanted to use your class I could just add that jar to the classapth of my project, so the compiler and the runtime system would know to search this file when looking for classes. I would be able then to write an import statement myself inside my class and I could use your logger.

I hope this clears things up

c.s.
  • 4,786
  • 18
  • 32
0

You will have to create a jar file, then people can import that into their projects.

0

The Scala language lets you import members of arbitrary objects, but Java will only let you import static members. You can try using static imports. However, you'd need to change your Logger class to have a static log method. Since you probably just want a single instance of your logger, I'd recommend using the singleton enum pattern:

// Using "enum" instead of "class"
public enum Logger {
    // Create singleton instance
    INSTANCE;

    // Create static log method for export
    public static void log(String message) {
      INSTANCE.log(message);
    }

    // The rest of your class is unchanged
    FileWriter fw;
    BufferedWriter br;
    File file = new File("log.log");
    boolean fileExists = file.exists();
    public void log(String message) {
      // ...
    }
    public void create() {
      // ...
    }
}

Now in each file you want to use it you can just do import static mydomain.Logger.log; to get direct access to the log method!

Community
  • 1
  • 1
DaoWen
  • 32,589
  • 6
  • 74
  • 101