한여름밤의코딩 2015. 11. 5. 17:48
package AddressBook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

public class AddressFile {

	public static void FileSave(List<Address> list) throws Exception 
	{
		OutputStream os = new FileOutputStream("C:/Addrinfo.txt");
		for(int i=0;i<list.size();i++) {
			Address addr = list.get(i);
			byte[] data = new byte[32];
			byte[] data1 = addr.name.getBytes();
			byte[] data2 = addr.telephone.getBytes();
			System.arraycopy(data1,0,data, 0, data1.length);
			os.write(data,0,32);
			System.arraycopy(data2,0,data, 0, data2.length);
			os.write(data,0,32);
		}
		os.flush();
		os.close();
	}
	public static void FileLoad(List<Address> list) throws Exception 
	{
		InputStream is = new FileInputStream("C:/Addrinfo.txt");
		String name , telephone;
		int readByte;
		byte[] data1 = new byte[32];
		byte[] data2 = new byte[32];
		while(true) {
			readByte = is.read(data1);
			if(readByte == -1) break;
			name = new String(data1, 0, readByte);
			readByte = is.read(data2);
			if(readByte == -1) break;
			telephone = new String(data2, 0, readByte);			
			Address addr = new Address(name.trim(),telephone.trim());
			list.add(addr);
		}
		is.close();
	}
	
	public static void main(String[] args)  throws Exception {
		List<Address> list = new ArrayList<Address>();
		Scanner scanner = new Scanner(System.in); // 키보드 입력기 생성
		String	name,telephone;
		int		n;
		
		while(true) {
			System.out.print("[0]종료 [1]추가 [2]리스트출력 [3]삭제 [4]저장 [5]불러오기 = ");
			try {
				n= scanner.nextInt(); // 수를 입력받는다.
			} 
			catch(InputMismatchException e) { // 키 입력을 정수로 변환하지 못하는 예외 처리 
				System.out.println("정수만 입력하셔야 합니다!!");
				scanner.nextLine(); // 나머지 모든 키를 읽어서 버린다.
				continue; // 다시 시도한다.
			}
			scanner.nextLine();	//  버퍼초기화
			if (n==0) return;
			if (n==1) {
				System.out.print("  이름 =  ");
				name = scanner.nextLine();
				System.out.print("  전화전호 =  ");
				telephone = scanner.nextLine();
				Address addinfo = new Address(name,telephone);
				list.add(addinfo);
			}
			if (n==2) {
				for(int i=0;i<list.size();i++) {
					Address addr = list.get(i);
					System.out.printf("이름 = %s , 전화전호 = %s\n",
							addr.name , addr.telephone );
				}			
			}
			if (n==4) {
				FileSave(list);
			}
			if (n==5) {
				FileLoad(list);
			}
		}
	}
}


============================
package AddressBook;

public class Address {
	String		name;
	String		telephone;
	public Address(String name,String telephone) {
		this.name = name;
		this.telephone = telephone;
	}
}