DataOutputStream

 

DataOutputStream은 자바의 기본 데이터 타입별로 출력하는 별도의 메소드들이 있으며,

기본 데이터를 매개 변수로 호출한다.

 

예를 들어, double 데이터를 출력하려면 writeDouble(double v)char 데이터를 출력하려면 writeChar(int v)를 이용한다. 문자열을 출력할 때는 writeUTF(String str)을 사용한다.

 

DataOutputStream을 이용해서 "C:\\test.txt" 파일에 여러 가지 자바 기본 타입별로 데이터를 기록하는 예제를 살펴 본 뒤, DataInputStream을 이용해서 나중에 읽어들이는 예제를 만들어 보도록 하겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<p>
import java.io.*;


public class DataOutputStreamEx {
    public static void main(String[] args){
        FileOutputStream f = null;
        DataOutputStream out = null;
         
         try {
            f = new FileOutputStream("C:\\test.txt");
            out = new DataOutputStream(f);
            out.writeBoolean(false); // 0x00 출력
            out.writeByte(0x33); // 0x33 출력
            out.writeShort(0x1234); // 0x1234 출력
            out.writeInt(0x5678); // 0x00005678 출력
            out.writeLong(0x12abcdef); // 0x0000000012abcdef 출력
            out.writeChar('c'); // 0x0063 출력
            out.writeDouble(0.12e-3); // long으로 변환 후 0x3f1f75104d551d69 출력
            out.writeFloat((float) 3.14); // int로 변환 후 0x4048f5c3 출력
            out.writeUTF("가나다라"); // UTF-8로 인코딩 후 0x000ceab080eb8298eb8ba4eb9dbc 출력
            out.close();
            f.close();
        }
        catch (IOException e) {
            System.out.println("입출력 오류");
        }
    }
}


</p>

 

 

 

DataInputStream 

 

이전에 DataOutputStream을 이용해서 test.txt파일에 바이너리 형태로 입력했던 자바 기본 데이터

타입 데이터를 DataInputStream을 이용해서 다시 읽어올 수 있다.

 

예를 들어, double 데이터를 읽으려면 readDouble()char 데이터를 읽을 때는 readChar()를 이용한다. 문자열을 읽을 때는 readUTF()을 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ReadData {
    public static void main(String[] args){
        FileInputStream f = null;
        DataInputStream in = null;
        try
        {
            f = new FileInputStream("C:\\test.txt"); 
            in = new DataInputStream(f); // 파일에 연결된 데이터 입력 스트림 생성
            System.out.println(in.readBoolean()); // 1바이트 읽어 boolean값 반환
            System.out.printf("%x\n",(byte)in.readByte()); // 1바이트 읽어 byte값 반환
            System.out.printf("%x\n",in.readShort()); // 2바이트 읽어 short값 반환
            System.out.printf("%x\n",in.readInt()); // 4바이트 읽어 int값 반환
            System.out.printf("%x\n",in.readLong()); // 8바이트 읽어 long값 반환
            System.out.println((char)in.readChar()); // 2바이트 읽어 char값 반환
            System.out.println(in.readDouble()); // 8바이트 읽어 double값 반환
            System.out.println(in.readFloat()); // 4바이트 읽어 float값 반환
            System.out.println(in.readUTF()); // UTF-8로 인코딩된 문자열 읽어 반환
            in.close();
            f.close();
        }
        catch (IOException e)
        {
            System.out.println("입출력 오류");
        }
    }
}

 

 

 

출처 : https://apphappy.tistory.com/69

반응형

성능 향상 보조 스트림이란?

 : 프로그램의 성능은 입출력이 가장 늦은 장치를 따라가게 되는데요.

예를 들어서 CPU 랑 메모리의 성능이 아무리 좋다고 해도 하드 디스크의 입출력 늦다면

프로그램의 실행 성능은 하드 디스크의 처리 속도에 따라 맞춰갑니다.

네트워크도 느린 네트워크 환경이라면 컴퓨터의 성능이 좋더라도 메신저 또는 게임의 속도가 느려집니다.

이에 대한 완전한 해결책은 없는데요, 프로그램이 입출력 소스와 직접 작업하는 대신에

중간에 메모리 버퍼와 작업함으로써 실행 성능을 어느 정도 향상 시킬 수는 있습니다.

BufferedInputStream 과 BufferedOutputStream은 바이트 기반의 성능 향상 보조 스트림이고,

BufferedReader 와 BufferedWriter는 문자 기반 성능 향상 스트림입니다.

 

BufferedInputStream과 BufferedReader :

 BufferedInputStream은 바이트 입력 스트림에 연결되어서 버퍼를 제공해주는 보조 스트림입니다.

BufferedReader는 문자 입력 스트림에 연결되어서 버퍼를 제공해주는 스트림입니다.

 

위의 스트림은 둘 다 입력 소스로부터 자신의 내부 버퍼 크기만큼 데이터를 미리 읽고 버퍼에 저장합니다.

생성자 매개값으로 준 입력 스트림과 연결되어 8918 내부 버퍼 사이즈를 갖습니다.

