자바에서 파일 읽고 쓰기..

    InputStream 과 OutputStream 사용



input ≒ read

output ≒ write



byte 단위

char 단위 (2byte)

읽기

InputStream

Reader

쓰기

OutputStream

Writer


ㅁ InputStream 의 메소드 두개만 알자

  int read() : 한 바이트씩 읽는다 (리턴형 int 는 데이터다..).. 느리지.. 느려..

  int read(byte[] b) : 한번에 왕창 읽는다 (데이터가 byte[] 배열에 저장. 리턴형 int 는 카운터다..)


ㅁ OutputStream 의 메소드

  void write(byte[] b) : b 바가지로 퍼다가 한번에 처리한다

  void write(byte[] b, int off, int len) : byte[] 배열에 저장, off 는 시작위치 어디부터, len 은 몇개

  void write(int b)


************************************************************************************


코드 예) 웹에서 파일 읽어서 복사

import java.io.*;
import java.net.*;

public class FileCopy1 {

 public static void main(String[] args) throws Exception{
 
  String path = "http://www.penfo.co.kr/bbs/data/free/emma201thumb.jpg";

  URL url = new URL(path);
  InputStream fin = url.openStream();
  System.out.println(fin.getClass().getName());
 
  OutputStream fos = new FileOutputStream("copy.jpg");
 
  while(true){
   int data = fin.read();
   if(data == -1){
    System.out.println("파일 끝났음");
    break;
   }
   fos.write(data);  
  }
  fin.close();
  fos.close();
 }

}

************************************************************************************


코드 예) 그냥 파일 읽고 복사하기

import java.io.*;

public class FileCopy2 {

 public static void main(String[] args) throws Exception{

  InputStream fin = new FileInputStream("aaa.txt");
  OutputStream fos = new FileOutputStream("ccc.txt");
 
  byte[] buffer = new byte[1024];
 
  while(true){
   int count = fin.read(buffer);
   System.out.println("COUNT : " + count);
   if(count == -1){
    System.out.println("더이상 읽은 데이터가 없다.");
    break;
   }
   fos.write(buffer, 0, count);
  }
  fin.close();
  fos.close();
 }

}


*************************************************************************************


파일 경로나 파일 검색 프로그램 기초 코딩 예)


import java.io.*;

public class FileSearcher {

 public void findAll(String folderName){
  File file = new File(folderName);
 
  File[] files = file.listFiles();
 
  for(int i=0; i<files.length; i++){
   if(files[i].isDirectory() == true){
    System.out.println("FOLDER : " + files[i].getAbsolutePath());
   }
   else{
    System.out.println("FILE : " + files[i].getName());
   }
  }
 }
 public static void main(String[] args) {

  FileSearcher searcher = new FileSearcher();
  searcher.findAll("C:\\Documents and Settings\\Axl\\My Documents\\Study\\JavaStudy");
 
 }

}

이걸 바탕으로 조금 수정해보자.....


'기타 > Old' 카테고리의 다른 글

東京 狐の嫁入  (0) 2008.06.03
2008년 4월 신작 자막 제작자 정리표  (0) 2008.06.03
JDom을 이용하여 XML생성하기  (0) 2008.06.02
JDom 관련 문서  (0) 2008.06.02
JDOM으로 XML 프로그래밍 단순화 하기 (한글)  (0) 2008.06.02

+ Recent posts