일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- orm
- JPA
- 멋쟁이사자처럼
- DOCS
- VB
- 테킷
- responsepart
- 부트캠프
- Git
- 반복문 탈출
- querydsl
- PDF병합
- 코딩테스트
- Hibernate
- spring jpa
- 값 타입
- 프로그래머스
- 알고리즘
- GitFlow
- 스프링부트 쇼핑몰 프로젝트
- break-label
- PDFBOX
- 제작기
- springboot
- 연관관계
- spring
- Java
- Visual Basic
- 체인호출
- 커밋 컨벤션
Archives
- Today
- Total
섭섭한 개발일지
[TIL] 자바 txt 저장과 불러오기 본문
명언 관리 앱을 제작하며 확인한 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) {
}
}