상세 컨텐츠

본문 제목

자바 io

프로그래밍/JAVA

by 라제폰 2009. 1. 23. 17:08

본문

자바 입출력의 개요 (1)

--------------------------------------------------------------------------------

- java.io패키지는 사용자가 작성한 자바 프로그램에서 입력 출력을 있도록 도와주는 클래스    들을 포함하고 있다.

- java.io.InputStream클래스를 중심으로 하는 입력 스트림과

- java.io.OutputStream클래스를 중심으로 하느 출력 스트림이 있다.

 

1 InputStream 클래스

 모든 입력 스트림 클래스의 슈퍼 클래스로 기본적인 입력에 관련된 메쏘드들을 제공한다. 클래스는 abstract 클래스로 new 연산자나 newInstance() 메쏘드를 이용하여 직접적으로 객체를 성할 없다.

 

멤버

int available() - 블록킹이 되지 않고 읽을 있는 바이트의 수를 넘겨준다.

void close() - 스트림을 닫는다.

void mark( int readlimit ) - 스트림내의 현재 위치에 표시를 해둔다.

boolean markSupported() - 스트림이 마크/리셋을 지원하는 가를 판별한다.

abstract int read() - 스트림으로부터 바이트를 읽어서 넘겨준다.

int read( byte b [] ) - 스트림으로부터 바이트의 배열만큼 읽어서 b에 채워 준다.

int read( byte b[] , int off, int length ) - 스트림으로부터 length만큼 읽어서 b의 off부터 채워줌.

void reset() - 최근에 마크된 위치로 스트림을 재위치시킨다.

long skip( long n ) - 지정한 바이트 수만큼 건너뛴다.

 

2 OutputStream 클래스

  클래스는 모든 출력 스트림 클래스들의 슈퍼 클래스이며, abstract 클래스라 new 연산자나 newInstance()메쏘드를 이용해서 직접적으로 객체를 생성할 없다. 대부분의 출력 스트림 클래스는 클래스와 멤버가 비슷하다.

 

멤버

void close() - 스트림을 닫는다. 스트림과 관련되었던 시스템자원도 모두 돌려준다.

void flush() - 스트림에 의해 쓰여진 buffer에 있던 내용을 강제적으로 출력한다.

void write( byte b[] ) - 스트림에 b.length만큼 쓴다.

void write( byte b[], int off, int length ) - 스트림에 b의내용을 off부터 length만큼 쓴다.

abstract void write( int b ) - 스트림에 한바이트를 쓴다.

 

 

자바 입출력의 개요 (2)

--------------------------------------------------------------------------------

입력스크림 클래스들

 