BufferedInputStream bis = new BufferedInputStream(바이트 입력 스트림); //  최대 8912 바이트

BufferedReader br = new BufferedReader(문자 입력 스트림); // 최대 8912 문자

 

스트림이 데이터를 읽어들이는 방법은 InputStream / Reader 와 갖습니다.

 

예제)

import java.io.BufferedInputStream;
import java.io.FileInputStream;


public class Example {
 public static void main(String[] args) throws Exception {
  long start = 0;
  long end = 0;
  
  FileInputStream fis1 = new FileInputStream("파일 경로/image.jpg");
  start = System.currentTimeMillis();
  while(fis1.read() != -1) {}
  end = System.currentTimeMillis();
  System.out.println("사용하지 않았을 때 걸린 시간: " + (end-start) + "ms");
  fis1.close();
  
  FileInputStream fis2 = new FileInputStream("C:/apache-tomcat-8.0.20/webapps/thisisjava/src/forest.jpg");
  BufferedInputStream bis = new BufferedInputStream(fis2);
  start = System.currentTimeMillis();
  while(bis.read() != -1) {}
  end = System.currentTimeMillis();
  System.out.println("사용했을 때 걸린 시간: " + (end-start) + "ms");
  bis.close();
  fis2.close();
 }
}
예제를 실행시켜보면 시간 차이가 꽤 많이 나는 것을 확인할 수 있습니다.


예제2)
예제2) BufferedReader / readLine()메서드를 추가적으로 가지고 있음. 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;


public class Example2 {
 public static void main(String[] args) throws Exception {  
  InputStream inputStream = System.in;
  Reader reader = new InputStreamReader(inputStream); 
  BufferedReader bufferedReader = new BufferedReader(reader);
  
  System.out.print("입력: ");
  String lineString = bufferedReader.readLine();
  
  System.out.println("출력: " + lineString); 
 }


}

BufferedOutPutStream :

바이트 출력 스트림에 연결되어서 버퍼를 제공해 주는 보조 스트림입니다.

BufferedWriter :

문자 출력 스트림에 연결되어 버퍼를 제공해주는 스트림입니다.

 

위 두 스트림은 프로그램에서 전송한 데이터를 내부에 두었다가 버퍼가 꽉 차면 버퍼의 모든

데이터들을 한번에 보냅니다.

BufferedOutputStream bufferedOutputStream

 = new BufferedOutputStream(바이트출력스트림); // 최대 8912바이트

BufferedWriter bufferedWriter

 = new BufferedWriter(문자출력스트림); // 최대 8912 문자

 

출력 방법은 OutputStream/ Writer 과 동일합니다.

예제)

성능차이를 보여주는 예제
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class Example {
 public static void main(String[] args) throws Exception {
  FileInputStream fileInputStream = null;
  FileOutputStream fileOutputStream = null;
  BufferedInputStream bufferedInputStream = null;
  BufferedOutputStream bufferedOutputStream = null;
  
  int data = -1;
  long start = 0;
  long end = 0;
  
  fileInputStream = new FileInputStream("파일 경로/image.jpg");
  bufferedInputStream = new BufferedInputStream(fis);
  fileOutputStream = new FileOutputStream("C:/Temp/forest.jpg");    
  start = System.currentTimeMillis();
  while((data = bufferedInputStream.read()) != -1) {
   fileOutputStream.write(data);
  }
  fileOutputStream.flush();
  end = System.currentTimeMillis();
  fileOutputStream.close();
  bufferedInputStream.close();
  fileInputStream.close();
  System.out.println("사용하지 않았을 때 걸린 시간: " + (end-start) + "ms");
  
  fileInputStream = new FileInputStream("C:/apache-tomcat-8.0.20/webapps/thisisjava/src/forest.jpg");
  bufferedInputStream = new BufferedInputStream(fis);
  fileOutputStream = new FileOutputStream("C:/Temp/forest.jpg");  
  BufferedOutputStream = new BufferedOutputStream(fileOutputStream);
  start = System.currentTimeMillis(); // 시작시간
  while((data = bufferedInputStream.read()) != -1) {
   BufferedOutputStream.write(data);
  }
  BufferedOutputStream.flush();
  end = System.currentTimeMillis(); // 종료시간
  BufferedOutputStream.close();
  fileOutputStream.close();
  bufferedInputStream.close(); 
  fileInputStream.close();
  System.out.println("사용했을 때 걸린 시간: " + (end-start) + "ms");
 }
}

 



출처: https://altongmon.tistory.com/274

반응형

'[ 개발 ] > Java' 카테고리의 다른 글

[Java] List와 ArrayList  (0) 2021.07.22
[Java] DataInputStream / DataOutputStream  (0) 2021.07.22
[Java] flush()와 close()  (0) 2021.07.22
[Java] 프로젝트에 이미지 폴더 넣는 방법  (0) 2021.04.16

FileWriter를 사용 후에는 flush()와 close()를 호출해야 한다.

 

