[Java] 8장 실습문제 (입출력 스트림과 파일 입출력)

[Java] 8장 실습문제 (입출력 스트림과 파일 입출력)

728x90

[8장 1번] Scanner로 입력받은 이름과 전화번호를 한 줄에 한 사람씩 c:\temp\phone.txt 파일에 저장하라. "그만을" 입력하면 프로그램을 종료한다

package Java8_1; import java.io.*; import java.util.*; public class Java8_1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); FileWriter fw = null; System.out.println("전화번호 입력 프로그램입니다."); try{ fw = new FileWriter("c:\\Temp\\phone.txt"); while(true){ System.out.print("이름 전화번호 >> "); String text = sc.nextLine(); if(text.equals("그만")) break; fw.write(text); fw.write("

"); } fw.close(); System.out.println("c:\\Temp\\phone.txt에 저장하였습니다."); } catch (IOException e) { e.printStackTrace(); } } } ----------------------------- 전화번호 입력 프로그램입니다. 이름 전화번호 >> 차범근 010-1111-2222 이름 전화번호 >> 손흥민 010-3333-4444 이름 전화번호 >> 이승우 010-5555-6666 이름 전화번호 >> 백승호 010-6666-7777 이름 전화번호 >> 그만 c:\Temp\phone.txt에 저장하였습니다.

[8장 2번] 앞서 저장한 c:\temp\phone.txt 파일을 읽어 화면에 출력하라

package Java8_2; import java.io.*; public class Java8_2 { public static void main(String[] args) throws IOException{ try{ File f = new File("c:\\Temp\\phone.txt"); BufferedReader br = new BufferedReader(new FileReader(f)); System.out.println(f.getPath() + "를 출력합니다."); String line; while((line = br.readLine()) != null) System.out.println(line); br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } --------------------------- c:\Temp\phone.txt를 출력합니다. 차범근 010-1111-2222 손흥민 010-3333-4444 이승우 010-5555-6666 백승호 010-6666-7777

[8장 3번] c:\windows\system.ini 파일을 읽어 소문자를 모두 대문자로 바꾸어 출력하라

package Java8_3; import java.io.*; public class Java8_3 { public static void main(String[] args) { try{ File f = new File("c:\\windows\\system.ini"); BufferedReader br = new BufferedReader(new FileReader(f)); String line; while((line = br.readLine()) != null) System.out.println(line.toUpperCase()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ------------------------------------ ; FOR 16-BIT APP SUPPORT [386ENH] WOAFONT=DOSAPP.FON EGA80WOA.FON=EGA80WOA.FON EGA40WOA.FON=EGA40WOA.FON CGA80WOA.FON=CGA80WOA.FON CGA40WOA.FON=CGA40WOA.FON [DRIVERS] WAVE=MMDRV.DLL TIMER=TIMER.DRV [MCI]

[8장 4번] c:\windows\system.ini 파일에 라인 번호를 붙여 출력하라

package Java8_4; import java.io.*; public class Java8_4 { public static void main(String[] args) { try{ File f = new File("c:\\windows\\system.ini"); BufferedReader br = new BufferedReader(new FileReader(f)); String line; int count = 0; System.out.println(f.getPath() + " 파일을 읽어 출력합니다."); while((line = br.readLine()) != null) { System.out.println((++count) + ": " + line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ------------------------------------ c:\windows\system.ini 파일을 읽어 출력합니다. 1: ; for 16-bit app support 2: [386Enh] 3: woafont=dosapp.fon 4: EGA80WOA.FON=EGA80WOA.FON 5: EGA40WOA.FON=EGA40WOA.FON 6: CGA80WOA.FON=CGA80WOA.FON 7: CGA40WOA.FON=CGA40WOA.FON 8: 9: [drivers] 10: wave=mmdrv.dll 11: timer=timer.drv 12: 13: [mci]

[8장 5번] 2개의 파일을 입력받고 비교하여 같으면 "파일이 같습니다.", 틀리면 "파일이 서로 다릅니다"를 출력하는 프로그램을 작성하라. 텍스트 및 바이너리 파일 모두를 포함한다.

package Java8_5; import java.io.*; import java.util.*; public class Java8_5 { private static boolean compare(FileInputStream fin1, FileInputStream fin2) throws IOException { byte[] b1 = new byte[1024]; // file1 내용 저장 byte[] b2 = new byte[1024]; // file2 내용 저장 fin1.read(b1, 0, b1.length); fin2.read(b2, 0, b2.length); for(int i=0; i> "); String file1 = sc.nextLine(); System.out.print("두번째 파일 이름을 입력하세요 >> "); String file2 = sc.nextLine(); System.out.println(file1 + "와 " + file2 + "를 비교합니다."); try{ FileInputStream fin1 = new FileInputStream(file1); FileInputStream fin2 = new FileInputStream(file2); if(compare(fin1, fin2) == true) System.out.println("파일이 같습니다."); else System.out.println("파일이 다릅니다."); fin1.close(); fin2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } --------------------------------------- 전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다. 첫번째 파일 이름을 입력하세요 >> elvis1.txt 두번째 파일 이름을 입력하세요 >> elvis2.txt elvis1.txt와 elvis2.txt를 비교합니다. 파일이 같습니다. --------------------------------------- 전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다. 첫번째 파일 이름을 입력하세요 >> elvis1.txt 두번째 파일 이름을 입력하세요 >> elvis2.txt elvis1.txt와 elvis2.txt를 비교합니다. 파일이 다릅니다.

[8장 6번] 사용자로부터 2개의 텍스트 파일 이름을 입력받고 첫 번째 파일 뒤에 두 번째 파일을 덧붙인 새로운 파일을 생성하는 프로그램을 작성하라.

package Java8_6; import java.io.*; import java.util.Scanner; public class Java8_6 { private static void new_file(FileReader fr, FileWriter fw) throws Exception{ char[] buf = new char[100]; int count = 0; while(true){ count = fr.read(buf, 0, buf.length); if(count == -1) // 파일 끝 만나면 break; if(count>0) fw.write(buf, 0, count); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); FileReader fr = null; FileWriter fw = null; File file = new File("appended.txt"); System.out.println("전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다."); System.out.print("첫번째 파일 이름을 입력하세요 >> "); String file1 = sc.nextLine(); System.out.print("두번째 파일 이름을 입력하세요 >> "); String file2 = sc.nextLine(); try{ fr = new FileReader(file1); fw = new FileWriter(file); new_file(fr, fw); fr.close(); // file1은 file에 다 옮겼으니 close, file은 file2를 더 적어야 하기때문에 close안함 fr = new FileReader(file2); new_file(fr, fw); System.out.println("프로젝트 폴더 밑에 " + file.getName() + " 파일에 저장하였습니다."); fr.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } ---------------------------------- 전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다. 첫번째 파일 이름을 입력하세요 >> elvis1.txt 두번째 파일 이름을 입력하세요 >> elvis2.txt 프로젝트 폴더 밑에 appended.txt 파일에 저장하였습니다.

[8장 7번] 파일 복사 연습을 해보자. 이미지 복사가 진행되는 동안 10% 진행될 때마다 '*' 하나씩 출력하도록 하라

package Java8_7; import java.io.*; public class Java8_7 { public static void main(String[] args) { File f1 = new File("a.png"); File f2 = new File("b.png"); BufferedInputStream bri = null; BufferedOutputStream bro = null; System.out.println(f1.getName() + "를 " + f2.getName() + "로 복사합니다.

10%마다 *를 출력합니다."); try{ bri = new BufferedInputStream(new FileInputStream(f1)); bro = new BufferedOutputStream(new FileOutputStream(f2)); long progress = 0; long tenp = f1.length()/10; byte[] buf = new byte[1024]; int count = 0; while(true){ count = bri.read(buf, 0, buf.length); if(count == -1){ if(progress>0) System.out.print("*"); break; } if(count > 0) bro.write(buf, 0, count); progress += count; if(progress >= tenp){ System.out.print("*"); progress = 0; } } bri.close(); bro.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ------------------------- a.png를 b.png로 복사합니다. 10%마다 *를 출력합니다. *********

[8장 8번] File 클래스를 이용하여 c:\에 있는 파일 중에서 제일 큰 파일의 이름과 크기를 출력하라

package Java8_8; import java.io.File; public class Java8_8 { public static void main(String[] args) { File file = null; file = new File("c:\\"); File[] files = file.listFiles(); // 파일 리스트 배열 File big = null; // 가장 큰 파일 long max = 0; // 가장 큰 파일의 크기 for(int i=0; i

[8장 9번] c:\temp에 있는 .txt 파일만 삭제하는 프로그램을 작성하라. c:\나 c:\windows 등의 디렉터리에 적용하면 중요한 파일이 삭제될 수 있으니 조심하라

package Java8_9; import java.io.*; public class Java8_9 { public static void main(String[] args) { File file = new File("c:\\Temp"); String[] files = file.list(); System.out.println(file.getPath() + "디렉터리의 .txt 파일을 모두 삭제합니다...."); int count = 0; for(int i=0; i

[8장 10번] 전화번호를 미리 c:\temp\phone.txt 파일에 여러 개 저장해둔다. 이 파일을 읽어 다음 실행 예시와 같은 작동하는 검색 프로그램을 작성하라

package Java8_10; import java.util.*; import java.io.*; public class Java8_10 { public static void main(String[] args) { Scanner sc = null; File file = new File("c:\\Temp\\phone.txt"); FileReader fr = null; HashMap hs = new HashMap(); try{ fr = new FileReader(file); sc = new Scanner(fr); while(sc.hasNext()){ String name = sc.next(); String phone = sc.next(); hs.put(name, phone); } System.out.println("총 " + hs.size() + "개의 전화번호를 읽었습니다."); sc = new Scanner(System.in); while(true){ System.out.print("이름 >> "); String name = sc.next(); if(name.equals("그만")) break; String phone = hs.get(name); if(phone == null) System.out.println("찾는 이름이 없습니다."); else System.out.println(phone); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } -------------------------------- 총 9개의 전화번호를 읽었습니다. 이름 >> 모드리치 찾는 이름이 없습니다. 이름 >> 밪구영 찾는 이름이 없습니다. 이름 >> 손흥민 010-1111-2222 이름 >> 박주영 010-6666-7777 이름 >> 차범근 010-2222-3333 이름 >> 메시 010-8888-9999 이름 >> 그만

[8장 11번] words.txt에는 한 라인에 하나의 영어 단어가 들어 있다. 이 파일을 한 라인씩 읽어 Vector에 라인별로 삽입하여 저장하고, 영어 단어를 입력받아 그 단어로 시작하는 모든 단어를 벡터에서 찾아 출력하는 프로그램을 작성하라

package Java8_11; import java.io.*; import java.util.*; public class Java8_11 { public static void main(String[] args) { Vector v = new Vector(); File file = new File("words.txt"); FileReader fr = null; Scanner sc = null; try{ fr = new FileReader(file); sc = new Scanner(fr); while(sc.hasNext()){ String word = sc.nextLine(); v.add(word); } System.out.println("프로젝트 폴더 밑의 " + file.getName() + " 파일을 읽었습니다..."); sc = new Scanner(System.in); while(true){ boolean find = false; System.out.print("단어 >> "); String u_word = sc.next(); if(u_word.equals("그만")){ System.out.println("종료합니다...."); break; } for(int i=0; i> lov love lovebird lovelorn 단어 >> kitt kitten kittenish kittle kitty 단어 >> asdfjl 발견할 수 없음 단어 >> but but butadiene butane butch butchery butene buteo butler butt butte butterball buttercup butterfat butterfly buttermilk butternut buttery buttock button buttonhole buttonweed buttress butyl butyrate butyric 단어 >> 그만 종료합니다....

[8장 12번] 텍스트 파일에 있는 단어를 검색하는 프로그램을 작성해보자.

package Java8_12; import java.io.*; import java.util.*; public class Java8_12 { public static void main(String[] args) { Vector v = new Vector(); FileReader fr = null; Scanner sc = null; try { System.out.println("전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다."); sc = new Scanner(System.in); System.out.print("대상 파일명 입력 >> "); String fileN = sc.next(); fr = new FileReader(fileN); sc = new Scanner(fr); while (sc.hasNext()) { String word = sc.nextLine(); v.add(word); } sc = new Scanner(System.in); while(true){ boolean find = false; System.out.print("검색할 단어나 문장 >> "); String text = sc.nextLine(); if(text.equals("그만")){ System.out.println("프로그램을 종료합니다..."); break; } for(int i=0; i> test.java 검색할 단어나 문장 >> void 6 : public static void main(String[] args) { 검색할 단어나 문장 >> int 9 : System.out.println("전화번호 입력 프로그램입니다."); 13 : System.out.print("이름 전화번호 >> "); 21 : System.out.println("c:\\Temp\\phone.txt에 저장하였습니다."); 23 : e.printStackTrace(); 검색할 단어나 문장 >> class 5 :public class Java8_1 { 검색할 단어나 문장 >> ; 1 :package Java8_1; 2 :import java.io.*; 3 :import java.util.*; 7 : Scanner sc = new Scanner(System.in); 8 : FileWriter fw = null; 9 : System.out.println("전화번호 입력 프로그램입니다."); 11 : fw = new FileWriter("c:\\Temp\\phone.txt"); 13 : System.out.print("이름 전화번호 >> "); 14 : String text = sc.nextLine(); 16 : break; 17 : fw.write(text); 18 : fw.write("

"); 20 : fw.close(); 21 : System.out.println("c:\\Temp\\phone.txt에 저장하였습니다."); 23 : e.printStackTrace(); 검색할 단어나 문장 >> 그만 프로그램을 종료합니다...

[8장 13번] 간단한 파일 탐색기를 만들어보자. 처음 시작은 c:\에서부터 시작한다. 명령은 크게 2가지로서 ".."를 입력하면 부모 디렉터리로 이동하고, "디렉터리명"을 입력하면 서브 디렉터리로 이동하여 파일리스트를 보여준다.

package Java8_13; import java.io.*; import java.util.*; public class Java8_13 { private File current = null; private File[] lists = null; private Scanner sc = null; Java8_13(){ current = new File("c:\\"); // 초기 시작 = c:\\ } void subDic(){ System.out.println("\t[" + current.getPath() + "]"); lists = current.listFiles(); // 현재 디렉토리의 파일리스트들 for(int i=0; i> "); sc = new Scanner(System.in); String command = sc.next(); if(command.equals("그만")) break; if(command.equals("..")){ String s = current.getParent(); if(s==null) continue; else{ current = new File(current.getParent()); // 현재 위치를 부모디렉터리로 reset subDic(); } } else{ if((new File("c:\\", command)).isFile()) // command가 파일이면 System.out.println("\t디렉터리가 아닙니다."); else if(command.equals(current.getName())){ // command가 현재 위치랑 동일할 때 subDic(); } else{ current = new File(current.getPath(), command); subDic(); } } } } public static void main(String[] args) { Java8_13 dic = new Java8_13(); dic.run(); } } ------------------------------------------ ***** 파일 탐색기입니다. ***** [c:\] dir 4096바이트 $Recycle.Bin dir 0바이트 $WinREAgent dir 36864바이트 Config.Msi dir 4096바이트 Documents and Settings file 8192바이트 DumpStack.log.tmp ... ... dir 4096바이트 Temp dir 4096바이트 Users dir 20480바이트 Windows dir 16384바이트 WINDOWS.X64_193000_db_home >> windows [c:\windows] dir 0바이트 addins file 353118바이트 afreeca.ico file 222691바이트 AhnInst.log dir 0바이트 appcompat ... ... dir 13107200바이트 WinSxS file 316640바이트 WMSysPr9.prx file 11264바이트 write.exe >> web [c:\windows\web] dir 0바이트 4K dir 0바이트 Screen dir 0바이트 Wallpaper >> web [c:\windows\web] dir 0바이트 4K dir 0바이트 Screen dir 0바이트 Wallpaper >> .. [c:\windows] dir 0바이트 addins file 353118바이트 afreeca.ico file 222691바이트 AhnInst.log dir 0바이트 appcompat ... ... dir 13107200바이트 WinSxS file 316640바이트 WMSysPr9.prx file 11264바이트 write.exe >> .. [c:\] dir 4096바이트 $Recycle.Bin dir 0바이트 $WinREAgent dir 36864바이트 Config.Msi ... ... dir 4096바이트 Users dir 20480바이트 Windows dir 16384바이트 WINDOWS.X64_193000_db_home >> .. >> 그만 Process finished with exit code 0

[8장 14번] 문제 13을 확장하여 다음 명령을 추가하라

>>rename phone.txt p.txt // phone.txt를 p.txt로 변경. 파일과 디렉터리 이름 변경 >>mkdir XXX // 현재 디렉터리 밑에 XXX 디렉터리 생성

package Java8_14; import java.io.*; import java.util.*; public class Java8_14 { private File current = null; private File[] lists = null; private Scanner sc = null; Java8_14(){ current = new File("c:\\"); // 초기 시작 = c:\\ } void subDic(){ System.out.println("\t[" + current.getPath() + "]"); lists = current.listFiles(); // 현재 디렉토리의 파일리스트들 for(int i=0; i> "); sc = new Scanner(System.in); String command = sc.nextLine(); String[] s = command.split(" "); if(command.equals("그만")) break; if(command.equals("..")){ String st = current.getParent(); if(st==null) continue; else{ current = new File(current.getParent()); // 현재 위치를 부모디렉터리로 reset subDic(); } } else if(s[0].equals("mkdir")){ if(s[0].equals(current.getName())) System.out.println(s[1] + " 디렉터리는 이미 존재합니다."); else { current = new File(current.getPath(), s[1]); mkdir(); System.out.println(s[1] + " 디렉터리를 생성하였습니다."); current = new File(current.getParent()); subDic(); } } else if(s[0].equals("rename")){ if(s.length == 1) System.out.println("파일명 2개가 주어지지 않았습니다!"); else if(s.length == 2){ System.out.println("두 개의 파일명이 주어지지 않았습니다!"); } else if(s.length == 3){ File file1 = new File(current.getPath(), s[1]); File file2 = new File(current.getPath(), s[2]); rename(file1, file2); System.out.println(s[1] + " -> " + s[2] + " 이름을 변경하였습니다!!"); subDic(); } } else{ if((new File("c:\\", command)).isFile()) // command가 파일이면 System.out.println("\t디렉터리가 아닙니다."); else if(command.equals(current.getName())){ // command가 현재 위치랑 동일할 때 subDic(); } else{ current = new File(current.getPath(), command); subDic(); } } } } public static void main(String[] args) { Java8_14 dic = new Java8_14(); dic.run(); } } ------------------------------------------ ***** 파일 탐색기입니다. ***** [c:\] dir 4096바이트 $Recycle.Bin dir 0바이트 $WinREAgent dir 36864바이트 Config.Msi ... ... dir 4096바이트 Users dir 20480바이트 Windows dir 16384바이트 WINDOWS.X64_193000_db_home >> Temp [c:\Temp] file 222바이트 phone.txt >> mkdir 손흥민 손흥민 디렉터리를 생성하였습니다. [c:\Temp] file 222바이트 phone.txt dir 0바이트 손흥민 >> mkdir 차범근 차범근 디렉터리를 생성하였습니다. [c:\Temp] file 222바이트 phone.txt dir 0바이트 손흥민 dir 0바이트 차범근 >> mkdir 이승우 이승우 디렉터리를 생성하였습니다. [c:\Temp] file 222바이트 phone.txt dir 0바이트 손흥민 dir 0바이트 이승우 dir 0바이트 차범근 >> rename 이승우 백승호 이승우 -> 백승호 이름을 변경하였습니다!! [c:\Temp] file 222바이트 phone.txt dir 0바이트 백승호 dir 0바이트 손흥민 dir 0바이트 차범근 >> rename phone.txt p.txt phone.txt -> p.txt 이름을 변경하였습니다!! [c:\Temp] file 222바이트 p.txt dir 0바이트 백승호 dir 0바이트 손흥민 dir 0바이트 차범근 >> 그만 Process finished with exit code 0

728x90

반응형

from http://cs-ssupport.tistory.com/169 by ccl(A) rewrite - 2021-12-17 23:01:44