3 File클래스

    - 파일에 대한 기본적인 정보를 제공해 주는 클래스이다.

    - 파일의 크기나 날짜등 파일 자체 정보와 실제로 파일 입출력과는 관계가 없다.

            

    [File생성]

             File dukcifile=new File(":\java\dukci.doc");

             File dukciDir=new File(c:\java");

 

4. FileInputStream클래스

    - 파일을 입출력 하고자 한다면 클래스를 사용한다.

    - 순차젓인 방법으로 파일의 데이터를 바이트씩 가져올 있다.

   

     [FileInputStream 생성]

             File dukciFile=new File("c:\java\dukci.doc");

             FileInputStream file=new FileInputStream(dukciFile);

             또는

             FileInputStream file=new FileInputStream("dukci.doc");

 

5. DataInputStream클래스

    - 클래스는 자바에서 사용되는 기본 데이터 타입으로 바로 읽어들일 있으며 라인 단위        처리를 있다.

 

     [DataInputStream 생성]

             String line;

             FileInputStream in=new FileInputStream("dukci.txt");

             DataInputStream dis=new DataInputStream(in);

             while((line=dis.readLine())!=null)

 

6. 그밖의 입력스트림 클래스

ByteArrayInputStream 클래스

  클래스의 객체는 별도의 입력장치가 아닌 byte의 배열에서 자료를 읽어 들인다. 다른 입력 스트림들과 달리 클래스의 입력 메쏘드들은 block되지 않는다.

 

PipedInputStream 클래스

  클래스는 파이프의 끝을 이용해서 서로 통신할 경우 사용되는데, 쓰레드가 파이프의 한쪽을 이용해서 데이터를 보내면 다른 쓰레드가 다른 파이프의 한쪽을 이용해서 데이터를 읽어 들일 있다.

 

PushbackInputStream 클래스

  클래스는 1바이트 push back buffer를 제공하는 입력 스트림 필터로, 응용 프로그램에서 마지막으로 읽은 문자를 "unread"할 있다. 따라서 "unread"한 문자는 다시 읽어 들일 있다.

 

 

자바 입출력의 개요 (3)

--------------------------------------------------------------------------------

1. ByteArrayOutputStream 클래스

  클래스는 바이트 배열에 출력을 하기 위한 출력 스트림을 가진다. 버퍼는 자동적으로 크기가 증가된다.

 

2. DataOutputStream 클래스

  클래스는 간단한 방식으로 출력 스트림에 자바 기본 데이터형을 출력하는데 유용하다.

 

3. PipedOutputStream 클래스

  클래스는 파이프의 보내는 쪽에 위치한다. 쓰레드간의 통신에서 클래스는 보내는 쪽에 위치해서 데이터를 보내는 역할을 한다.

 

4. PrintStream 클래스

  클래스는 주로 텍스트로 출력 데이터를 출력하기 위해서 디자인되었다. 클래스에는 다수의 print()와 println()메쏘드가 각각 매개 변수로 서로 다른 자료형을 받아들이도록 overload 되어 있다. 코드의 구현은 println()메쏘드는 print()메쏘드를 이용하도록 되어 있고, print()메쏘드는 write()메쏘드를 이용해서 출력하도록 되어 있다. Println()메쏘드와 print()메쏘드는 바꿈 기능의 여부이다.

 

5. FileOutputStream 클래스

  클래스는 파일로 출력을 하기 위해 사용된다. 쓰기 위한 메쏘드들은 OutputStream 클래스와 같다.

 

FileOutputStream 클래스와 PrintStream 클래스와의 연동

 

class TestFileOutput {

public static void main(String args[] ){

java.io.FileOutputStream fout;

java.io.PrintStream pout;

try{

fout = new java.io.FileOutputStream( "testfile.data");

pout = new java.io.PrintStream( fout );

 

pout.println("파일로 출력되는 내용");

fout.close();

}catch( java.io.IOException e){

System.out.println( e );

}

}

}

 

 

BufferReader의 사용

--------------------------------------------------------------------------------

Socket mail = new Socket("mail.host.name", 25);

BufferedReader in = new BufferedReader(new InputStreamReader(mail.getInputStream()));

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(mail.getOutputStream()));

out.write(...); out.newLine(); out.flush();  // to send.

in.readline(); // to get responses.

 

위와 같은 경우는 지정된 소켓에서부터 데이터를 읽어 들일 있고 반대로 지정된 소켓의 포드에 데이터를 출력할 있습니다.

 

 

BufferedWriter와 FileWriter의 사용예제

--------------------------------------------------------------------------------

BufferReader, BufferedWriter와 FileWriter의 사용예제에 대해 알아봅니다.

 

FileWriter에서 번째 인자는 경로명이고, 번째 인자는 추가모드(true)인지 새로운 생성모드(false) 인지를 판가름한다.

 

flush() :실질적으로 파일에 출력하는 메소드이다.

 

[사용예제]

import java.io.*;

  

class dukciBufferedWriterTest {

