05.16. IO기반 입출력
package f01_file;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class FileExample {
public static void main(String[] args) {
// 물리적인 file of directory에 대한 정보 및 제어에 대한 기능을 제공하는 class
String path = "c:\\Temp\\temp.txt";
String separator = File.separator; //실행 운영체제에 맞게 구분자를 제공해줌
System.out.println(separator);
path = "c:"+File.separator+"Temp"+File.separator+"dir";
System.out.println(path);
char separatorChar = File.separatorChar;
System.out.println(separatorChar);
File file = new File(path);
//File 객체에 지정된 디렉토리 또는 파일의 절대 경로를 반환
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
//exists 해당위치에 지정된 폴더나 파일이 존재하면 true
// 존재하지 않으면 false
if(file.exists()) {
System.out.println("디렉토리 존재");
}else {
System.out.println("디렉토리가 존재하지 않습니다.");
//경로상에 존재하지 않는 마지막 디렉토리 생성
boolean isMaked = file.mkdir();
System.out.println("디렉토리 생성 여부 : "+isMaked);
//경로상에 존재하지 않는 모든 디렉토리 생성(연산 조금 느림)
//mkdirs 사용시 경로에 파일명 있으면 파일명을 폴더로 만들어버리니 주의!
isMaked = file.mkdirs();
System.out.println("디렉토리 생성 여부 : "+isMaked);
}
File file2 = new File(file,"file.txt");
absolutePath = file2.getAbsolutePath();
System.out.println(absolutePath);
if(!file2.exists()) {
try {
// 파일 생성
file2.createNewFile();
System.out.println("파일 생성 완료");
} catch (IOException e) {
System.out.println("파일 생성 실패 :" + e.getMessage());
}
}
// 현재 실행중인 프로젝트 경로
File file3 = new File("");
System.out.println("file 3 : "+file3.getAbsolutePath());
//디렉토리의 파일 및 디렉토리 정보
File temp = new File("C:\\Temp");
File[] temps = temp.listFiles();
System.out.println(temps.length);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
for(File f : temps) {
//폴더나 파일의 마지막 수정 시간 - 1000/1 밀리세컨으로 제공
long modified = f.lastModified();
String lastModified = sdf.format(modified);
System.out.print(lastModified+"\t");
// 해당되는 File이 디렉토리인지 확인
boolean isDirectory = f.isDirectory();
System.out.print(isDirectory ? "<DIR>" :"<FILE>");
System.out.print("\t");
// file or 디렉토리 명
String name = f.getName();
System.out.print(name+"\t");
// 쓰기 가능한 파일또는 디렉토리 인지 여부
boolean isWrite = f.canWrite();
System.out.println(isWrite);
path = "C:\\Temp\\dir";
File file4 = new File(path);
// 지정된 디렉토리나 파일 삭제
boolean isDeleted = file4.delete();
System.out.println("디렉토리 삭제 여부 : " + isDeleted);
File file5 = new File(path,"file.txt");
isDeleted = file5.delete();
System.out.println("파일 삭제 여부 : " + isDeleted );
File file6 = new File(path);
isDeleted = file6.delete();
System.out.println("디렉토리 삭제 여부 : " + isDeleted );
}
}
}
package c4_tree.comparable;
import java.util.TreeSet;
//Person타입 비교하려면 Comparable 인터페이스 구현해야함.
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
// 반환하는 값이 0 또는 음수면 제자리
// 양수면 변경
// 나이를 기준으로 오름차순 정렬
return this.age - o.age;
}
}
public class ComparableExample {
public static void main(String[] args) {
TreeSet<Integer> intSet = new TreeSet<>();
intSet.add(50);
intSet.add(70);
intSet.add(60);
System.out.println(intSet);
System.out.println("======================");
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("최기근",26));
set.add(new Person("이진형",17));
set.add(new Person("김진우",56));
set.add(new Person("김선경",29));
System.out.println(set);
}
}
package f02_output_stream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
public class OutputStreamExample {
public static void main(String[] args) {
String path = "C:\\Temp\\file.txt";
File file = new File(path);
try {
// 지정된 위치에 파일이 존재하지 않으면 파일 생성
// 파일을 찾아가기 위한 디렉토리가 존재하지 않으면 예외.
// 디렉토리는 생성하지 않음.
//파일 생성 해준다.(대신 dir는 생성x) , (file대신 path도 입력가능, append(이어쓰기) 여부)
// true면 이어쓰기 false면 덮어쓰기(기본값 false)
OutputStream os = new FileOutputStream(file,true);
String s = "표현";
//문자열을 바이트 배열로 변환
byte[] bytes = s.getBytes();
/* 1바이트씩 출력
System.out.println(Arrays.toString(bytes));
for(int i = 0; i<bytes.length;i++) {
os.write(bytes[i]);
}
*/
// byte 배열을 매개변수로 전달받아 모든 byte배열의 값을 출력
//os.write(bytes);
// 매개변수로 전달된 배열의 3번째 인덱스부터 n개 만큼 바이트로 출력
os.write(bytes,3,3);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f03_input_stream;
import java.io.*;
public class InputStreamExample {
public static void main(String[] args) {
//프로그램 기준에서 외부 데이터를 읽어오는 class
InputStream is = null;
try {
String path = "C:\\Temp\\file.txt";
is = new FileInputStream(path);
// inputstream과 연결된 파일의 크기를 byte단위로 반환
int size = is.available();
int readByte = 0;
byte[] bytes = new byte[size];
for(int i = 0; i < size;i++) {
readByte = is.read();
bytes[i] = (byte)readByte; //int 타입이라서 byte로 변환
}
System.out.println(new String(bytes)); // 아스키코드 이외에는 String클래스 생성자 이용해서 변환
/*
while(true) {
readByte = is.read();
System.out.println(readByte);
// EOF End Of File == -1
// 파일 데이터를 전부 읽어들이면 파일 read가 끝났다는걸 알려주는 값
if(readByte == -1) break;
System.out.println((char)readByte);
}
*/
System.out.println("size : "+size);
} catch (IOException e) { //FileNotFoundException의 상위객체
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f03_input_stream;
import java.io.*;
public class InputReadExample {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("C:\\Temp\\file.txt");
int readByte = 0;
byte[] bytes = new byte[100];
String data = "";
while(true) {
readByte = is.read(bytes); //readByte : 실제 읽은 byte크기
System.out.println("읽어들인 바이트 크기 : " + readByte);
if(readByte == -1) {
break;
}
data += new String(bytes,0,readByte);
}
System.out.println(data);
is.close();
}
}
package f03_input_stream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class InputReadSecondExample {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("c:\\Temp\\file.txt");
int available = is.available();
System.out.println("읽어 들일 수 있는 파일의 크기 : "+available);
byte[] bytes = new byte[available];
int readByte = is.read(bytes,0,bytes.length);
System.out.println(Arrays.toString(bytes));
System.out.println(readByte);
available = is.available();
System.out.println("읽어 들일 수 있는 파일의 크기 : "+available);
is.close();
// 한번 close된 스트림은 재사용 불가
}
}
package f03_input_stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ReadWriteExample {
public static void main(String[] args) {
// 앞에 기준이 없으면 현재 프로젝트가 기준
File file = new File("src\\f03_input_stream\\InputReadExample.java");
System.out.println(file.getAbsolutePath());
InputStream is = null;
try {
is = new FileInputStream(file);
int data;
OutputStream os = System.out;
while((data = is.read()) != -1) {
os.write(data);
}
os.flush();
// System.out 연결 종료 -> 이후 콘솔 통해서 출력 불가
os.close();
is.close();
System.out.println("출력!");
System.out.println("끝!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package f04_writer_reader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
public class WriterExample {
public static void main(String[] args) {
try {
Writer writer = new FileWriter("c:\\Temp\\data.hwp",true);
String str = "최기근님";
char[] chars = str.toCharArray();
System.out.println(Arrays.toString(chars));
writer.write(chars);
writer.write('A');
writer.write("점 입니다.");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package f04_writer_reader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("c:\\Temp\\data.hwp");
int readData;
char[] cBuf = new char[100];
while((readData = reader.read(cBuf)) != -1) {
System.out.println(readData);
System.out.println(new String(cBuf,0,readData));
}
/*
while(true) {
// 문자단위로 읽어옴. 반환하는 값은 char
readData = reader.read();
if(readData == -1) {
break;
}
System.out.print((char)readData);
}
*/
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f05_console;
import java.io.Console;
public class ConsoleExample {
public static void main(String[] args) {
// Console 객체는 실제 운영체제에서만 실행 가능 (export - Runnable JAR File)
// IDE에서는 확인할 수 없음
// java -jar console.jar
Console console = System.console();
System.out.println("아이디 : ");
// 사용자에게 콘솔을 통해서 한 문장 - 한라인 을 입력받는다.
String id = console.readLine();
System.out.print("비밀번호 : ");
// 한 라인의 문장을 입력 받되 사용자에게 노출하지 않음
char[] password = console.readPassword();
System.out.println("-----------------------");
String strPass = new String(password);
System.out.println("아이디는 : " + id);
System.out.println("비밀번호는 : "+strPass);
}
}
package f06_stream_reader_writer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class StreamWriterExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Temp\\fos.txt");
Writer writer = new OutputStreamWriter(fos);
String data = "바이트 출력 스트림을 문자기반 출력 스트림으로 변환~";
writer.write(data);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f06_stream_reader_writer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class StreamReaderExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("c:\\Temp\\fos.txt");
Reader reader = new InputStreamReader(fis);
char[] cBuf = new char[100];
int readData = reader.read(cBuf);
String result = new String(cBuf,0,readData);
System.out.println(result);
reader.close();//보조스트림 close하면 기반스트림도 자동close
InputStream is = System.in;
reader = new InputStreamReader(is);
readData = 0;
char[] cbuf = new char[100];
while((readData = reader.read(cbuf)) != -1) {
String data = new String(cbuf,0,readData);
System.out.println(data);
//console은 끝이 없음. quit로 시작하는 문자라면 break;
if(data.startsWith("quit")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package f07_buffered;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class BufferedExample {
public static void main(String[] args) throws Exception{
String originalPath = "C:\\Temp\\cat2.jpg";
File file = new File(originalPath);
FileInputStream fis = new FileInputStream(file);
// 내부의 버퍼를 두고 읽기 쓰기를 하여 속도를 향상시킨 보조 스트림
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(originalPath)
);
FileOutputStream fos = new FileOutputStream("C:\\Temp\\copy\\copy.jpg");
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Temp\\copy\\copy2.jpg")
);
long startTime, endTime;
startTime = endTime = 0;
int data;
startTime = System.nanoTime();
while((data = fis.read()) !=-1) {
fos.write(data); //이미지 정보가 복사됨
}
fos.flush();
fos.close();
endTime = System.nanoTime();
System.out.printf("file : %d ns %n",(endTime - startTime));
startTime = System.nanoTime();
while((data=bis.read())!=-1) {
bos.write(data);
}
bos.flush();
bos.close();
endTime = System.nanoTime();
System.out.printf("file : %d ns %n",(endTime - startTime));
System.out.println("copy 완료");
}
}
package f07_buffered;
import java.io.*;
public class BufferedCharExample {
public static void main(String[] args) {
try {
InputStream is = System.in;
Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);
BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Temp\\fos.txt",true)
);
String readData = "";
while((readData = br.readLine()) != null) {
writer.write(readData);
writer.newLine(); // 줄바꿈
writer.flush();
if(readData.startsWith("quit")) {
break;
}
}
writer.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f08_data_stream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataStreamExample {
public static void main(String[] args) {
// 기본 타입 8종료 + String(문자열)
// 바이트 기반 스트림을 기본타입을 편하게 작성할 수 있도록 변환
try {
String path = "primitive.txt";
FileOutputStream fos = new FileOutputStream(path);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeUTF("최기근");
dos.writeDouble(99.9);
dos.writeInt(100);
dos.writeBoolean(true);
dos.writeUTF("홍길동");
dos.writeDouble(100.0);
dos.writeInt(50);
dos.writeBoolean(false);
fos.flush();
dos.close();
DataInputStream dis = new DataInputStream(
new FileInputStream("primitive.txt")
);
//작성된 순서대로 읽어와야 지정한 데이터 형식으로 값을 사용할 수 있다.
String name = dis.readUTF();
int order = dis.readInt();
double score = dis.readDouble();
boolean isCheck = dis.readBoolean();
System.out.println("name : "+name);
System.out.println("order : "+order);
System.out.println("score : "+score);
System.out.println("isCheck : "+isCheck);
System.out.println("=====================");
name = dis.readUTF();
score = dis.readDouble();
order = dis.readInt();
isCheck = dis.readBoolean();
System.out.println("name : "+name);
System.out.println("order : "+order);
System.out.println("score : "+score);
System.out.println("isCheck : "+isCheck);
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package f09_print;
import java.io.*;
public class PrintExample {
public static void main(String[] args) {
try {
File file = new File("data.txt");
FileOutputStream fos = new FileOutputStream(file,true);
// PrintStream의 두번째 매개변수 : true - autoflush (기본값false)
PrintStream ps = new PrintStream(fos,true);
ps.println();
ps.println("[프린트 보조 스트림]");
ps.print(1);
ps.print("마치 ");
ps.println("콘솔에 출력하는 것 처럼~ ");
ps.println("데이터를 출력합니다!");
ps.printf("A의 값은 %d입니다.", 100);
ps.println();
ps.close();
// PrintWriter : 문자기반, 바이트기반스트림 둘 다 사용 가능
// 두번째 매개변수 : true - autoflush (기본값false)
PrintWriter pw = new PrintWriter(
new FileWriter(file,true),true
);
} catch (IOException e) {
e.printStackTrace();
}
}
}