package fileStream; // 패키지는 소문자로 시작
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
public class EX1 {
public static byte [] readFileWithList(String fileName) throws IOException{
try {
FileInputStream fis1 = new FileInputStream("InputFolder/" + fileName);
LinkedList<Byte> lst = new LinkedList<Byte>();
while(true) {
int data = fis1.read();
if(data == -1) {
break;
} else {
lst.add((byte)data);
}
}
fis1.close();
byte[] arr = new byte[lst.size()];
for(int i = 0; i < arr.length; i++) {
arr[i] = lst.get(i);
// get = list의 인덱싱
}
// list.toArray()는 Object 배열이기에, 받는 쪽에서 형변환 처리를 해주는게 좋음
return arr;
} catch (IOException e) {
throw e;
}
}
public static void writeFile(String fileName, byte[] arr) throws IOException {
try {
FileOutputStream fos1 = new FileOutputStream("OutputFolder/WRITEFILE.txt");
fos1.write(arr);
fos1.close();
} catch (IOException e) {
// FileNoutFoundException을 지운 이유?
// 파일을 만들어주기 때문에 파일을 못 찾지 않고,
// 파일을 기록할 수 없다가 뜰 것임
throw e;
}
}
public static void main(String[] args) {
// 작업할 위치 설정
File dir1 = new File("InputFolder");
File dir2 = new File("OutputFolder");
dir1.mkdir();
dir2.mkdir();
try {
byte[] arr = readFileWithList("READFILE.txt");
writeFile("WRTIEFILE.txt", arr);
} catch (IOException e) {
System.out.println(e);
}
}
}