        public static void main(String args[]){        

                try {

                        BufferedWriter fw = new BufferedWriter(new

                                                 FileWriter("dukciout",true));

                        fw.write("dukciout파일에 문자열을 추가합니다." );

                        fw.newLine();

                        fw.flush();

                        fw.close(); 

                } catch (FileNotFoundException e) {

                        System.out.println("no found File");

                } catch (IOException e) {

                        System.out.println("IO Exception");

                }

        }

}

 BufferWriter의 객체의 경우는 Buffer메모리에 임시로 우선 출력을 놓은 후에 한번에 File에 출력하기 때문에 속도의 향상 효과를 얻을 있습니다.

 그래서 이에서 BufferWriter를 사용한 것입니다.

 

 그리고 FileWriter의 객체를 생성하였는데 이것은 실제로 데이터를 저장할 파일 객체를 만드는 것입니다.

 

newLine() : 라인의 공백라인을 추가한다는 뜻입니다.

flush() : 실제로 파일에 데이터를 출력하는 메소드이고요.

close() : 파일에 이상 출력할 데이터가 없을 경우 이제 파일 객체를 다룹니다.

 

 

디렉토리 모든 파일 리스트 출력

--------------------------------------------------------------------------------

디렉토리 모든 파일 리스트 출력하는 방법을 알아봅니다.

 

1. 아래 코드에서 File객체의 경로를 c:\\temp로 지정하였습니다.

    주의점] 반드시 "\\"와 같이 두개의 슬래시를 사용해야 경로지정이 됩니다.

2. 그런 후에 File클래스의 list()메소드를 사용하여 지정된 path의 화일 리스트를 얻어 String배열인        listing에 화일수만큼 배열을 할당해 화일이름을 저장합니다.

3. 그런 String배열 안의 내용을 for문을 사용하여 처음부터 차례대로 consol에 출력합니다.

4. consol에서 지정된 경로의 파일을 모두 있습니다.

 

[사용예제]

import java.io.*;

 

class dukciFileTest {

        public static void main(String args[]) {

                File f = new File( "c:\\temp" );

                String[] listing = f.list();

            for( int i = 0; i < listing.length; i++ )

                System.out.println( listing[i] );

        }

}

 

이것은 지정 디렉토리의 모든 화일 리스트를 배열에 저장하고 출력하는 것입니다.

 

 

특정 확정자만을 골라 Consol출력하기

--------------------------------------------------------------------------------

이번에는 저번의 파일 리스트 출력보다는 좀더 발전한 특정 확정자만을 골라 Consol출력하기에 대해 알아봅니다.

 

1. 형식은 저번과 비슷하지만 특정 확장자만을 골라 표현해야 하기 때문에 특정 확장자만을 구별해      새로운 Class객체를 만들었습니다.

2. OnlyExt라는 클래스를 만들어 그곳에 특정 확장자를 인수로 주어지면 endsWith()메소드를 사용하    파일 이름중에 끝에 확정자가 맞는지를 필터할 있습니다.

3. 그런 걸러진 파일을 list()메소드를 이용하여 얻을 있습니다.

4. IndexOf(".") :이것은 파일이름을 "."을 기준으로 나누어 확장자를 임의로 붙어주는 것입니다.

 

 

import java.io.*;

 

public class dukciFilterFileList {

        public static void main(String[] args) {

              OnlyExt flist = new OnlyExt("java");

              File f = new File("c:/temp/test/");

              String[] s=f.list(flist);         // f화일 경로명에 있는 모든 파일을 java 확장자가                                                          는지 검사합니다.

                for(int i=0;i<s.length;i++) {

                        System.out.println(s[i].substring(0,s[i].

                                                     indexOf("."))+".java");   // indexOf(".") :

                                                                   // .을 기준으로 앞문자를 얻는다.

                }   

        }

}

-------------------------------------------------------------------

import java.io.*;

 

class OnlyExt implements FilenameFilter {

        String ext;

               

        public OnlyExt(String ext) {

                this.ext="."+ext;

        }

