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?