kh17일차 InputOutput(WordContorller)

2022. 7. 12. 18:09코딩/Java

ByteStreamTest

package kh.java.func;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class ByteStreamTest {
	Scanner sc;

	public ByteStreamTest() {
		super();
		sc = new Scanner(System.in);
		// TODO Auto-generated constructor stub
	}

	public void PrimaryStream() {
		// 1.스트림생성 -> 2.메소드를 통한 입/출력 ->3.자원반환
		System.out.print("저장할 파일명 입력 : ");
		String filename = sc.nextLine();

		FileOutputStream fos = null;//스트림으로 끝나면 1byte단위로 왔다갔다하는것

		try {
			// 입력받은 파일명으로 파일생성
			// 생성된 파일과 프로그램이 stream연결
			fos = new FileOutputStream("C:\\Users\\user1\\Desktop\\" + filename);// 저장 경로 변환
			System.out.println("[" + filename + "]");// 파일에 저장될 내용 입력
			System.out.println("종료는 exit를 입력하세요.");
			while (true) {
				System.out.print("내용입력 : ");
				String str = sc.nextLine()+"\r\n";// \r\n =>엔터기능
				if(str.equals("exit\r\n")) {
					break;
				}
				byte[] arr = str.getBytes();// 문자열을 바이트 배열로 변환(쪼갠다)
				// write메소드의 매개변수가 byte[]타입이기때문에
				fos.write(arr);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {//자원반환
			try {
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

CharStreamTest

package kh.java.func;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CharStreamTest {
	private Scanner sc;

	public CharStreamTest() {
		super();
		sc = new Scanner(System.in);
	}

	public void primarStream() {
		System.out.print("저장할 파일명 입력 : ");
		String filename = sc.nextLine();
		FileWriter fw = null;// 파일 기준으로 나가는것,write으로 끝나면 2byte단위로 왔다갔다하는것
		//close를 시킬수있게 범위를 크게잡기위해 try문 위에다 사용
		try {
			// 1.파일이 생성되고 스트림이 연결
			fw = new FileWriter("C:\\Users\\user1\\Desktop\\" + filename);
			System.out.println("[" + filename + "] 파일에 저장");
			System.out.println("종료는 exit");
			while (true) {
				System.out.print("입력 : ");
				String str = sc.nextLine() + "\r\n";
				if (str.equals("exit\r\n")) {
					break;
				}
				// 문자스트림은 1문자단위로 전송하기 때문에 바이트배열로 전환x
				fw.write(str);// 2.메소드를통한 출력
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				// 3.자원반환
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void subStream() {
		System.out.print("저장할 파일명 입력");
		String filename = sc.nextLine();
		BufferedWriter bw = null; // 보조스트림

		try {
			// 주스트림 생성
			FileWriter fw = new FileWriter(filename);
			// 주스트림에 보조스트림을 추가하는 기능
			bw = new BufferedWriter(fw);
			System.out.println("[" + filename + "]에 저장할 내용입력");
			System.out.println("종료는 exit");
			while (true) {
				System.out.print("입력 :");
				String str = sc.nextLine();// 엔터 안쓰는이유 버퍼에서 자동 지원해주는 기능이있음
				if (str.equals("exit")) {
					break;
				}
				bw.write(str);// 보조스트림을 통한 테이터 전송
				bw.newLine();// 보조스트림에 존재하는 줄개행 기능(엔터)
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				// 보조스트림 반환시 주스트림은 자동으로 반환
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void charStreamReader() {
		// 1.스트림생성 ->2.메소드를 통한 입력 ->3.자원반환
		System.out.print("로드할 파일명 입력 : ");
		String filename = sc.nextLine();
		// 데이터를 읽어올 보조스트림
		BufferedReader br = null;

		// 파일 읽어올 주스트림
		try {
			FileReader fr = new FileReader(filename);
			br = new BufferedReader(fr);// 보조스트림을 만들때 주스트림을 넣는다
			while (true) {
				// 스트림에서 연결된파일에서 1줄 읽어옴
				// 더이상 읽어올 내용이 없는경우 null 리턴
				String str = br.readLine();// 2.메소드를통한 입력
				if (str == null) {
					break;
				}
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {// 자원반환
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

FileTest

package kh.java.func;

import java.io.File;
import java.util.Scanner;

public class FileTest {
	public void test() {
		Scanner sc = new Scanner(System.in);
		System.out.println("파일명 입력 : ");
		String filename = sc.nextLine();
		File file = new File(filename);
		if (file.exists()) {// 파일이 경로에있는지확인
			// 절대경로 -> 내컴퓨터부터 찾아가는 경로
			// 상대경로 -> 현재위치기준으로 찾아가는 경로
			System.out.println("파일이름 : " + file.getName());
			System.out.println("파일 절대 경로 :" + file.getAbsolutePath());
			System.out.println("파일 크기 : " + file.length() + "Byte");
			System.out.println("해당파일을 삭제하시겠습니까(1.yes/2.no)?");
			int sel = sc.nextInt();
			if (sel == 1) {
				boolean bool = file.delete();// 해당파일을 삭제하고 그결과 리턴
				System.out.println(bool);
			}
		} else {
			System.out.println("파일을 찾을 수 없습니다.");
		}
	}
}

StreamTest

package kh.java.func;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class StreamTest {
	public void test1() {
		// quiz.txt파일의 내용을 읽어올예정
		BufferedReader br = null;
		// 이미지로내보낼 보조스트림
		BufferedOutputStream bos = null;

		// quiz.txt를 읽어오기 위한 주 스트림 생성
		FileReader fr;
		try {
			fr = new FileReader("quiz.txt");
			// 보조스트림을 통한 개선
			br = new BufferedReader(fr);
			// quiz.txt는 1줄짜리 파일로 한번만 읽으면 모든정보 로드 완료
			String str = br.readLine();// 보조스트림기능 - 한줄씩 읽는다.
			// ""띄어쓰기 기준으로 데이터를 잘라서 토큰으로 관리
			StringTokenizer sT = new StringTokenizer(str, " ");
			// 데이터 내보낼때 byte스트림을 사용할 예정
			// 읽어온 숫자를 byte list 에 저장
			ArrayList<Byte> list = new ArrayList<Byte>();// 바이트로 변환한다음ArrayList<Byte> list 에 저장
			while (sT.hasMoreTokens()) {// hasMoreTokens는 sT에 데이터가 남아있는지 아닌지 확인
				String num = sT.nextToken();// nextToken: sT에 있는 데이터를 하나씩 가져오는것
				int iNum = Integer.parseInt(num);// int형으로 변환
				list.add((byte) iNum);// byte형으로 변환

			} // 이 while문이 끝나면 파일을 다 읽어온것

			System.out.println("파일 읽어오기 완료");
			System.out.println("리스트 길이 : " + list.size());
			// 이미지 파일을 내보내기 위한 주스트림 생성
			FileOutputStream fos = new FileOutputStream("test.gif");
			// 성능개선을 위한 보조스트림 생성
			bos = new BufferedOutputStream(fos);
			for (Byte b : list) {
				bos.write(b);
			}
			System.out.println("내보내기 종료");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

WordController

package ka.java.word.controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import ka.java.word.view.WordView;

public class WordController {
	private ArrayList<String> words;
	private WordView view;
	private Random r;
	private int win;
	private int lose;

	public WordController() {
		super();
		words = new ArrayList<String>();
		getWordFile();
		view = new WordView();
		r = new Random();
		// System.out.println(words);

	}

	public void main() {
		while (true) {
			int sel = view.showMenu();
			switch (sel) {
			case 1:
				startGame();
				break;
			case 2:
				break;
			case 0:
				return;

			}
		}
	}

	public void startGame() {
		// 1.words리스트에서 랜덤단어1개추출
		int random = r.nextInt(words.size());
		String word = words.get(random);
		view.startGame();
		view.comTurn(word);
		while (true) {
			char lastLetter = word.charAt(word.length() - 1);// 글자수-1을 해야 마지막자리
			String userWord = view.userTrun(lastLetter);
			int userResult = checkWord(userWord, lastLetter);
			if (userResult == -1) {
				return;
			} else if (userResult == 1) {
				continue;// while문 내의 맨위로
			}
			char userLastLetter = userWord.charAt(userWord.length() - 1);
			word = comTurn(userLastLetter);
			if(word == null) {
				win++;
				view.winMsg();
				return;//메소드종료
			}else {
				view.comTurn(word);
			}
		}
	}

	private String comTurn(char lastLetter) {
		// TODO Auto-generated method stub
		// 1. 문자열을 저장할 ArrayList 생성
		ArrayList<String> list = new ArrayList<String>();// 1.

		for (String word : words) {
			// 2. words중에 사용자가 입력한 마지막글로 시작하는 단어를 생성한 리스트에 add
			char firstLetter = word.charAt(0);
			if (firstLetter == lastLetter) {
				list.add(word);
			}
		}

		// 만약 마지막글자로 시작하는 단어가 한개도 없으면 -> return null;
		if (list.isEmpty()) {
			return null;
		} else {
			// 단어가 있으면 단어중 랜덤단어 1개 리턴
			int random = r.nextInt(words.size());
			String word = words.get(random);
			return word;
		}
	}

	public int checkWord(String userWord, char lastLetter) {
		// 1.gg입력한 경우->return -1
		// 2.정상인 경우 ->이전단어 끝글자와 입력단어 첫글자가 일치
		// ->입력한 단어가 words에 존재하는경우
		// ->위 두가지 조건을만족하는 경우 return 0
		// 3.비정상인경우
		// 3-1. 이전단어 끝글자와, 입력단어 첫글자가 다른경우
		// 3-2.이전단어 끝글자와 입력단어 첫글자는 같은데
		// 입력단어가 words에존재하지않는경우

		if (userWord.equals("gg")) {
			view.loseMsg();
			lose++;
			return -1;
		}
		char firstLetter = userWord.charAt(0);
		if (firstLetter == lastLetter) {
			if (words.contains(userWord)) {// 유저단어와 words에 있는 단어비교
				// if(words.indexof(userWord) != -1)이것도 위의 조건문과 같다.
				return 0;
			} else {
				// 3-2.이전단어 끝글자와 입력단어 첫글자는 같은데
				view.noSearchWord();
				return 1;
			}
		} else {
			// 3-1. 이전단어 끝글자와, 입력단어 첫글자가 다른경우
			view.wrongMsg();
			return 1;
		}
	}

	public void getWordFile() {
		BufferedReader br = null; // 보조스트림
		try {
			FileReader fr = new FileReader("words.txt");
			br = new BufferedReader(fr);
			while (true) {
				String word = br.readLine();
				if (word == null) {
					break;
				}
				words.add(word);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

WordView

package ka.java.word.view;

import java.util.Scanner;

public class WordView {
	private Scanner sc;

	public WordView() {
		super();
		sc = new Scanner(System.in);
	}

	public int showMenu() {
		System.out.println("=====끝말잇기=====");
		System.out.println("1. 게임시작");
		System.out.println("2. 전적보기");
		System.out.println("0. 프로그램종료");
		System.out.print("선택 > ");
		int sel = sc.nextInt();
		return sel;
	}

	public void startGame() {
		// TODO Auto-generated method stub
		System.out.println("=====게임시작=====");
	}

	public void comTurn(String word) {
		// TODO Auto-generated method stub
		System.out.println("컴퓨터 : " + word);
	}

	public String userTrun(char lastLetter) {
		System.out.println("[" + lastLetter + "] 로 시작하는 단어를 입력하세요 : ");
		System.out.println("포기하는 경우 gg 입력");
		System.out.print("단어 입력 :");
		String word = sc.next();
		return word;
	}

	public void loseMsg() {
		// TODO Auto-generated method stub
		System.out.println("패배");
	}

	public void noSearchWord() {
		// TODO Auto-generated method stub
		System.out.println("단어를 찾을 수 없습니다.");
	}

	public void wrongMsg() {
		// TODO Auto-generated method stub
		System.out.println("잘못입력하셨습니다.");
	}

	public void winMsg() {
		// TODO Auto-generated method stub
		System.out.println("승리");
	}

}

User

package kh.java.func;

import java.io.Serializable;

public class User implements Serializable{//Serializable사용시 오버라이드 안해도됨
											//Serializable가 직렬화 시키겠다는의미 없으면 내보내기 불가
											//
	private String id;
	private transient String pw;
	private String name;
	private int age;

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(String id, String pw, String name, int age) {
		super();
		this.id = id;
		this.pw = pw;
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

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

	public String getPw() {
		return pw;
	}

	public void setPw(String pw) {
		this.pw = pw;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

UserMgr

package kh.java.func;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;

public class UserMgr {
	public void test1() {
		Scanner sc = new Scanner(System.in);
		System.out.print("아이디 입력 : ");
		String id = sc.next();
		System.out.print("비밀번호 입력 : ");
		String pw = sc.next();
		System.out.print("이름 입력 : ");
		String name = sc.next();
		System.out.print("나이 입력 : ");
		int age = sc.nextInt();

		User u = new User(id, pw, name, age);

		// 객체내보내기 (프로그램 백업하는것도 이런것)
		// 객체를 내보내기위한 보조스트림
		ObjectOutputStream oos = null;// 보조이기에 단독으로 사용 불가

		try {
			FileOutputStream fis = new FileOutputStream("object.txt");
			oos = new ObjectOutputStream(fis);

			// 객체 내보내는 코드
			oos.writeObject(u);
			System.out.println("객체 내보내기 완료");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void test2() {
		// 직렬화를 통해 내보낸 데이터를 불러오기
		// 보조스트림생성
		ObjectInputStream ois = null;
		try {
			FileInputStream fis = new FileInputStream("object.txt");
			ois = new ObjectInputStream(fis);

			User u = (User) ois.readObject();
			System.out.println(u.getId());
			System.out.println(u.getPw());
			System.out.println(u.getName());
			System.out.println(u.getAge());

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

Student

package kh.java.func;

import java.io.Serializable;

public class Student implements Serializable{
	
	private String name;
	private int age;
	private String addr;

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Student(String name, int age, String addr) {
		super();
		this.name = name;
		this.age = age;
		this.addr = addr;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

}

StudentMgr

package kh.java.func;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;

public class StudentMgr {
	private ArrayList<Student> students;
	private Scanner sc;

	public StudentMgr() {
		super();
		students = new ArrayList<Student>();
		sc = new Scanner(System.in);
		importStudent();
	}

	public void main() {
		while (true) {
			System.out.println("1. 학생정보등록");
			System.out.println("2. 전체조회");
			System.out.println("3. 정보내보내기");
			System.out.println("4. 정보불러오기");
			System.out.println("0. 프로그램종료");
			System.out.println("선택 > ");
			int sel = sc.nextInt();
			switch (sel) {
			case 1:
				insertStudent();
				break;
			case 2:
				printAllStudent();
				break;
			case 3:
				// students를 직렬화 해서 내보내기
				// 파일 이름은 students.txt
				outputStudent();
				break;
			case 4:
				importStudent();
				break;
			case 0:
				return;
			}
		}
	}

	public void insertStudent() {
		System.out.println("=====학생 정보 등록=====");
		System.out.print("이름 입력 : ");
		String name = sc.next();

		System.out.print("나이 입력 : ");
		int age = sc.nextInt();

		System.out.print("주소 입력 : ");
		sc.nextLine();
		String addr = sc.nextLine();

		Student s = new Student(name, age, addr);
		students.add(s);
	}

	public void printAllStudent() {
		System.out.println("\n=====전체 학생 정보 출력=====\n");
		System.out.println("이름\t나이\t주소");
		System.out.println("============================");
		for (Student s : students) {
			System.out.println(s.getName() + "\t" + s.getAge() + "\t" + s.getAddr());
		}

	}

	public void outputStudent() {

		ObjectOutputStream oos = null;

		try {
			FileOutputStream fis = new FileOutputStream("students.txt");
			oos = new ObjectOutputStream(fis);

			oos.writeObject(students);
			System.out.println("정보 내보내기 완료");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void importStudent() {
		ObjectInputStream ois = null;

		try {
			FileInputStream fis = new FileInputStream("students.txt");
			ois = new ObjectInputStream(fis);
			students = (ArrayList<Student>) ois.readObject();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				ois.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}