        public boolean accept(File dirFile,String name) {

                return name.endsWith(ext);                      // 문자열 ext로 끝나는 파일명을                                                                                                                             호출자에게 리턴합니다.

        }

}

 

 

Consol상에서 입력한 문자열 읽어들이기

--------------------------------------------------------------------------------

Consol상에서 입력한 문자열 읽어들이는 방법을 알아봅니다.

// DataInputStream(readLine), System.in.read의 가지 방법 예제를 알아봅니다.

 

번째는 DataInputStream를 이용한 방법을 알아보도록 합니다.

 

1. DataInputStream은 인자로 지정된 곳에서부터 데이터를 받아들여 객체에 저장할 있는 기능을 제공합니다.

  아래의 경우는 인자가 System.in으로 있으니 시스템 Consol에서 문자를 받아 들인다는 의미가 됩니다.

2. 밑에 readLine()는 시스템 Consol에 아직 읽지 않은 문자열이 있을 경우 계속해서 읽어들이는 메소드입니다

3. 그런 후에 문자열 l이 끝날때까지 계속해서 읽어들여 Consol에 출력합니다.

import java.io.*;

 

public class dukciCondolInput {

        public static void main(String args[]) {

                DataInputStream in = new DataInputStream(System.in);

               

                String  l;

 

                try {

                        l = in.readLine();                         // Consol상의 문자를 읽어들임

                        while (l != null) {

                                System.out.println("READ: "+l);

                                l = in.readLine();

                        }

                } catch (Exception e) {

                        System.out.println("Error: "+e.toString());

                }

        }

}

 

---------------------------------------------------------

번째 방법은 System.in.read()메소드를 이용하여 하는 방법입니다.

 

1. System.in.read()메소드는 Consol의 문자를 읽어 들이는 메소드입니다.

    아래의 경우 256byte씩 읽어 들이도록 인자를 것입니다.

 

2. 그런 System.out.write()메소드를 사용하여 정수를 256byte씩 int형을 Consol에 출력함으로서      대로 입력값을 표현할 있습니다.

import java.io.*;

 

class dukciIn{

        public static void main( String[] args) {

                byte[] buffer = new byte[256];

                int numOfBytesRead = 0;

 

                while (true){

                        try{

                                numOfBytesRead = System.in.read( buffer);

                        } catch (IOException e){

                                System.err.println("Exception on input:" + e);

                        }

                        System.out.write( buffer, 0, numOfBytesRead);                               

                }

        }

}

 

:SN13

;TIFileDialog만들기

;IM

;TX

FileDialog만드는 방법에 대해 알아봅니다.

 

1. FileDialog의 객체를 만듭니다.

2. 인자로서는 FileDialog가 들어갈 Container를 첫번째 인자로 주고 두번째 인자로는 자신의 사용하고자 하는 의도에 받게 주어집니다. 아래에는 화일을 Open하는 방식으로 FileDialog를 사용하기 때문에 "Open File"이라는 인자를 주었습니다.

3. FileDialog를 생성했으면 사용자는 특정화일만을 FileDialog에 표현하고자 경우는 setFilenameFilter()라는 메소드안에 FilenameFilter메소드를 상속하여 만든 아래와 같은 코드를 생성시키는 인자를 주는 방법이 있습니다. 그러면 특정 조건에 맞는 확장자만을 리턴합니다.

4. 리턴된 값들로 FileDialog를 구성하여

5. Frame에 출력을 하는 것입니다.

 

import java.io.*;

import java.awt.*;

 

public class dukciFileDialog {

    public static void main(String args[]){

         Frame f = new Frame("dukci FileDialog Test");

         f.setSize(200,200);

         f.setVisible(true);

         FileDialog openFileDlg = new FileDialog(f, "Open File");

         openFileDlg.setFilenameFilter(new dukciFilenameFilter(".class"));

         openFileDlg.setVisible(true);

    }

}

 

------------------------------------------------------------

import java.io.*;

 

