๐ก ๋งค๋ฒ ๋ก๊น ์ฝ๋๋ฅผ ์์ฑํ๋ ๊ฒ์ ๋ถํธํ ์ ์์ต๋๋ค.
๊ทธ๋์ ๋ก๊ทธ๋ฅผ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉํ ์ ์๋๋ก ํด๋์ค๋ฅผ ์ค๊ณํ๊ณ , ์๊ตฌ์ ์ผ๋ก ๋ก๊ทธ๋ฅผ ์ ์ฅํ ์ ์๋ ํ์ผ ์ ์ฅ ๊ธฐ๋ฅ์ ํฌํจํ๋ ์ฝ๋๋ฅผ ์์ฑํด ๋ด ์๋ค.
ํ๋ก์ ํธ ์์ฑ
public class ConsoleLogger {
public void log(String message) {
System.out.println(message);
}
}// end of class
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileLogger {
private String fileName;
private SimpleDateFormat dateFormat;
public FileLogger(String fileName) {
this.fileName = fileName;
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
public void log(String message) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
// ํ์ฌ ์๊ฐ
String now = dateFormat.format(new Date());
writer.write(now + "::" + message);
writer.newLine();
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readLogs() {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MyLogger {
private static ConsoleLogger consoleLogger = new ConsoleLogger();
private static FileLogger fileLogger = new FileLogger("mLogger.txt");
// ์ฝ์์ฐฝ์ ๋ก๊ทธ ์ฐ๋ ๊ธฐ๋ฅ
public static void logToConsole(String message) {
consoleLogger.log(message);
}
// ์ฝ์์ฐฝ + ํ์ผ์ ์ ์ฅํ๋ ๊ธฐ๋ฅ
public static void logToFile(String message) {
logToConsole(message);
fileLogger.log(message);
}
}
public class MainTest {
public static void main(String[] args) {
MyLogger.logToConsole("์คํ 1");
System.out.println("-----------------------");
MyLogger.logToFile("์์ธ ํ์ธ null pointer");
System.out.println("-----------------------");
MyLogger.logToFile("์์ธ ํ์ธ ํ ๋ณํ ์ค๋ฅ ๋ฐ์");
}
}
์คํ ๊ฒฐ๊ณผ_______
------------------------------------------
โถ txt ํ์ผ ์์ฑ๋จ
โถ txt ํ์ผ ์ ๋ ฅ ํ์ธ
'JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] ๊ณ ์์ค ์คํธ๋ฆผ(Data/Object Stream) (0) | 2024.05.22 |
---|---|
[JAVA] ์ฌ์ฉ์๋ชจ๋์ ์ปค๋๋ชจ๋ (0) | 2024.05.22 |
[JAVA] ํ์ผ๋ณต์ฌ(๋ฌธ์๊ธฐ๋ฐ ์ /์ถ๋ ฅ), ZIPํ์ผ๋ก ์์ถ (0) | 2024.05.21 |
[JAVA] ๋์ ! - ํ์ ๊ฐ์ ์์ ๊ธฐ๋ก ๋ฐ ์กฐํ ์์คํ (0) | 2024.05.16 |
[JAVA] ๋์ ! - ์ํ ํ์ ๊ด๋ฆฌ ์์คํ (0) | 2024.05.16 |