본문 바로가기
(학) (공) (자)

01.23 (17일차)

by 만석이 2024. 1. 23.

1교시

---File클래스---
              1. 파일 또는 폴더에 대한 정보를 제공하는 클래스
2. 경로명, 파일크기, 타입, 날짜 등의 속성 정보를 제공한다.
3. 파일 생성, 삭제, 이름 변경 등 파일 관리 작업을 지원하기 위한 메서드로 구성되어있다.


--File클래스 예시1--
public class Ex1_File {

public static void main(String[] args) {

//파일 객체를 생성할 경로
String path = "D:/Test.txt";

//준비된 경로로 File객체 생성
File f = new File(path);

//실행을 하면 File클래스가 path까지의 통로를 생성한다고 생각하면 된다.


//isFile() : 최종목적지가 파일인지? 파일이면 true
if(f.isFile()) { //length() : 최종목적지 파일의 크기
System.out.println(f.length() +"byte");
}

}
}

---list()---
디렉토리 하위 요소들의 이름을 모두 반환한다.


--list 예시1--

public class Ex2_File {
public static void main(String[] args) {

String path = "D:/";

File f = new File(path);

//최종목적지가 폴더면 True
if(f.isDirectory()){{
//list()
//디렉토리 하위 요소들의 이름을 모두 반환한다.
String[] names = f.list();

for(String s : names) {
System.out.println(s);
}

}

}
}
}



---exists()---
1. 경로가 존재하면 True



---mkdirs---
1.폴더생성



--exists()/mkdirs-- 예시 

public class Ex3_File {


public static void main(String[] args) {

String path = "D:/aaa/bbb";

File f = new File(path);

//exists() : 경로가 존재하면 True
if(!f.exists()) {
System.out.println("폴더생성");
f.mkdirs();
}
}
}


---입출력 스트림---

1. 자바의 기본적인 데이터 입출력은 java.io패키지에서 제공한다.
2.  java.io패키지에서는 파일 시스템의 정보를 얻기위한 File클래스와 데이터 입출력을 위한 다양한 스트림 클래스를 제공한다.


---스트림종류---
1.바이트 기반의 스트림
1-1. (1byte) 단위로 나눠 읽거나 쓴다.

2.문자 기반의 스트림
2-1 (2byte) 이상의 단위로 나워 보통 텍스트 기반의 문서를 다루기위해 사용되는 스트림



---read()---
한번에 1byte씩 읽는다.
읽을 내용이 없으면 -1을 반환한다.