public class dukciFilenameFilter implements FilenameFilter{

    private String extension;

 

     public dukciFilenameFilter(String extension){

          this.extension = extension;

     }

 

     public boolean accept(File dir, String name){

          if ( name.endsWith(extension) ) {

                        return true;

          } else {

                   return false;

          }

     }

}

 

 

writeByte로 한글 출력

--------------------------------------------------------------------------------

writeByte로 한글 출력["안녕하세요"를 writeByte로 화일t에 출력]하는 방법에 대해 알아 봅니다.

 

1. 어떤 화일에 출력을 것이지 FileOutputStream에 인자로서 정합니다.

    [참고] 화일이 존재하지 않을경우에는 자바 프로그램이 만듭니다.

2. 데이터를 출력할 있는 객체인 DataOutputStream객체에 화일을 인자로 주므로서 그곳에 데이타를 있게 합니다.

3. 그런후 실제로 writeByte()메소드를 사용하여 실제로 문자를 출력합니다.

4. 문자 출력시 writeByte()는 4byte를 출력합니다. 그러므로 한글의 경우에는 8byte가 되어야 한글자가 완성이 되기 때문에 2개의 코드를 합쳐 하나의 글자가 됩니다.

5. 인자로서 사용된 정수들은 그에맞는 문자코드 번호를 지정한 것입니다.

 

import java.io.*;

 

class dukciwriteByteTest {

        public static void main(String args[]) {

                try{

                        FileOutputStream os=new FileOutputStream("dukci.dat");

                        DataOutputStream outputStream=new DataOutputStream(os);

                                outputStream.writeByte(-66);

                                outputStream.writeByte(-56);

                                outputStream.writeByte(-77);

                                outputStream.writeByte(-25);

                                outputStream.writeByte(-57);

                                outputStream.writeByte(-49);

                                outputStream.writeByte(-68);

                                outputStream.writeByte(-68);

                                outputStream.writeByte(-65);

                                outputStream.writeByte(-28);

                        outputStream.close();

                } catch (IOException e) {}

       }

}

 

// -66 -56 -77 -25 -57 -49 -68 -68 -65 -28 46 13 10

 

안녕하세요.

int 표현되어 출력이 된다.

한글자에 2개의 정수로 표현됨.

 

 

라인문자(cr/lf) 2가지 사용방법

--------------------------------------------------------------------------------

라인문자(cr/lf) 2가지 사용방법 [속성이용, 이전방법]

 

