스포츠마케터의 초보 개발자 도전기
JAVA study 18 본문
1. File
- Input과 Output (IO)
jvm을 기준으로 밖에 어떤 데이터를 만들면 output, 밖에 있는 어떤 데이터를 읽어오면 input
1) 파일 용량 체크
package ex1_file;
import java.io.File;
public class Ex1_File {
public static void main(String[] args) {
// IO(Input/Output)
// IO는 입출력 스트림을 의미
// 스트림이란 데이터를 입출력하기 위한 통로
// jvm에서 console로 값을 내보내면 Output
// console의 값을 jvm에서 읽어오면 Input
String path = "C:/java_kms/test.txt";
File f = new File(path);
// 접근하는 마지막 단계가 파일인지 폴더인지 확인 가능
if (f.isFile()) {
System.out.println("파일 크기 : " + f.length() + "byte"); // f.length() -> 파일의 용량 가지고 올 수 있음
}
}// main
}
2) 폴더 내부 하위 요소의 이름 확인
package ex1_file;
import java.io.File;
public class Ex2_File {
public static void main(String[] args) {
String path = "C:/java_kms";
File f = new File(path);
if(f.isDirectory()) {//!f.isFile도 가능
// 접근하는 마지막 단계가 폴더라면, 폴더내부의 하위 요소들의 이름을 모두 가져온다
String[] names = f.list();
for(String s : names) {
System.out.println(s);
}
}
}//main
}
3) 하위 목록들 중 폴더만 확인
package ex1_file;
import java.io.File;
public class Ex3_File {
public static void main(String[] args) {
String path = "C:/java_kms";
File f = new File(path);
//하위목록들의 폴더만 확인
if(f.isDirectory()) {
File[] farr = f.listFiles();
for ( int i = 0; i < farr.length; i++) {
if( farr[i].isDirectory()) {
System.out.println(farr[i].getName());
}
}
}
}//main
}
4) 폴더 만들기, 폴더나 파일 삭제
package ex1_file;
import java.io.File;
public class Ex4_File {
public static void main(String[] args) {
//File 클래스는 폴더를 만들 수 있다 (파일은 안됨)
//abc폴더 만들기
String path = "C:/java_kms/abc";
File f = new File(path);
if (!f.exists()) {
// f가 가진 path 경로가 실제로 존재한다면 true
f.mkdirs(); //make directory, //폴더를 2개 이상 일때는 복수형을 써야하지만 그냥 복수형으로 다쓰면 됨
}else {
System.out.println("폴더가 존재함");
//path경로의 폴더나 파일 삭제
//f.delete();
}
}// main
}
2. FileInput
package ex2_file_input;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Ex1_FileInput {
public static void main(String[] args) {
String path = "C:/java_kms/test.txt";
File f = new File(path);
FileInputStream fis = null; //밖에 만드는 것이 좋음
if (f.exists()) { // 파일이 없으면 오류가 나기때문에 확인용으로 exists 사용
// 파일 클래스와 연결할 InputStream을 생성
try {
fis = new FileInputStream(f); // 파일이 없으면 안되니 try-catch로 묶음. 1byte단위로 가져오기때문에 한글은은 오류값 나옴
int code = 0;
// Stream은 더이상 읽을 것이 없다면 -1을 반환한다
// fis.read()를 통해 1byte씩 데이터를 가져오다가
// 문서의 끝 (EOF - end of file)인 -1을 마나면 종료한다
while ((code = fis.read()) != -1) { // 파일에서 읽어 올 것이 없을때 -1을 가져옴
System.out.print((char) code);
}
// 사용을 완료한 stream은 반드시 닫아 줘야함 (아래 확인)
// fis.close();
} catch (Exception e) { // Exception으로 오류를 통합하여 잡는게 편함
} finally { // 정석으로 닫기
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
}
}
}
}// main
}
예제) 파일에 숫자와 영어가 있을때 숫자만 더한 합을 구하기
package ex2_file_input;
import java.io.File;
import java.io.FileInputStream;
public class Ex2_InputWork {
public static void main(String[] args) {
String path = "C:/java_kms/work.txt";
File f = new File(path);
FileInputStream fis = null;
if (f.exists()) {
try {
fis = new FileInputStream(f);
int code = 0;
int sum = 0;
while ((code = fis.read()) != -1) {
// String s = "" + (char) code; 아래코드가 jvm입장에서 더 좋은
String s = String.valueOf((char) code);
try {
sum += Integer.parseInt(s); // Integer.parseInt() -> 숫자형의 문자열을 받으면 Integer로 변환
} catch (Exception e) {
}
} // while
System.out.println("결과 : " + sum);
} catch (Exception e) {
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e2) {
}
}
}
}// main
}
3. Stream의 종류
package ex2_file_input;
import java.io.File;
import java.io.FileInputStream;
public class Ex3_FileInput {
public static void main(String[] args) {
//Stream의 종류
//...Stream : byte기반의 스트림 (1byte씩만 처리 가능)
//...Reader, ...Writer : char기반의 스트림(최대 2byte씩 처리 가능)
String path = "C:/java_kms/test.txt";
File f = new File(path);
byte[] b_read = new byte[(int)f.length()];//(int)f.length -> 파일의 크기와 가장 가깝게 byte배열 사이즈 정하기
FileInputStream fis = null;
if (f.exists()) {
try {
fis = new FileInputStream(f);
// fis가 읽어온 내용을 b_read에 담는다
fis.read(b_read);
// byte의 배열을 String 형식으로 변환
String res = new String(b_read);
System.out.println(res);
} catch (Exception e) {
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e2) {
}
}
}
}// main
}
(참고)
package ex3_input;
import java.io.IOException;
public class Ex1_Input {
public static void main(String[] args) {
// 참고
// 스캐너 내부 구조 키보드 입력값
byte[] console = new byte[100];
try {
System.out.print("값 : ");
System.in.read(console);
String str = new String(console);
System.out.println(str.trim()); // System.in은 표준입력장치(키보드 등)에서 값을 받을때 쓰는 스트림
} catch (IOException e) {
}
}// main
}
4. BufferedInputStream
package ex4_buffered_input;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Ex1_BufferedInput {
public static void main(String[] args) {
// Buffered스트림을 통해 입출력의 효율성을 향상시킬 수 있다.
// 파일을 읽거나 쓸때 버퍼링 작업을 수행하기 때문이다.
// 버퍼링이란 : 입출력할 데이터를 버퍼라는 메모리 영역에 바이트 배열로 저장하여 한번에 사용하는 것
File f = new File("C:/java_kms/test.txt");
FileInputStream fis = null;
BufferedInputStream bis = null; // buffer라는 이름이 들어있으면 시간적으로 이득을 보려고 하는 구조가 많다
byte[] b_read = new byte[(int) f.length()];
try {
fis = new FileInputStream(f);
bis = new BufferedInputStream(fis); // BufferedInputStream은 FileInputSteam에서 넘겨받아야함
bis.read(b_read);
String res = new String(b_read);
System.out.println(res);
} catch (Exception e) {
} finally { // 스트림이 열려있을때 열린 역순으로 닫는 것이 좋다
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e2) {
}
}
}// main
}
5. Ouput
package ex5_output;
import java.io.PrintStream;
public class Ex1_Output {
public static void main(String[] args) {
//PrintStream은 OutputStream의 대표적인 자식 클래스로서
//화면에 데이터를 출력하도록 하는 클래스
PrintStream ps = null;
ps = System.out;
int first = 'A';
ps.write(first);
ps.write('B');
ps.write('\n');
ps.write('C');
}// main
}
--
package ex5_output;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Ex2_FileOutput {
public static void main(String[] args) {
String path = "C:/java_kms/fileOutput예제.txt";
File f = new File(path);
FileOutputStream fos = null;
if (!f.exists()) {
try {
// new FileOutputStream(File 클래스의 객체, 내용 이어 붙일지 여부);
fos = new FileOutputStream(f, true);
String msg = "file output stream의 예제입니다.";
// msg.getBytes(); <- String을 byte[]로 변환
fos.write(msg.getBytes());
} catch (Exception e) {
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (Exception e2) {
}
}
}
}// main
}
BufferedOutput
package ex5_output;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class Ex3_BufferedOutputStream {
public static void main(String[] args) {
// BufferedOutputStream
// 일반 OutputStrea을 보조하여 속도를 높여주는 스트림
File f = new File("C:/java_kms/bufOut.txt");
FileOutputStream fos = null;
BufferedOutputStream bos = null;
if (!f.exists()) {
try {
fos = new FileOutputStream(f);
bos = new BufferedOutputStream(bos);
String msg = "버퍼 OutputSteam의 예제";
bos.write(msg.getBytes());
// flush : 쓰고자하는 내용을 기억하고 있다가 물리적으로 파일에 쓰는 메서드
// 기록을 끝낸 상태에서 닫는 순서에 상관없이 기록함 -> 메모리차지, 속도저하의 문제 있으나 오류 막는 용도
bos.flush();
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}// main
}
6.Reader
package ex7_reader;
import java.io.File;
import java.io.FileReader;
public class Ex1_FileReader {
public static void main(String[] args) {
// byte기반의 스트림은 1바이트씩 처리하기 때문에 한글의 입출력이 불현하지만
// char기반의 스트림은 최대 2바이트를 지원하기 때문에 한글로 구성된 파일을 입출려하는데 적합하다
File f = new File("C:/java_kms/test.txt");
FileReader fr = null;
try {
fr = new FileReader(f);
int code = 0;
while ((code = fr.read()) != -1) {
System.out.print((char) code + " ");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}// main
}
package ex7_reader;
import java.io.File;
import java.io.FileReader;
public class Ex2_FileReader {
public static void main(String[] args) {
// file.txt의 내용을 읽고 대소문자 갯수 출력
File f = new File("C:/java_kms/file.txt");
FileReader fr = null;
try {
fr = new FileReader(f);
int code = 0;
int up = 0;
int lo = 0;
while ((code = fr.read()) != -1) {
// if(Character.isUpperCase((char)code)) {
if (code >= 'A' && code <= 'Z') {
up++;
}
// if(Character.isLowerCase((char)code)) {
if (code >= 'a' && code <= 'z') {
lo++;
}
} // while
System.out.println("대문자 갯수 : " + up);
System.out.println("소문자 갯수 : " + lo);
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}// main
}
Writer
package ex8_writer;
import java.io.File;
import java.io.FileWriter;
public class Ex1_FileWriter {
public static void main(String[] args) {
File f = new File("C:/java_kms/fileWriter예제.txt");
FileWriter fw = null;
try {
fw = new FileWriter(f);
String str = "나는 fileWriter의 예제입니다.\n두 줄도 잘됨";
// char기반의 스트림은 문자열을 byte[]로 쪼개지 않아도 파일에 쓸 수 있다.
fw.write(str);
// fw.flush(); 닫기 잘해서 필요없도록 하자
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}// main
}
--
BufferedWriter
package ex8_writer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Ex2_BufferedWriter {
public static void main(String[] args) {
File f = new File("C:/java_kms/bufWriter.txt");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(f);
bw = new BufferedWriter(fw);
bw.write("bufWriter의 테스트 입니다.");
bw.newLine(); // 엔터함수
bw.write("\n출력테스트 중"); // 엔터함수 없이 다음줄로 작성
bw.flush();
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}// main
}
과제1) 파일에서 읽어온 내용이 회문인지 판단
package ex6_work;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Ex1_work {
public static void main(String[] args) {
// FileInputStream을 통해서 file.txt의 내용을 읽어온다
// 일어온 내용이 회문인지 판단
File f = new File("C:/java_kms/file.txt");
byte[] b_read = new byte[(int) f.length()];
FileInputStream fis = null;
BufferedInputStream bis = null;
if (f.exists()) {
try {
fis = new FileInputStream(f);
bis = new BufferedInputStream(bis);
bis.read(b_read);
String res = new String(b_read);
System.out.println(res);
// 비교
for (int i = 0; i < res.length() / 2; i++) {
if (res.charAt(i) != res.charAt(res.length() - i - 1)) {
System.out.println("회문이 아닙니다.");
return;
}
} // for
System.out.println("회문입니다.");
} catch (Exception e) {
} finally {
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
}
}
}
}// main
}
과제2) 파일에서 읽어온 내용에 입력한 문장이 몇번 나오는지 횟수 체크
package ex6_work;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
public class Ex2_work {
public static void main(String[] args) {
// work1.txt를 만들고 내용을 넣은 후, 키보드에서 입력받은 문장의 출현빈도를 출력하시오
Scanner sc = new Scanner(System.in);
File f = new File("C:/java_kms/work1.txt");
byte[] b_read = new byte[(int) f.length()];
FileInputStream fis = null;
BufferedInputStream bis = null;
int cnt = 0;
if (f.exists()) {
try {
fis = new FileInputStream(f);
bis = new BufferedInputStream(bis);
bis.read(b_read);
String res = new String(b_read);
System.out.println(res);
System.out.print("입력 : ");
String in = sc.next();
for (int i = 0; i < res.length() - (in.length() - 1); i++) {
if (in.equals(res.substring(i, in.length() + i))) {
cnt++;
}
}
System.out.println("출현횟수는 " + cnt);
} catch (Exception e) {
System.out.println("에러");
e.printStackTrace();
// TODO: handle exception
} finally {
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}// main
}
tCode
package ex6_work;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
public class Ex2_work_tCode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("C:/java_kms/work1.txt");
byte[] b_read = new byte[(int)f.length()];
String content = ""; //원본을 담을 변수
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(f);
bis = new BufferedInputStream(bis);
bis.read(b_read);
content = new String(b_read);
System.out.println("입력 : ");
String input = sc.next();
// int leng = 0;
// int count = 0;
// while(leng + input.length() <= content.length()) {
// if(input.equals(content.substring(leng,leng+input.length()))) {
// count++;
// }
// leng++;
// }//while
// System.out.println(input + "횟수" + count);
int count = 0;
int idx = content.indexOf(input);
while(idx != -1) {
count++;
idx = content.indexOf(input, idx + 1);
}
System.out.println(input + "횟수" + count);
} catch (Exception e) {
// TODO: handle exception
}
}//main
}
과제) 행맨
package ex9_work;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Ex1_Work {
public static void main(String[] args) {
/*
* word : ☆☆☆☆☆ >> o
* o는 포함되어있지 않습니다.
* word : ☆☆☆☆☆ >> p
* word : ☆pp☆☆ >> aa
* 한글자 영소문자만 입력하세요
* word : ☆pp☆☆ >> a
* word : app☆☆ >> a
* a는 이미 입력한 문자입니다.
* word : app☆☆
* >> e word : app☆e >> l word : apple >> apple 정답! 정답횟수 7회
*/
String[] str = { "hope", "view", "banana", "apple" };
Scanner sc = new Scanner(System.in);
int randomArr = new Random().nextInt(str.length);
String question = str[randomArr];
String[] que = question.split("");
for (int i = 0; i < que.length; i++) {
System.out.print(que[i] + "");
}
System.out.println();
System.out.print("word : ");
String[] star = new String[que.length];
for (int i = 0; i < que.length; i++) {
star[i] = "☆";
System.out.print(star[i]);
}
System.out.println(" >>");
// System.out.print("word : " + star + ">>");
while(true) {
// 단어 맞추기
String answer = sc.next();
// 1글자만 입력
if (answer.length() > 1) {
System.out.println("한글자만 입력하세요.");
}
// 입력한 글자가 랜덤 단어에 있는지 확인하고 별을 원래 글자로
for (int i = 0; i < que.length; i++) {
if (que[i].equals(answer)) {
star[i] = que[i];
}
System.out.print(star[i]+"\n");
}//for
System.out.println();
//글자 확인하고 문제내는 거 반복
System.out.print("word : ");
for (int i = 0; i < que.length; i++) {
System.out.print(star[i]);
}//for
System.out.println(" >>");
}
}// main
}
과제)tCode
package ex9_work;
import java.util.Random;
import java.util.Scanner;
public class Ex1_Work_tCode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
String[] words = { "apple", "dog", "banana" };
int count = 0;
String answer = words[rnd.nextInt(words.length)];
// answer와 같은 길이의 문자 배열을 만들고 ☆로 채워줌
char[] cWord = new char[answer.length()];
for (int i = 0; i < cWord.length; i++) {
cWord[i] = '☆';
}
// String cString = String.valueOf(cWord); 아래꺼 대체 가능
String cString = "";
for (char c : cWord) {
cString += c;
}
while (!cString.equals(answer)) {
count++;
System.out.printf("word : %s >> ", cString);
String temp = sc.next(); // 키보드값 받기
char in = temp.charAt(0);
if (in < 'a' || in > 'z' || temp.length() > 1) {
System.out.println("한글자의 영소문자만 입력하세요.");
continue;
}
if (cString.indexOf(in) != -1) {
System.out.println(in + "은 이미 입력한 문자");
continue;
}
boolean found = false;
cString = "";
for (int i = 0; i < answer.length(); i++) {
if (answer.charAt(i) == in) {
cWord[i] = in;
found = true;
}
cString += cWord[i];
} // for
if (!found) {
System.out.println(in + "은 포함되어 있지 않음");
}
} // while
System.out.println(answer + "정답");
System.out.println("정답횟수 : " + count);
}// main
}
'develop > JAVA' 카테고리의 다른 글
JAVA study 20 (0) | 2024.05.09 |
---|---|
JAVA study 19 (0) | 2024.03.25 |
JAVA study 17 (0) | 2024.03.20 |
JAVA study 16 (0) | 2024.03.19 |
JAVA study 15 (0) | 2024.03.18 |