package Week03.day0722;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;
class Driver{
private String name;
private int licenceNo;
private HashMap cars = new HashMap();
private int hisMaxIndex = 3;
private int hisIndex;
private Accident[] history = new Accident[hisMaxIndex]; // 사고이력
private int cnt = 0;
Driver() {
}
Driver(String name, int licenseNo) {
this.name = name;
this.licenceNo = licenseNo;
}
public void addCar(String carNo, String type, int volume) throws Exception { // HashMap
// 소유자동차를 추가한다
// - carNo(차량번호), type(차종), volume(배기량)
// - carNo를 key로 HashMap에 추가한다
// - 동일한 자동차를 추가할 수 없다
// - HashMap에는 Key는 String, Value에는 Car class만 추가가능하다 // 제네릭스 추가.
int New_carNo = (Integer.parseInt(carNo.substring(4, 7)));
cars = new HashMap(New_carNo);
String carInfo = carNo + "/" + type + "/" + volume;
if(cars.containsKey(New_carNo)) {
throw new Exception("동일한 자동차는 추가 될 수 없습니다.");
}
else{
cars.put(New_carNo, carInfo);
}
}
public void printCars() { // 소유하고 있는 Car를 출력한다- carNo/type/volume를 출력한다 // HashMap
Set set = cars.entrySet();
Iterator it = set.iterator();
while(it.hasNext()) {
Entry e = (Entry) it.next();
System.out.println(e.getValue());
}
}
public void addAccident(Accident ac) { // arraylist
// 사고이력을 추가한다
// - 사고이력 추가 시 Array size를 넘어설 경우 Array size를 2배로 늘려서 추가한다
// - 사고이력 추가 시 Car는 Driver가 소유하고 있는 Car만 추가가능 하다
if(hisIndex == hisMaxIndex-1) {
Accident[] old = history; //old배열에 기존배열 데이터를 담아둔다.
hisMaxIndex = 2 * hisMaxIndex;
history = new Accident[hisMaxIndex];
for(int i = 0; i < hisIndex; i++) {
history[i] = old[i];
}
}
history[this.hisIndex++] = ac;
}
public void printAccident() { // 사고이력을 출력한다 . arraylist
System.out.println("======사고이력======");
for(int i=0; i<this.hisIndex; i++) {
Car info = history[i].getCar();
System.out.println("사고장소 = " + history[i].getLocation() +", 사고일자 = " + history[i].getDate()+", 사고차량 = " + info.getCarNo() + "/" + info.getType() + "/" + info.getVolume());
}
}
}
class Accident extends Driver{
private String location; // 위치
private String date; // 사고일자
private Car car; // 사고차량
Accident(){
}
Accident(String location, String date, Car car){
this.location = location;
this.date = date;
this.car = car;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
class Car extends Accident{
private String carNo;
private String type;
private int volume;
Car(String carNo, String type, int volume){
this.carNo = carNo;
this.type = type;
this.volume = volume;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public boolean equals(Object obj) {
if (obj != null && obj instanceof Accident) { // obj가 Accident의 Instance
String tmp = carNo + type + volume;
String tmp2 = ((Car)obj).getCarNo() + ((Car)obj).getType() + ((Car)obj).getVolume();
return tmp.equals(tmp2);
} else {
return false;
}
}
}
public class practice0722 {
public static void main(String[] args) throws Exception {
Car cr = new Car("32다4931", "소형차", 3000);
cr.addCar("32다4931", "소형차", 3000);
// try {
// cr.addCar("32다4931", "소형차", 3000); // 오류메세지 출력용
// } catch (Exception e) {
// e.printStackTrace();
// }
cr.printCars();
Accident ac = new Accident("로타리사거리", "20190228", cr);
cr.addAccident(ac);
cr.printAccident();
}
}
--------------------------------------------------------------------------
/* Stream */
1. 데이터의 흐름, 통로(파일/키보드/메모리/Network)
2. 데이터를 읽고 쓰기 위한 공통된 방법을 제공
3. 장치마다 연결할 수 있는 각각의 Stream 이 존재
package Week03.day0722;
import java.io.File;
public class FileEx1 {
public static void main(String[] args) {
File f = new File("C:\\Temp\\practice0722.java");
String fileName = f.getName();
int pos = fileName.lastIndexOf("."); // 확장자 구분자 위치
System.out.println("경로를 제외한 파일이름 - " + f.getName()); // 경로를 제외한 파일이름 - practice0722.java
System.out.println("확장자를 제외한 파일이름 - " + fileName.substring(0,pos)); // 확장자를 제외한 파일이름 - practice0722
System.out.println("확장자 - " + fileName.substring(pos+1)); // 확장자 - java
System.out.println("경로를 포함한 파일이름 - " + f.getPath()); // 경로를 포함한 파일이름 - C:\Temp\practice0722.java
System.out.println("파일의 절대경로 - " + f.getAbsolutePath()); // 파일의 절대경로 - C:\Temp\practice0722.java
System.out.println("파일이 속해 있는 디렉토리 - " + f.getParent()); // 파일이 속해 있는 디렉토리 - C:\Temp
System.out.println();
System.out.println("File.PathSeparator - " + File.pathSeparator); // File.PathSeparator - ; // String용
System.out.println("File.pathSeparator Char - " + File.pathSeparatorChar); // File.pathSeparator Char - ; // Char용
System.out.println("File.separator - " + File.separator); // File.separator - \ // String용
System.out.println("File.separatorChar - " + File.separatorChar); // File.separatorChar - \ // Char용
}
}
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.File;
public class FileEx2 {
public static void main(String[] args) {
File f = new File("C:\\Temp");
if(!f.exists() || !f.isDirectory()) {
System.out.println("유효하지 않은 디렉토리입니다.");
System.exit(0);
}
File[] files = f.listFiles();
for(int i=0; i<files.length; i++) {
String fileName = files[i].getName();
System.out.println(files[i].isDirectory() ? "[" + fileName+"]" : fileName);
}
} // main
}
//출력값
//[AUtempR]
//practice0722.java
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.File;
import java.util.ArrayList;
public class FileEx3 {
//디렉토리와 파일을 불러와서 출력 + 재귀호출
static int totalFiles = 0;
static int totalDirs = 0;
public static void main(String[] args) {
File dir = new File("C:\\Temp");
if(!dir.exists() || !dir.isDirectory()) {
System.out.println("유효하지 않은 디렉토리입니다.");
System.exit(0);
}
printFileList(dir);
System.out.println();
System.out.println("총" + totalFiles + "개의 파일");
System.out.println("총" + totalDirs + "개의 디렉토리");
}
public static void printFileList(File dir) {
System.out.println(dir.getAbsolutePath() + " 디렉토리");
File[] files = dir.listFiles(); // dir내부 파일목록(디렉토리 포함)
ArrayList subDir = new ArrayList();
//내부 파일목록 출력
for(int i=0; i<files.length; i++) {
String filename = files[i].getName();
if(files[i].isDirectory()) {
filename = "[" + filename + "]"; // 디렉토리이면 []로 표시
subDir.add(i+"");
}
System.out.println(filename);
}
int dirNum = subDir.size();
int fileNum = files.length - dirNum;
totalFiles += fileNum;
totalDirs += dirNum;
System.out.println(fileNum + "개의 파일, " + dirNum + "개의 디렉토리");
System.out.println();
for(int i=0; i<subDir.size(); i++) {
int index = Integer.parseInt((String)subDir.get(i));
printFileList(files[index]); //디렉토리인 것에 대해 재귀호출
}
}
}
//출력값
//C:\Temp 디렉토리
//[AUtempR]
//practice0722.java
//1개의 파일, 1개의 디렉토리
//
//C:\Temp\AUtempR 디렉토리
//0개의 파일, 0개의 디렉토리
//
//
//총1개의 파일
//총1개의 디렉토리
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderWriterTest {
public static void main(String[] args) {
//Stream - 문자
boolean append = false;
int i, len = 0;
String strFile01 = "C:\\Temp\\practice0722.java";
String strFile02 = "C:\\Temp\\0722실습.txt";
FileReader in = null;
FileWriter out = null;
try { // 파일을 Character input Stream 에 연결한다.
in = new FileReader(new File(strFile01));
//파일은 Character output Stream에 연결한다.
out = new FileWriter(strFile02, append);
} catch(FileNotFoundException e) {
System.out.println(e);
} catch(IOException e) {
System.out.println(e);
}
try { // input Stream에 연결된 파일 내용을 읽는다.
while((i=in.read())!=-1){ // 1 char 읽어서
//Output Stream에 연결된 파일에 내용을 출력한다.
out.write(i);
//총 읽은 byte수를 count한다.
len++;
}
in.close(); out.close(); System.out.println(len + " bytes are copied..."); // 4255 bytes are copied...
} catch(IOException e) {
System.out.println(e);
}
}
}
--------------------------------------------------------------------------
/* FileInputStream */
1. FileInputStream(File file) : 주어진 File객체가 가리키는 파일을 바이트 스트림으로 읽기위한 FileInputStream 객체를 생성
2. FileInputStream(String name) : 주어진 이름이 가리키는 파일을 바이트 스트림으로 읽기위한 FileInputStream 객체를 생성
3. 파일과 직접 연결하여 사용
/* FileOutputStream */
1. FileOutputStream(File file) : 주어진 File객체가 가리키는 파일을 바이트 스트림으로 읽기위한 FileOutputStream 객체를 생성
2. FileOutputStream(String name) : 주어진 이름이 가리키는 파일을 바이트 스트림으로 읽기위한 FileOutputStream 객체를 생성
- 기존 파일이 존재할때는 덮어씀.
3. FileOutputStream(String name, boolean append) : 주어진 이름이 가리키는 파일을 바이트 스트림으로 쓰기 위한 FileOutputStream 객체를 생성.
- append 값에 따라 새로운 파일을 생성하거나 또는 기존의 내용에 추가
package Week03.day0722;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileInputOutputStream {
public static void main(String[] args) {
//Stream - byte
boolean append = false;
int i, len = 0;
String strFile01 = "C:\\Temp\\practice0722.java";
String strFile02 = "C:\\Temp\\0722실습.txt";
InputStream in = null;
OutputStream out = null;
try { // 파일을 Character input Stream 에 연결한다.
in = new FileInputStream(new File(strFile01));
//파일은 Character output Stream에 연결한다.
out = new FileOutputStream(strFile02, append);
} catch(FileNotFoundException e) {
System.out.println(e);
}
try {
while((i=in.read())!=-1){ // 1byte를 읽어서
System.out.println(i); // 1byte이므로 한글은 깨짐.
out.write(i); // 1byte를 쓴다.
len++;
}
in.close(); out.close(); System.out.println(len + " bytes are copied..."); // 4703 bytes are copied...
} catch(IOException e) {
System.out.println(e);
}
}
}
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteArrayInputOutputTest {
public static void main(String[] args) throws IOException {
//배열 입출력 Stream = Byte
int ch;
byte arr[] = { (byte) 'J', (byte)'a', (byte)'v', (byte)'a', (byte)'!'};
//배열 arr을 입력버퍼로 사용하는 객체 생성
ByteArrayInputStream in = new ByteArrayInputStream(arr);
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileOutputStream outFile = new FileOutputStream("0722실습.txt");
//배열 arr의 내용을 읽는다.
while((ch=in.read())!=-1) {
//출력Stream의 버퍼에 출력합니다.
out.write(ch);
System.out.println(" read:[" + (char)ch + "]" + ", write:[" + out.toString() + "]" + out.size() + ", available:" + in.available());
}
System.out.println("String: " + out.toString());
byte arrOut[] = out.toByteArray();
for(int i=0; i<arrOut.length; i++) {
System.out.println(arrOut[i]+",");
}
//출력버퍼의 내용을 인자로 주어진 OutputStrema(File)에 출력합니다.
out.writeTo(outFile);
}
}
//출력값
//read:[J], write:[J]1, available:4
//read:[a], write:[Ja]2, available:3
//read:[v], write:[Jav]3, available:2
//read:[a], write:[Java]4, available:1
//read:[!], write:[Java!]5, available:0
//String: Java!
//74,
//97,
//118,
//97,
//33,
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
public class CharArrayReadeWriterTest {
public static void main(String[] args) throws IOException {
//배열 입출력 Stream - 문자
int ch;
//input Stream 으로 사용할 char 배열
char arr[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'J', 'a', 'v', 'a', '!'};
CharArrayReader in;
CharArrayWriter out;
//주어진 문자 배열의 주어진 부분을 입력 버퍼로 사용하는 input Stream을 생성
in = new CharArrayReader(arr, 7, 5); //7번째 index부터 5개를 read.
//디폴트 크기의 문자 배열을 출력 버퍼로 사용하는 output Stream을 생성
out = new CharArrayWriter();
while((ch=in.read())!=-1) {
//출력버퍼에 쓰기
out.write(ch);
System.out.println(" read:[" + (char)ch + "]" + ", write:[" + out.toString() + "]" + out.size());
}
//출력버퍼에 쓰여진 내용을 문자열로 리턴한다.
System.out.println("String: " + out.toString());
//출력버퍼를 char 배열로 리턴
char arrOut[] = out.toCharArray();
for(int i=0; i<arrOut.length; i++) {
System.out.println(arrOut[i]+",");
}
}
}
//출력값
//read:[J], write:[J]1
//read:[a], write:[Ja]2
//read:[v], write:[Jav]3
//read:[a], write:[Java]4
//read:[!], write:[Java!]5
//String: Java!
//J,
//a,
//v,
//a,
//!,
--------------------------------------------------------------------------
package Week03.day0722;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
public class StringReaderWriterTest {
public static void main(String[] args) throws IOException {
//문자열 입출력 Stream
int ch;
//입력 버퍼로 사용할 문자열
String s = "Hello, Java!";
//String s를 입력 Stream으로 하는 StringReader객체생성
StringReader in = new StringReader(s);
//주어진 크기의 문자열 Buffer를 포함하고 있다.
StringWriter out = new StringWriter(s.length() /2 );
//주어진 개수만큼 건너뛴다. index를 J로 이동
in.skip(7);
while((ch=in.read())!=-1){
out.write(ch);
//출력함에 따라 출력버퍼의 size는 늘어난다.
System.out.println("read:[" + (char)ch + "]" + ", write: [" + out.toString() + "]" + out.getBuffer().length());
}
//Java!
System.out.println(" out : " + out.toString());
//StringWriter의 내부출력버퍼의 내용을 반전시킴. Java!
out.getBuffer().reverse();
System.out.println(" out : " + out.toString());
in = new StringReader(out.toString());
//Char 배열 출력 Stream 생성
CharArrayWriter out2 = new CharArrayWriter();
while((ch=in.read())!=-1) {
out2.write(ch);
System.out.println("read : [" + (char)ch + "]" + ", write : [" + out2.toString() + "]" + out2.size());
}
//CharArrayWriter Stream에 쓰여진 내용을 StringWriter Stream에 쓴다.
//기존에 쓰여진 부분은 append 된다.
out2.writeTo(out);
//문자열 output Stream에 append된 결과 출력
System.out.println(" out: " + out.toString());
System.out.println(" out2: " + out2.toString());
}
}
//출력값
//read:[J], write: [J]1
//read:[a], write: [Ja]2
//read:[v], write: [Jav]3
//read:[a], write: [Java]4
//read:[!], write: [Java!]5
// out : Java!
// out : !avaJ
//read : [!], write : [!]1
//read : [a], write : [!a]2
//read : [v], write : [!av]3
//read : [a], write : [!ava]4
//read : [J], write : [!avaJ]5
// out: !avaJ!avaJ
// out2: !avaJ