Presentation is loading. Please wait.

Presentation is loading. Please wait.

어서와 Java는 처음이지! 제17장 파일입출력.

Similar presentations


Presentation on theme: "어서와 Java는 처음이지! 제17장 파일입출력."— Presentation transcript:

1 어서와 Java는 처음이지! 제17장 파일입출력

2 파일의 필요성

3 스트림(stream) 스트림(stream)은 “순서가 있는 데이터의 연속적인 흐름”이다.
스트림은 입출력을 물의 흐름처럼 간주하는 것이다.

4 스트림의 분류 입출력의 단위에 따라서 분류

5 바이트 스트림과 문자 스트림 바이트 스트림(byte stream)은 바이트 단위로 입출력하는 클래스
바이트 스트림 클래스들은 추상 클래스인 InputStream와 OutputStream에서 파생된다. 바이트 스트림 클래스 이름에는InputStream(입력)과 OutputStream(출력)이 붙는다. 문자 스트림(character stream)은 문자 단위로 입출력하는 클래스 이들은 모두 기본 추상 클래스인 Reader와 Write 클래스에서 파생된다. 문자 스트림 클래스 이름에는 Reader(입력)와 Writer(출력)가 붙는다.

6 바이트 스트림

7 문자 스트림

8 기본적인 메소드 InputStream 클래스 OutputStream 클래스 Reader 클래스 Writer 클래스
abstract int read() - 한 바이트를 읽어서 반환한다(0에서 255 사이의 정수). OutputStream 클래스 abstract void write(int b) - 한 바이트를 특정한 장치에 쓴다. Reader 클래스 abstract int read() - 한 문자를 읽어서 반환한다. Writer 클래스 abstract void write(int c) - 한 문자를 특정한 장치에 쓴다.

9 FileInputStream과 FileOutputStream
파일이 입출력 대상이 된다.

10 LAB: SimplePair 클래스 작성하기
public class CopyFile1 { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) in.close(); if (out != null) out.close();

11 LAB: SimplePair 클래스 작성하기
input.txt The language of truth is simple. Easier said than done. First think and speak. Translators, traitors. No smoke without fire. output.txt The language of truth is simple. Easier said than done. First think and speak. Translators, traitors. No smoke without fire.

12 예제 설명

13 LAB: 이미지 파일 복사하기 하나의 이미지 파일을 다른 이미지 파일로 복사하는 프로그램을 작성하여 보자.

14 LAB: SimplePair 클래스 작성하기
public class ByteStreamsLab { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); System.out.print("원본 파일 이름을 입력하시오: "); String inputFileName = scan.next(); System.out.print("복사 파일 이름을 입력하시오: "); String outputFileName = scan.next(); try (InputStream inputStream = new FileInputStream(inputFileName); OutputStream outputStream = new FileOutputStream(outputFileName)) { int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } System.out.println(inputFileName + "을 " + outputFileName + "로 복사하였습니다. ");

15 파일 문자 스트림