cr/lf with win32 jdk1.1(CR/LF(라인_문자의 사용)

 

1. 속성을 이용한 사용방법

    line.separator라는 인자를 기억하세요.

    이렇게 하면 newLine이라는 String형을 라인문자로 인식하게 있습니다.

 

        String newLine = System.getProperty("line.separator");

        ...

        of.write("Line one Java" + newLine);

        of.write("Line two Info" + newLine);

        of.write("Line three Shop"+newLine);

        ...

 

2. 이전의 방법

    이전에 JDK1.02에는 아래와 같이 주로 \n문자를 첨가하여 사용하였습니다.

 

        import java.io.*;

        class lftest {

         public static void main(String args[]) {

                   try {

                                     FileWriter of = new FileWriter("lftest.txt");

                                     of.write("Line one Java\n");

                                     of.write("Line two Info\n");

                                     of.write("Line three Shop\n");

                                     of.flush();

                               of.close();

                            } catch ( IOException e ) {

                                System.out.println("IO error");

                }

        }

}

 

 

PrintStream으로 화명 출력

--------------------------------------------------------------------------------

// PrintStream으로 화명 출력

 

PrintStream에서  인자를 System.out로 설정할 경우 Consol에 문자를 출력한다.

아래의 간단한 코드만으로도 화면에 문자열을 출력할 있습니다.

 

import java.io.*;

 

class ptest {

        public static void main(String args[]) {

                PrintStream prn = new PrintStream (System.out);

                prn.println("string");

        }      

}

 

 

화일 복사 프로그램 분석

--------------------------------------------------------------------------------

화일 복사 프로그램 [BufferedReader.PrintWriter]

 

BufferedReader로 읽어 PrintWriter로 화일에 다시 쓰는 것입니다.

 

import java.io.*;

import java.net.*;

 

public class dukcicp {

    static PrintWriter stdout = new PrintWriter (System.out, true);

             // System.out으로 첫번째 인자가 주어졌기 때문에 화면 출력을 합니다.

             // 여기서 true인 주번째 인자는 기존이 문자열에 있으면 추가하라는 뜻입니다.

 

    public static void main (String [] args) {

        try {

            BufferedReader fr = new BufferedReader ( new FileReader (args[0]));

             // 실행 명령에서 첫번째로 주어진 인자의 화일을 Buffer에 읽어 들입니다.

 

            PrintWriter fw = new PrintWriter (new FileWriter (args[1]));

             // 실행 명령에서 2번째 인자로 주어진 화일명에 출력할 있게 합니다.

 

            String line = null;

            while ((line = fr.readLine()) != null) {

             // 첫번재 인자 화일에서 문자가 없을때 까지 계속해서 읽어 들입니다.

 

                fw.println(line);

                 // 읽어들인 라인의 문자 전체를 출력할 있는 객체로 생성된 fw의 2번째

                     인자의 화일 이름을 지닌것에 출력합니다.

            }

            fr.close();

            fw.close();

        } catch (FileNotFoundException e) {

            stdout.println("FileNotFoundException : " + e);

        } catch (IOException e) {

            stdout.println("IOException : " + e);

        }

    }

}

 

 

GUI를 이용한 TEXT프린트 소스

--------------------------------------------------------------------------------

GUI를 이용한 TEXT프린트 소스

 

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.Properties;

 

public class TestPrint extends Frame {

  TextArea textArea;

  Label statusInfo;

  Button loadButton, printButton, closeButton;

  Properties p = new Properties();

   

  public TestPrint() {

    super ("File Loader");

    add (statusInfo = new Label(), "North");

    Panel p = new Panel ();

    p.add (loadButton = new Button ("Load"));

    loadButton.addActionListener( new LoadFileCommand() );

    p.add (printButton = new Button ("Print"));

    printButton.addActionListener( new PrintCommand() );

    p.add (closeButton = new Button ("Close"));

    closeButton.addActionListener( new CloseCommand() );       

    add (p, "South");

    add (textArea = new TextArea (10, 40), "Center");

    pack();

  }

  public static void main (String args[]) {

    TestPrint f = new TestPrint();

    f.show();

  }

 

  // Bail Out

  class CloseCommand implements ActionListener {

    public void actionPerformed (ActionEvent e) {

      System.exit (0);

    }

  }

   

  // Load a file into the text area.

  class LoadFileCommand implements ActionListener {

    public void actionPerformed (ActionEvent e) {

      int state;

      String msg;

      FileDialog file = new FileDialog (TestPrint.this, "Load File", FileDialog.LOAD);

      file.setFile ("*.java");  // Set initial filename filter

      file.show(); // Blocks

      String curFile;

      if ((curFile = file.getFile()) != null) {

        String filename = file.getDirectory() + curFile;

        char[] data;

        setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        File f = new File (filename);

        try {

          FileReader fin = new FileReader (f);

          int filesize = (int)f.length();

          data = new char[filesize];

          fin.read (data, 0, filesize);

        } catch (FileNotFoundException exc) {

          String errorString = "File Not Found: " + filename;

          data = errorString.toCharArray ();

        } catch (IOException exc) {

          String errorString = "IOException: " + filename;

          data = errorString.toCharArray ();

        }

        statusInfo.setText ("Load: " + filename);

        textArea.setText (new String (data));

        setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

      }

    }

  }

 

  // Print a file into the text area.

  class PrintCommand implements ActionListener {

    public void actionPerformed (ActionEvent e) {

      PrintJob pjob = getToolkit().getPrintJob(TestPrint.this, "Cool Stuff", p);

      if (pjob != null) {

        Graphics pg = pjob.getGraphics();

        if (pg != null) {

          String s = textArea.getText();

          printLongString (pjob, pg, s);

          pg.dispose();

        }

        pjob.end();

      }

    }

  }

 

  // Print string to graphics via printjob

  // Does not deal with word wrap or tabs

  void printLongString (PrintJob pjob, Graphics pg, String s) {

    int pageNum = 1;

    int linesForThisPage = 0;

    int linesForThisJob = 0;

    // Note: String is immutable so won't change while printing.

    if (!(pg instanceof PrintGraphics)) {

      throw new IllegalArgumentException ("Graphics context not PrintGraphics");

    }

    StringReader sr = new StringReader (s);

    LineNumberReader lnr = new LineNumberReader (sr);

    String nextLine;

    int pageHeight = pjob.getPageDimension().height;

    Font helv = new Font("Helvetica", Font.PLAIN, 12);

    //have to set the font to get any output

    pg.setFont (helv);

    FontMetrics fm = pg.getFontMetrics(helv);

    int fontHeight = fm.getHeight();

    int fontDescent = fm.getDescent();

    int curHeight = 0;

    try {

      do {

        nextLine = lnr.readLine();

        if (nextLine != null) {        

          if ((curHeight + fontHeight) > pageHeight) {

            // New Page

            System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);

            pageNum++;

            linesForThisPage = 0;

            pg.dispose();

            pg = pjob.getGraphics();

            if (pg != null) {

              pg.setFont (helv);

            }

            curHeight = 0;

          }

          curHeight += fontHeight;

          if (pg != null) {

            pg.drawString (nextLine, 0, curHeight - fontDescent);

            linesForThisPage++;

            linesForThisJob++;

          } else {

            System.out.println ("pg null");

          }

        }

      } while (nextLine != null);

    } catch (EOFException eof) {

      // Fine, ignore

    } catch (Throwable t) { // Anything else

      t.printStackTrace();

    }

    System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);

    System.out.println ("pages printed: " + pageNum);

    System.out.println ("total lines printed: " + linesForThisJob);

  }

}

 

 

