섭섭한 개발일지

[TIL] 자바 txt 저장과 불러오기 본문

카테고리 없음

[TIL] 자바 txt 저장과 불러오기

Seop 2023. 10. 24. 17:19

명언 관리 앱을 제작하며 확인한 txt파일 저장과 불러오기

데이터베이스 없이 데이터 값을 보존해야할 경우 사용

 

[model]

public class WiseModel {
    int id;
    String content;
    String author;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

 

[save]

    public void save() {
        String saveFilePath = "{path}";

        try {
            // 파일 생성 및 텍스트 작성을 위한 버퍼드 객체 생성
            BufferedWriter writer = new BufferedWriter(new FileWriter(saveFilePath));

            // 반복문을 통해 wiseArr에 들어있는 데이터를 txt 파일에 순차적 작성
            for (WiseModel wiseModel : wiseArr) {
                String objectText =
                        String.format("%d,%s,%s", wiseModel.getId(), wiseModel.getAuthor(),
                                wiseModel.getContent());
                writer.write(objectText);
                writer.newLine();
            }

            // 버퍼드 객체 close
            // close 하지 않을 경우 txt가 작성되지 않는 문제 발생
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

 

[load]

    public void load() {
        String userHome = System.getProperty("user.home");
        String filePath = userHome + "/workspace/saveWiseData.txt";

        try {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            String line = "";

            // txt 내 텍스트 전체를 읽을때까지 반복문을 통해 데이터 로드하여 wiseArr에 데이터 저장
            while ((line = reader.readLine()) != null) {
                String[] len = line.split(",");

                if (len.length == 3) {
                    int loadPostNum = Integer.parseInt(len[0]);
                    String loadAuthor = len[1];
                    String loadSentence = len[2];

                    WiseModel wiseModel = new WiseModel();
                    wiseModel.setId(loadPostNum);
                    wiseModel.setAuthor(loadAuthor);
                    wiseModel.setContent(loadSentence);

                    wiseArr.add(wiseModel);
                }
            }

        } catch (IOException e) {
			
        }
    }
Comments