자바
자바 텍스트 파일저장/로드 기본코드
by 가오가이거
2020. 12. 15.
package day10;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
/**
*
* 나열된 메소드를 적절히 구현 하세요.
* 적절한 예외처리를 해주세요.
*/
public class PhoneMgr {
/**
*
* @param count
* @param fileName
*
* //count 만큼 전화번호를 입력받는 기능을 작성하세요.. (IO 이용해서...)
//이름, 전화번호를 입력받아서
//입력받은 파일으름으로
// ex) 홍길동 : 010-222-2222
//파일에 저장!!
*/
public static void inputPhone(int count, String fileName) {
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(fileName, true))) {
for(int i = 0; i <count; i++) {
System.out.println("이름을 입력하세요. ");
String name = br.readLine();
System.out.println("전화번호를 입력하세요. ");
String phoneNumber = br.readLine();
pw.println(name +":"+phoneNumber);
}
}catch (Exception e) {
e.printStackTrace();
}
}
//매개변수로 입력받은 파일명에 해당하는 파일을 읽어서 출력하세요.
public static void printPhoneList(String fileName) {
try(BufferedReader br = new BufferedReader(new FileReader(fileName))){
String line = null;
while((line = br.readLine())!= null)
System.out.println(line);
}catch (Exception e) {
e.printStackTrace();
}
}
//파일을 읽어서, 읽은 내용으로 Phone객체를 생성하고, Phone객체를 List에 담아서 반환 하세요.
public static List<Phone> getPhoneList(String fileName) {
List<Phone> phoneList = new ArrayList<Phone>();
try(BufferedReader br = new BufferedReader(new FileReader(fileName))){
String line = null;
while((line = br.readLine())!= null) {
//이름:전화번호 -이 값으로 Phone 객체를 생성하고, list에 담는 코드를 수행.
String[] info = line.split(":");
Phone phone = new Phone();
phone.setName(info[0]);
phone.setPhoneNumber(info[1]);
phoneList.add(phone);
}
}catch (Exception e) {
e.printStackTrace();
}
return phoneList;
}
public static void main(String[] args) {
String fileName = "phone.txt";
inputPhone(3,fileName);
printPhoneList(fileName);
List<Phone> phoneList = getPhoneList(fileName);
System.out.println(phoneList);
}
}
package day10;
public class Phone {
// 이름, 전화번호,
private String name;
private String phoneNumber;
public Phone() {}
public Phone(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "Phone [name=" + name + ", phoneNumber=" + phoneNumber + "]";
}
}