작업 디렉토리 셋팅

--------------------------------------------------------------------------------

작업 디렉토리를 셋팅하는 방법을 알아보자

 

1. 어떤 특정 화일을 읽어 들이기위해 FileInputStream객체를 만들고

2. Properties객체를 생성해 시스템 속성을 얻은후

3..현재의 속성을 적용시키고

4. getProperty()메쏘드에 인자 user.dir를 주어 현재 디렉토리를 얻음

 

try {

        FileInputStream propFile = new FileInputStream("myProperties.txt");

        Properties p = new Properties(System.getProperties());

        p.load(propFile);

        System.setProperties(p);

        String cwd = System.getProperty("user.dir");

        System.out.println ("Current Working Directory is " + cwd);

    } catch (Exception e) {

                System.out.println("Execption occurred....." + e.getMessage());

        }

}

 

 

한글을 파일에 읽고 쓰기

--------------------------------------------------------------------------------

 

public class dukciFile {

  public static void main(String[] args) {

            try {

            BufferedWriter fw = new BufferedWriter(new FileWriter("dukci.txt"));

             // 빠른 출력을 위해 BufferedWriter를 사용하였다.

 

            fw.write("Hello dukci / 안영");

             // Hello dukci하는문자열을 Buffer에 출력

 

            fw.newLine();

             // 한라인의 공백을 추가

 

            fw.write("한글를 출력합니다.");

            fw.flush();

             // 실제로 Buffer의 내용을 화일로 생성시킴

 

            fw.close();

            } catch (IOException e) {}

             // 화일 쓰기시 입출력 에러처리

 

            try {

            BufferedReader br = new BufferedReader(new FileReader("han.txt"));

             // 화일을 읽을때에도 역시 BufferedReader르 사용 Buffer로 읽어들임

             // Buffer를 사용하면 빠르게 읽어 들일 있다.

 

            String str = br.readLine();

             // Buffer에 읽어들인 문자열중 한라인을 문자열str에 저장

 

            System.out.println(str);

             // Buffer로부터 읽은 문자열을 Consol에 출력

 

            br.close();

             // 더이상 Buffer로부터 읽을 문자열이 없을 경우 닫아줍니다.

 

            } catch (IOException e) {}

  }

}

 