---read() 예시1---
public class EX1_FileInputStream {

public static void main(String[] args) {

String path = "D:/Test.txt";

File f = new File(path);

if(f.exists()) {//파일이 실제 존재할 때만 수행
try {
FileInputStream fis = new FileInputStream(f);

int code = 0;

while((code = fis.read()) !=-1) {
Systehttp://m.out.print((char)code);
}
//스트림은 사용이 완료된 이후 close를 통해 닫아주는것이 좋다.
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


정리- 한글은 3바이트 지만 1바이트씩 읽어 오려하니 깨진다.






2교시



---read() 오버로딩---
1. read()는 한 바이트씩 읽어들이지만 
2. read(byte[]b)는 배열 byte[]b를 이용해서 한꺼번에 바이트 개수를 읽어온다.


--read() 오버로딩--예시1


public class Ex2_FileInputStream {
public static void main(String[] args) {
String path = "D:/Test.txt";

File f = new File(path);

byte[] read = new byte[100];

if(f.exists()) {
try {
FileInputStream fis = new FileInputStream(f);
//read()매세드의 오버로딩
//read()는 한 바이트씩 읽어들이지만 
//read(byte[]b)는 배열 byte[]b를 이용해서 한꺼번에 바이트 개수를 읽어온다.
fis.read(read);

String res = new String(read);

System.out.println(res);

fis.close();
} catch (Exception e) {

}
}
}
}




---write()---
외부에 값을 쓸수있다.


--write()--예시1


public class Ex1_FileOutputStream {

public static void main(String[] args) {

try {
FileOutputStream fos = new FileOutputStream("D:/fileOut.txt");

//write()는 문자나 int byte만 가능하다. 즉 문자열 불가능
try {

fos.write('J');
fos.write('A');
fos.write('V');
fos.write('A');

fos.close();
//경로에 파일이 없으면 파일을 같이 생성한다.

} catch (IOException e) {

e.printStackTrace();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
}


}
}


---문자열 쓰는법---

public class Ex1_FileOutputStream {

public static void main(String[] args) {

try {
FileOutputStream fos = new FileOutputStream("D:/fileOut.txt",true); //true 이어쓰기 False 줄바꿈

//write()
try {

fos.write('J');
fos.write('A');
fos.write('V');
fos.write('A');

String msg = "fileOutput 예제입니다.\n";
String msg2 = "여러분줄도 가능합니다.";

fos.write(msg.getBytes());
fos.write(msg2.getBytes());


fos.close();
//경로에 파일이 없으면 파일을 같이 생성한다.

} catch (IOException e) {

e.printStackTrace();
}



} catch (FileNotFoundException e) {
e.printStackTrace();
}


}
}



String 변수에 문자열값을 넣어놓고 변수의 문자열값을 write()로 불러온다. 




---문자 기반의 스트림---

1. 자바에서는 기본 자료형은 char을 통해 문자를 저장할수있다.

2. 1byte 단위로 처리하는 바이트 기반 스트림은 모든 파일을 다룰 수 있으나 문자를 처리하는 char형의 크기는
       2byte로 별로도 처리하지 않으면 정상적으로 읽지 못하는 경우가 있다.

3. 이때 문자 기반의 스트림을 사용하면 간단하게 문자를 처리할수있다.


---FileReader---
1. FileReader 는 FileInputStream의 기능과 메서드의 이름이 같다.

---char기반의 스트림---
1. Reader, Writer의 자식클래스를 사용
2. 기본적으로 2byte를 지원하기 때문에 2byte이상의 언어로 구성된 파일도 손쉽게 입출력가능하다.





--char기반의 스트림--예시1


public class Ex3_FileReader {

public static void main(String[] args) {
//char기반의 스트림은 Reader, Writer의 자식클래스를 사용
//기본적으로 2byte를 지원하기 때문에 2byte이상의 언어로 구성된 파일도 손쉽게 입출력가능하다.

try {
FileReader fr = new FileReader("D:/Test.txt"); 

int code = 0; 

while((code = fr.read())!=-1) { //-1은 파일의 마지막을 뜻한다.
Systehttp://m.out.print((char)code); //int 형식을 char로 변환해주면서 출력
}

} catch (Exception e) {

}
}
}












3교시

//Test.txt에 아무 내용이나 적는다.
//한글,영어 소문자/대문자 섞어서 작성

//Test.txt의 내용을 읽어와서
//내용의 대문자와 소문자의 개수를 출력하세요

//결과
//대문자 : X개
//소문자 : X개


public class Ex4_FileReader {
public static void main(String[] args) {

int upper =0;
int lower =0;
int lang =0;
int number =0;

try {
FileReader fr = new FileReader("D:/Test.txt");

int code = 0;

while((code = fr.read())!=-1) {

if(Character.isUpperCase((char)code)) {
upper ++;
}else if (Character.isLowerCase((char)code))
lower ++;
 else if((Character.toString((char)code)).matches("[0-9]")){
 number++;
 }else {
 lang++;
 }
 }


System.out.println("결과");
System.out.println("대문자"+upper+"개");
System.out.println("소문자"+lower+"개");
System.out.println("숫자"+number+"개");
System.out.println("한글"+lang+"개");


} catch (Exception e) {

}
}
}



---보조스트림---
1. 스트림은 기능에 따라 기반 스트림과 보조 스트림으로 구분한다.


--기반스트림--

대상에 직접 읽고 쓰는 스트림

--보조스트림--

1. 직접 읽고 쓰는 기능이 없이, 기반스트림에 추가로 사용할수있는 스트림
2. 보조스트림으로는 실제 데이터를 주고받을수없다.
3. 스트림의 기능을 향상시키거나 새로운 기능을 제공해주는 스트림으로 다른 보조스트림과 중첩하여 사용할수있다.



---보조스트림 연결하기---

1. 보조스트림을 사용하려면 보조 스트림을 매개변수로 받는 기반 스트림이 먼저 선언되어야한다.
2. 스스로 데이터를 읽거나 쓸수 없기 때문에 입출력과 바로 연결되는 기반 스트림이 필요하다.


---성능향상보조스트림---
1. 느린 하드디스크와 네트워크는 입출력 성능에 영향을 준다.
2. 이때 입출력 잡업하지 않고 버퍼라는 메모리를 이용해 작업하면 실행성능을 향상 시킬수있다.
3. 하지만 버퍼는 크기가 작아 많은 양의 데이터를 처리하기에는 부족하다.




--보조스트림--예시1


public class Ex1_bufferedInput {
public static void main(String[] args) {

FileInputStream in = null;
BufferedInputStream bis = null;

try {
in = new FileInputStream("D:/test.txt");
bis = new BufferedInputStream(in);

int code = 0;

while((code =bis.read())!=-1) {
Systehttp://m.out.print((char)code);
}

bis.close();
in.close();

} catch (Exception e) {
// TODO: handle exception
}

}


}



---Scanner VS BufferedReader---

1. Scanner는 타입에 구애받지않는다.
2. BufferedReader는 String형식으로만 읽고 저장하기때문에 형변환을 위한 추가 코드 작성이 불가피하다.
3.BufferedReader는 Scanner보다 효율적인 메모리 용량을 가진다.
4.BufferedReader는 1kb, Sscanner는 8kb
5.BufferedReader가 안전하며 속도가 빠르다.


---InputStreamReader---
1. InputStream을 문자기반의 스트림 Reader로 변환하는 보조스트림





--InputStreamReader--예시1


public class Ex3_BufferedReader {
public static void main(String[] args) {


try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("숫장 입력 : ");
String number = br.readLine();
System.out.println(Integer.parseInt(number));

} catch (Exception e) {
// TODO: handle exception
}
}
}



---파일을 복사해보자---

public class Ex4_BufferedWriter {
public static void main(String[] args) {
FileReader reader = null;
BufferedReader br =null;

FileWriter writer = null;
BufferedWriter bw = null;

try {
reader = new FileReader("D:/test.txt");
writer = new FileWriter("D:/Test_copy.txt",false);

br = new BufferedReader(reader);
bw = new BufferedWriter(writer);

String str ="";

while((str = br.readLine()) !=null) {
bw.write(str+"\n");
}
System.out.println("복사성공");

bw.close();
writer.close();
br.close();
reader.close();


} catch (Exception e) {
// TODO: handle exception
}

}
}

'(학) (공) (자)' 카테고리의 다른 글

자바 기초 커리큘럼  (1) 2024.04.04
01.22(16일차)  (0) 2024.01.22
01.18(14일차)  (0) 2024.01.18
01.16(12일차)  (0) 2024.01.16
01.15(11일차)  (1) 2024.01.15