16 예제 public class CopyFile2 {
public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("input.txt"); outputStream = new FileWriter("output.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); if (outputStream != null) { outputStream.close();

17 스트림들은 연결될 수 있다.

18 예제 FileInputStream fileSt = new FileInputStream("sample.dat");
DataInputStream dataSt = new DataInputStream(fileSt); int i = dataSt.readInt();

19 버퍼 스트림

20 예제 inputStream = new BufferedReader(new FileReader("input.txt"));
outputStream = new BufferedWriter(new FileWriter("out put.txt"));

21 브릿지 스트림

22 문자 엔코딩 자바에서는 StandardCharsets 클래스 안에 각 엔코딩 방법이 StandardCharsets.UTF_8, StandardCharsets.UTF_16과 같이 상수로 정의되어 있다. String s = new String(100, StandardCharsets.UTF_8 ); 파일에서 읽을 때는 InputStreamReader 클래스를 사용한다.

23 예제 public class CharEncodingTest {
public static void main(String[] args) throws IOException { File fileDir = new File("input.txt"); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(fileDir), "UTF8")); String str; while ((str = in.readLine()) != null) { System.out.println(str); }

24 DataInputStream 과 DataOutputStream
DataInputStream 클래스는 readByte(), readInt(), readDouble()과 같은 메소드들을 제공한다. DataOutputStream 클래스는 writeByte(int v), writeInt(int v), writeDouble(double v)와 같은 메소드들을 제공한다.

25 예제 import java.io.*; public class DataStreamTest {
public static void main(String[] args) throws IOException { DataInputStream in = null; DataOutputStream out = null; try { int c; out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream("data.bin"))); out.writeDouble(3.14); out.writeInt(100); out.writeUTF("자신의 생각을 바꾸지 못하는 사람은 결코 현실을 바꿀 수 없다."); out.flush(); in = new DataInputStream(new BufferedInputStream( new FileInputStream("data.bin")));

26 예제 System.out.println(in.readDouble());
System.out.println(in.readInt()); System.out.println(in.readUTF()); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); 3.14 100 자신의 생각을 바꾸지 못하는 사람은 결코 현실을 바꿀 수 없다.

27 압축 파일 풀기 자바에서는 ZipInputStream을 이용하여서 ZIP 파일을 읽을 수 있다.

28 예제 압축 해제: eclipse.ini publ ic class ZipTest {
public static void main(String[] args) throws IOException { FileInputStream fin = new FileInputStream("test.zip"); ZipInputStream zin = new ZipInputStream(fin); ZipEntry entry = null; while ((entry = zin.getNextEntry()) != null) { System.out.println("압축 해제: " + entry.getName()); FileOutputStream fout = new FileOutputStream(entry.getName()); for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } zin.closeEntry(); fout.close(); zin.close(); 압축 해제: eclipse.ini

29 ObjectInputStream과 ObjectOutputStream
직렬화(serialization): 객체가 가진 데이터들을 순차적인 데이터로 변환하는 것

30 예제 import java.io.*; import java.util.Date;
public class ObjectStreamTest { public static void main(String[] args) throws IOException { ObjectInputStream in = null; ObjectOutputStream out = null; try { int c; out = new ObjectOutputStream(new FileOutputStream("object.dat")); out.writeObject(new Date()); out.flush(); in = new ObjectInputStream(new FileInputStream("object.dat")); Date d = (Date) in.readObject(); System.out.println(d); 객체를 직렬화하여서 쓴다.

31 예제 } catch (ClassNotFoundException e) { } finally { if (in != null) {
in.close(); } if (out != null) { out.close(); Mon Jul 13 13:39:47 KST 2015

32 파일 정보를 얻으려면 Path 클래스는 경로를 나타내는 클래스로서 “/home/work”와 같은 경로를 받아서 객체를 반환한다. (예) Path workDirectory = Paths.get("C:\home\work"); File 객체는 파일이 아닌 파일 이름을 나타낸다. (예) File file = new File("data.txt");

33 예제 public clas s FileTest {
public static void main(String[] args) throws IOException { String name = "c:/eclipse"; File dir = new File(name); String[] fileNames = dir.list(); // 현재 디렉토리의 전체 파일 리스트 for (String s : fileNames) { File f = new File(name + "/" + s); // 절대 경로로 이름을 주어야 함 System.out.println("==============================="); System.out.println("이름: " + f.getName()); System.out.println("경로: " + f.getPath()); System.out.println("부모: " + f.getParent()); System.out.println("절대경로: " + f.getAbsolutePath()); System.out.println("정규경로: " + f.getCanonicalPath()); System.out.println("디렉토리 여부:" + f.isDirectory()); System.out.println("파일 여부:" + f.isFile()); }

34 예제 =============================== 이름: .eclipseproduct
경로: c:\eclipse\.eclipseproduct 부모: c:\eclipse 절대경로: c:\eclipse\.eclipseproduct 정규경로: C:\eclipse\.eclipseproduct 디렉토리 여부:false 파일 여부:true

35 LAB: 이미지 파일에서 RGB 값 구하기 이미지 파일에서 픽셀 값을 읽어서 그레이스케일 이미지로 변환한 후에 저장하여 보자.

36 예제 public class RGB2Gray { BufferedImage myImage; int width;
int height; public RGB2Gray() { File ifile = new File("test.jpg"); try { myImage = ImageIO.read(ifile); } catch (IOException e) { e.printStackTrace(); } width = myImage.getWidth(); height = myImage.getHeight(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) {

37 예제 Color c = new Color(myImage.getRGB(x, y));
int red = (int) (c.getRed() * 0.299); int green = (int) (c.getGreen() * 0.587); int blue = (int) (c.getBlue() * 0.114); Color gray = new Color(red + green + blue, red + green + blue, red + green + blue); myImage.setRGB(x, y, gray.getRGB()); } File ofile = new File("gray.jpg"); try { ImageIO.write(myImage, "jpg", ofile); } catch (IOException e) { e.printStackTrace(); static public void main(String args[]) throws Exception { RGB2Gray obj = new RGB2Gray();

38 임의 접근 파일 임의 접근 파일은 파일에 비순차적인 접근을 가능하게 한다.
new RandomAccessFile("all.zip", "r");

39 LAB: 시저 암호 작성하기 로마의 유명한 정치가였던 쥴리어스 시저(Julius Caesar, B.C.)는 친지들에게 비밀리에 편지를 보내고자 할 때 다른 사람들이 알아보지 못하도록 문자들을 다른 문자들로 치환하였다

40 예제 public class CaesarCipher {
public static void main(String[] args) throws IOException { FileReader fr = new FileReader("input.txt"); BufferedReader br = new BufferedReader(fr); String plaintext = br.readLine(); System.out.println(CaesarCipher.encode(plaintext, 3)); System.out.println(CaesarCipher.decode( CaesarCipher.encode(plaintext, 3), 3)); fr.close(); } // 아래 코드는 가져왔습니다. public static String decode(String enc, int offset) { return encode(enc, 26 - offset);

41 예제 public static String encode(String enc, int offset) {
offset = offset % ; StringBuilder encoded = new StringBuilder(); for (char i : enc.toCharArray()) { if (Character.isLetter(i)) { if (Character.isUpperCase(i)) { encoded.append((char) ('A' + (i - 'A' + offset) % 26)); } else { encoded.append((char) ('a' + (i - 'a' + offset) % 26)); } encoded.append(i); return encoded.toString();

42 Wkh odqjxdjh ri wuxwk lv vlpsoh.
The language of truth is simple.

43 LAB: 행맨 게임 작성하기 빈칸으로 구성된 문자열이 주어지고 사용자는 문자열에 들어갈 글자들을 하나씩 추측해서 맞추는 게임이다. 현재의 상태: ____ 글자를 추측하시오: b 글자를 추측하시오: m 현재의 상태: __m_ 글자를 추측하시오: t 글자를 추측하시오: n 현재의 상태: n_m_ 글자를 추측하시오: a 현재의 상태: nam_ 글자를 추측하시오: e 현재의 상태: name

44 예제 public class Test { static String solution;
static boolean check(String s, StringBuffer a, char ch) { int i; for (i = 0; i < s.length(); i++) { if (s.charAt(i) == ch) a.setCharAt(i, ch); } for (i = 0; i < s.length(); i++) if (s.charAt(i) != a.charAt(i)) return false; return true;

45 예제 public static void main(String[] args) throws IOException {
char ch; Scanner sc = new Scanner(System.in); BufferedReader in = null; String[] words = new String[100]; int count = 0; in = new BufferedReader(new FileReader("sample.txt")); for (int i = 0; i < 100; i++) { String s = in.readLine(); if (s == null) break; words[i] = s; count++; } int index = (new Random()).nextInt(count); solution = words[index]; StringBuffer answer = new StringBuffer(solution.length()); for (int i = 0; i < solution.length(); i++) answer.append(' '); for (int i = 0; i < solution.length(); i++) { if (solution.charAt(i) != ' ') answer.setCharAt(i, '_');

46 예제 while (true) { // System.out.println("현재의 상태: " + solution);
System.out.println("현재의 상태: " + answer); System.out.printf("글자를 추측하시오: "); String c = sc.next(); if (check(solution, answer, c.charAt(0)) == true) break; }


Download ppt "어서와 Java는 처음이지! 제17장 파일입출력."

Similar presentations


Ads by Google