api. io.charstream
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test01 {
public static void main (String[] args) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("output.log"));
bw.write("이게 마지막이다");
bw.newLine(); // 다음줄로 이동
bw.write("배고프다");
bw.newLine();
bw.write("뭐가 문제야 대체");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bw !=null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
생성파일
파일내용
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test02 {
public static void main(String[] args) {
File f = new File("output.log");
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)))) {
String str = "";
str = br.readLine();
System.out.println(str);
str = "";
char[] c = new char[10];
while(true) {
int n = br.read(c);
System.out.println(n);
if (n == -1) {
break;
}
str += new String(c ,0,n);
}
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
출력화면
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("output.log");
Scanner sc = new Scanner(f); // "output.log" 파일의 내용 f를 읽어오기
System.out.println(sc.nextLine()); // 줄 단위
System.out.println(sc.next()); // 띄어쓰기 단위
System.out.println(sc.next());
System.out.println(sc.next());
System.out.println(sc.next());
}
}
출력화면
api.io.singlebyte
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Test01 {
public static void main(String[] args) {
//파일 입출력
// - 파일 열기 - 입력
// - 파일 저장 - 출력
//파일 저장
File target = new File("files");
try {
if(!target.exists()) {
target.mkdirs();
target = new File(target,"single.txt");
if(!target.exists()) {
target.createNewFile();
}
}
} catch(IOException e) {
e.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(target);
// CPU -> out -> target -> 실제 파일
} catch ( FileNotFoundException e) {
e.printStackTrace();
}
try {
if(out != null) {
out.write(65);
out.write(66);
out.write(67);
out.write('D');
}
}catch(IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
}
}
}
// == 동일
File target = new File("files");
OutputStream out = null;
try {
if(!target.exists()) {
target.mkdirs();
}
target = new File(target,"single.txt");
if(!target.exists()) {
target.createNewFile();
}
out = new FileOutputStream(target);
out.write(65);
out.write(66);
out.write(67);
out.write('D');
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(out != null) {
out.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
콘솔창에 출력되지 않음
파일에 입력
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test03 {
public static void main(String[] args) {
//파일 열기
File target = new File("files","single.txt");
InputStream in = null;
try {
in = new FileInputStream(target);
// 실제 파일 -> target -> in -> CPU
}catch(FileNotFoundException e) {
e.printStackTrace();
}
// .read() - 1byte 단위로 데이터를 읽어오는 메소드
try {
while(true) {
int n = in.read();
System.out.println(n);
//더이상 데이터를 읽어올수 없을때는 -1을 읽어온다...
if(n == -1) {
break;
}
}
}catch(IOException e) {
e.printStackTrace();
}
try {
in.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
출력화면
Exercise 1
이미지파일 읽어서 복사하기
단, singlebyte를 이용해 파일을 복사할 것
파일은 자유
// 1
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.IIOException;
public class Test04 {
public static void main(String[] args) throws IOException {
File a = new File("files", "ort.png");
File b = new File("files", "ort_copy.png");
InputStream in = new FileInputStream(a); // 입력 통로
OutputStream out = new FileOutputStream(b); // 출력 통로
//[single.txt] -> a -> in -> CPU -> out -> b -> [target.txt]
while (true) {
int n = in.read();
if (n == -1) {
break;
}
out.write(n);
}
in.close();
out.close();
System.out.println("처리완료");
}
}
파일 복사 후 콘솔창엔 '처리완료' 메세지 띄움
//2
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test04a {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("C:\\Users\\Administrator\\JAVA\\Workspace\\API27\\files\\ort.PNG");
fos = new FileOutputStream("C:\\Users\\Administrator\\JAVA\\Workspace\\API27\\files\\ort2.PNG");
byte[] buffer = new byte[4096]; // 4KB, 코드로 변환된 문자를 저장할 공간
int len = 0; // 읽은 바이트수
int readCount = 0; // 읽은 횟수
while(true){
len = fis.read(buffer); //읽을파일경로 (원하는 바이트 수로)
if(len == -1){
break;
} else {
fos.write(buffer);// 내용, 기록할 내용의 시작위치, 기록할 내용의 끝위치 //쓸위치.쓴다(원하는 바이트수로)
readCount++;
if(readCount % 20 == 0){
}
}
}
File file = new File("C:\\Users\\Administrator\\JAVA\\Workspace\\API27\\files\\ort.PNG");
if (file.exists()) {
System.out.println(file.getName() + " 파일 복사 완료");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try { fis.close(); } catch (IOException e) { }
try { fos.close(); } catch (IOException e) { }
}
}
}
파일 복사 후 콘솔창엔 '복사 완료' 메세지 띄움
//3
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test04c {
public static void main(String[] args) {
try {
// 파일 객체 생성
File img = new File("C:\\Users\\Administrator\\JAVA\\Workspace\\API27\\files\\ort.PNG");
File copy = new File("C:\\Users\\Administrator\\JAVA\\Workspace\\API27\\files\\copy.PNG");
// 스트림 생성
FileInputStream fis = new FileInputStream(img);
FileOutputStream fos = new FileOutputStream(copy);
// 버퍼 생성
byte[] buf = new byte[5000];
// 파일 복사
int readData = 0;
// 파일의 끝에 도달할 때까지 버퍼의 크기만큼 읽어들임 (버퍼의 0번째 인덱스부터 버퍼 크기만큼)
while((readData = fis.read(buf, 0, buf.length)) != -1) {
fos.write(buf, 0, readData); // 쓰기
}
// 스트림 닫기
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
파일 생성 결과