[주의]

dukci.txt파일이 존재하지 않으면 새로 만들어 출력을 한다.

이미 존재하고 있다면 덮어 쓰기가 되어 기존 문자가 없어진다

하나의 라인을 읽어서 화면에 표시해줍니다.

 

 

File클래스의 주요 메쏘드

--------------------------------------------------------------------------------

 

io 패키지에 있는 File 클래스는 파일에 관한 기본적인 정보를 제공해주는 클래스이다.

가령 크기나 만들어진 날짜 파일 자체에 대한 정보를 가지고 있는 것으로,

이는 실제 파일 입출력하고는 직접적인 관계가 없다.

실제 File 클래스를 만드는 방법은 다음과 같다.

 

File docfile = new File("c:\javadoc\dukci.txt");

File docfile = new File("dukci.txt");

File dir = new File("c:\javadoc");

 

다음은 File 클래스의 주요 메쏘드들에 대해서 살펴보기로 한다.

             String getName() 파일의 이름을 가져온다

             String getPath() 파일의 경로를 가져온다

             String getAbsolutePath() 파일의 절대 경로를 가져온다

             String getParent() 부모 디렉토리를 가져온다

             boolean canRead() 파일을 읽을 수가 있는가 검사한다

             boolean canWrite() 파일에 쓸수가 있는가를 검사한다

             boolean exists() 파일이 존재하는 가를 검사한다

             boolean isFile() 파일인가를 검사한다

             boolean isDirectory() 디렉토리인가를 검사한다

             boolean isAbsolute() 절대 경로 인가를 검사한다

             boolean renameTo(File dest) 파일 이름을 다른 이름으로 변경한다

             boolean delete() 파일을 삭제한다

             long lastModified() 최근 변경일에 대한 정보를 나타낸다

             long length() 파일의 길이에 대한 정보를 나타낸다

             String toString() 파일이름을 String 타입으로 변환한다

             String[] list() 디렉토리의 내용을 리스팅한다

             boolean mkdir() 새로운 디렉토리를 만든다

 

 

JDK 1.1.x 입출력 종류

--------------------------------------------------------------------------------

JDK 1.1.x 입출력 종류

 

 자바 입출력 관련 클래스들을 보면 InputStream, OutputStream처럼 Stream이라는 문자열로 끝나는 것이 있고, FileReader, FileWriter처럼 Reader나 Writer로 끝나는 입출력 관련 클래스들이 많이 있습니다.

 

 그런데 Stream형태는 byte단위로 입출력을 처리하므로 한글처리에 문제를 가지고 있습니다. 한글 처리시 2byte가 필요하기 때문이죠. 그러나 Reader나 Writer는 Unicode문자 한문자를 표현할 있으므로 한글 처리에 적합합니다. Unicode에는 완성형 한글이 포함되어 있으니까요

-------------------------------------------------------

Stream형태 : byte(바이트) 단위로 입출력을 처리

Reader, Writer형태 : char(문자)데이터형으로 입출력 처리

-------------------------------------------------------

 

char데이터형 : 유니코드(unicode)한 문자를 저장할 있는 공간

한글 처리시 Reader, Writer형태 입출력 처리 요망


관련글 더보기