java

[java] java로 html 파일 생성하기(feat.자바의 환경 설정 정보 불러오기)

seulhasony 2023. 6. 6. 15:46

java로 파일을 생성해서 파일에 내용을 write하는 작업을 해보겠습니다.

파일 안의 내용은 설치된 자바의 환경의 정보를 가져와서 테이블로 키와 값을 가져와서 입력할게요!

 

하기의 사진처럼 html 파일이 생성되면 됩니다.

property.html

 

해당 html파일이 생성되기 위한 코드는 아래와 같습니다.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        //파일 생성
        File file = new File("property.html");
        try{
            String javaInfo = "";
            //자바 시스템 속성값 저장
            for(Object key : System.getProperties().keySet()){
                javaInfo += "<tr>"
                        +"<td>" +key.toString() +"</td>"
                        +"<td>" +System.getProperty((String)key).toString() +"</td>"
                        +"<tr>";
            }            
            String head = "<head>"
                                +"<meta charset = 'UTF-8'/>"
                                +"<style>"
                                    +"table{border-collapse: collapse; width: 100% }"
                                    +"th,td{border:solid 1px #000;}"
                                +"</style>"
                            +"<head>";
            String body = "<body>"
                                +"<h1>자바 환경정보</h1>"
                                +"<table>"
                                    +"<tr>"
                                        +"<th>키</th>"
                                        +"<th></th>"
                                    +"</tr>"
                                    +javaInfo
                                +"</table>"
                            +"</body>";

            //파일에 내용 입력
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(head+body);
            writer.close();

        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

 

사용된 메소드 및 클래스

메소드 설명
System.getProperty() JAVA 시스템의 정보와 현재 위치 정보등을 가져온다.
File File 클래스를 이용해서 생성자를 선언할 때 파일명을 입력하여 파일 및 디렉토리를 만들 수 있다. 이때, 파일명에 확장자로 html을 넣어 html파일을 생성할 수 있었다.
BufferWriter 버퍼를 사용해 입력하여 쓰는 함수이다.

<주요 메소드>
- write(): 메소드 안에 있는 내용 출력
- flush(): 남아있는 데이터 모두 출력
- close(): 버퍼를 사용했기 때문에 스트림을 닫아줘야 한다.