- flush() : FileWriter 내부 버퍼의 내용을 파일에 writer한다. flush()를 호출하지 않는다면 내용이 버퍼에만 남고 파일에는 쓰이지 않는 상황이 나올 수 있다. 즉, 메소드는 버퍼에 데이터가 가득 차 있건 아니건, 버퍼에서 강제로 밀어내도록 하는 메소드이다.

 

- close() : FileWriter는 스트림을 이용하여 파일의 내용을 읽어들인다. 이때 close()를 호출하여 스트림을 닫으면 그 스트림을 다시 이용하여 파일에 쓰는 것이 불가능하다.

 

파일은 파일시스템이나 기타 다른 곳에 있으므로 이 내용을 스트림으로 읽어 들이는데 메모리를 소모한다. 작업이 끝나면 close()를 호출하여 스트림을 닫아 종료된 작업에 대해 메모리를 확보해야 한다..

 

 

출처 : https://yangbox.tistory.com/64

반응형

 

web.xml을 켤때만 빨간줄이 생김!!

 

cvc-id.3: A field of identity constraint 'web-app-servlet-name-uniqueness' matched element 'web-
 app', but this element does not have a simple type.

 

이유가 궁금해서 찾아보니 

태그에 있는 xmlns="http://java.sun.com/xml/ns/javaee"  에서 java를 대문자로 바꿔주면 빨간줄 사라짐!

 

요렇게~!

 

 

반응형

Content-Type 헤더

Content-Type은 말그대로 HTTP 메시지(요청과 응답 모두)에 담겨 보내는 데이터의 형식을 알려주는 헤더입니다. 세상에 모든 브라우저와 모든 웹서버가 그렇다고는 말할 수 없겠지만 대부분의 HTTP 표준 스펙을 따르는 브라우저와 웹서버는 우선적으로 저 Content-Type 헤더를 기준으로 HTTP 메시지에 담긴 데이터를 분석하고 파싱할것입니다.

 

만약 Content-Type헤더가 없다면 데이터를 전송하는쪽(브라우저나 웹서버)에서는 특정한 형식의 데이터일지라도 받아들이는 쪽에서는 단순 텍스트 데이터라고밖에 생각할 수 없을것이며, 이를 분석하고 파싱하는 프로그램을 별도로 작성해주어야겠지요.

 

그러나 여기서 알아야할 점은 HTTP 요청의 경우 GET방식인 경우에는 무조건 URL 끝에 쿼리스트링으로 key=value 형식으로 날아가기 때문에 굳이 Content-Type 헤더가 필요 없습니다. 웹서버 입장에서도 요청메시지의 METHOD가 GET이면 key=value 형식의 데이터라는것을 유추할 수 있기 때문입니다.

 

따라서 Content-Type은 POST나 PUT처럼 메시지 BODY에 데이터를 싣어 보낼때 중요합니다. 예를 들어 브라우저를 기준으로 설명하자면 AJAX를 통해 json 형식의 데이터를 전송하는 경우 Content-Type 값을 application/json 으로 지정하여 보낼 수 있고 <form>태그를 통해 첨부파일 등을 전송하는 경우라면 브라우저가 자동으로 Content-Type울 multipart/form-data로 설정하여 요청 메시지를 보낼것입니다.

 

 

Accept 헤더

Accept 헤더의 경우에는 브라우저(클라이언트) 에서 웹서버로 요청시 요청메시지에 담기는 헤더입니다. 이 Accept헤더는 자신에게 이러한 데이터 타입만 허용하겠다는 뜻입니다. 즉 브라우저가 요청 메시지의 Accept 헤더 값을 application/json이라고 설정했다면 웹서버에게 나는 json 데이터만 처리할 수 있으니 json 데이터 형식으로 응답을 돌려줘 라고 말하는것과 같습니다. 물론 그것을 지키든 지키지 않든 하는것을 웹서버 마음이겠지만요.

 

 

정리

Content-Type 헤더와 Accept 헤더 둘 다 데이터 타입(MIME)을 다루는 헤더이지만 Content-Type 헤더는 현재 전송하는 데이터가 어떤 타입인지에 대한 설명이고 Accept 헤더는 클라이언트가 서버에게 웬만하면 데이터 전송할때 이러이러한 타입으로 가공해서 보내라 라고 하는것과 같습니다.



출처: https://dololak.tistory.com/630 [코끼리를 냉장고에 넣는 방법]

 

* 미디어 타입

과거에는 MIME type으로 불렸지만 지금은 "media type"으로 사용한다. 때때로는  "content type"이라고도 불리기도 한다. MIME type은 파일의 형식을 나타내는 문자열로 파일과 같이 송신되는데 content의 형식을 나타내기 위해 사용한다. 예를 들면 오디오 파일은 audio/ogg로 그림 파일은  image/png로 분류할 수 있다.

윈도우에서 사용하는 파일 확장자와 동일한 역할을 한다. MIME type이라는 명칭은 이메일에서 사용된 MIME standard에서 유래 됐다.

 

반응형

+ Recent posts