일단. 어떤것을 쓰던간에.. 화일은 잘 읽힌다.. 또한 유니코드의 경우 는 더욱더 편하게 읽힌다.
문제는... 유니코드가 아닌화일을 읽을때 글자깨짐이 일어난다는 점이다.
다음의 경우 Shift_JIS 화일을 읽어들인다. 글자 안깨진다...
다음의 method를 보면 알겠지만.. 인코딩 관련 지정이 하나도 없다..
왜일까? 인코딩을 사용하면 도리어 글자가 깨진다..왜지?

/** ディレクトリからファイルを読取って文字列に返す。
  * @param workName 作業名
  * @return
  */
 public void inputFile(String fileName) {
  BufferedInputStream is = null;       // inputStream初期化
  try {
     StringBuffer returnStr = new StringBuffer();     // ファイル内容を文字列で格納するStringBuffer。

    File inputFile = new File(fileName);       // ファイルを宣言する。
    if (inputFile.isFile() && inputFile.exists() ) {    // ファイルが存在するのを確認
     is = new BufferedInputStream(new FileInputStream(fileName));  // ファイルをstreamで読み取る。
     byte[] byteBuf =new byte[(int) inputFile.length()];  // 一時的にファイルをByteで格納するbyte配列
     for(int j = 0; j < (int) inputFile.length() ; j++) {
      byteBuf[j] = (byte) is.read();       // ファイルをByte読み取る。
/* 바로 이부분이다..왜 바이트로 읽는냐..바보 아니냐 하겠지만..
   다 이유가 있다... 한자 때문이다. Shift_JIS와 unicode는 100%호완되지 않기 때문에.
MS사이트에서 뒤지면 코드 변환표가 나온다..
자바는 내부적으로 유니코드로 처리하기 때문에..
reader를 사용하면.. 깨지는 글자가 생기기 때문이다..
reader에 인코딩 지정해도..결국 깨지는 글자가 발생했다..쩝..왜..그럴리가 없어야 되는데말이지.
단순히 커뮤니티 정도 만들려면..굳이 이렇게 쓸필요없지만..공공기관용을 만들어야 한다면..
어쩔수 없다... 아직까지는..더 좋은 방법을 찾지 못했다는말이지..
*/
     }
     returnStr.append(new String(byteBuf));      // ファイル内容を文字列で格納する。

    } // if (f.isFile() && f.exists()
    is.close();

  } catch (UnsupportedEncodingException e) {    // 支援しないコードの場合
   logger.error("지원하지 않는 인코딩", e);
  } catch (FileNotFoundException e) {      // ファイルが存在しない場合
   logger.error("화일을 찾을수 없다", e);
  } catch (IOException e) {        // 入出力エラーの場合
   logger.error("입출력에러", e);
  } catch (NullPointerException e) {      // 引数がNullの場合
   logger.error("null발생", e);
  }finally{
   try {
    if (is != null) is.close();      // 最後に inputStream を閉じられなかった場合閉じる。
   } catch (IOException e) {       // 入出エラー場合
      }
  } //finally

 } // inputFile(String fileName)

/**ファイル出力処理を行う。 화일 출력이다..뭐..출력은..그다지 상관 없다...잘 되니까..
  * @param str 受け取って編集済みデータ 받아와서 편집끝낸 화일내용
  * @param date 日付 시스템 날짜
  */
 public void outputFile(String str, String fileName ) {

  OutputStreamWriter os = null;       // 出力streamWriterの初期化 초기화..
  try {
   os = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(fileName)),"Shift_JIS"); // ファイル出力する。
   os.write(str);          // ファイル内容を記録する。 화일내용을 쓰는 부분..
   os.flush();           // ファイルを放出する。(生成する) 화일을 출력하는부분.
  } catch (IOException e) {        // 入出力エラーの場合
   logger.error("IO에러", e);
  } finally { //연습할때는 finally부분까지는 필요 없다.. 에러처리라는게..연습목적은 아니니까..
   try {
    if (os != null) os.close();      // 最後に outputStream を閉じられなかった場合閉じる。
   } catch (IOException e1) {       // 入出エラー場合
    logger.error("IO에러 ",e1);
   }
  } // finally
  } //outputFile(String str, String date)

이렇게 해서 Shift_JIS에서 화일 입출력은 끝냈따..
그럼 UTF-8화일일 경우에는?
자신이 편한대로 하면 된다..
 /** ファイル読み取る。
  * @param strAddress ファイル住所
  * @return ファイル値文字列
  */
 public String inputFile(String strAddress){
  DataInputStream is = null;       // データinputStream初期化
  StringBuffer returnStr = new StringBuffer();
  try {
   File tempfile = new File (strAddress);    // ファイル宣言
   if(tempfile.exists()){       // ファイルが存在する場合
    byte[] byteBuf = new byte[(int) tempfile.length()];  // 一時的にコード変換ファイルを格納するbyte配列
    is = new DataInputStream(new BufferedInputStream(new FileInputStream(tempfile))); // ファイルinputStream宣言
    while (is.read(byteBuf, 0, byteBuf.length) != -1){   // ファイル読み取る。
     returnStr.append(new String(byteBuf, "UTF-8"));   // ファイル内容を文字列で格納する。
    } //while
   } // if (tempfile.exists()
   is.close();  

  } catch (FileNotFoundException e) {     // ファイルが存在しない場合
   logger.error("화일 안보여", e);
  } catch (IOException e) {       // 入出力エラーの場合
   logger.error("IO에러다", e);  
  }finally{
   try {
    if (is != null) is.close();     // 最後に inputStream を閉じられなかった場合閉じる。
   } catch (IOException e) {     // 入出エラー場合
   logger.error("IO에러다", e);  
   }
  } //finally
  return returnStr.toString();
 } // end od inputFile


Posted by 김반장78
,
import java.io.IOException;
import java.io.Writer;

import java.util.Stack;

import com.generationjava.io.WritingException;

/**
* Makes writing XML much much easier.
*
* @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a>
* @version 0.1
*/

public class XmlWriter {

    private Writer writer;      // underlying writer
    private Stack stack;        // of xml entity names
    private StringBuffer attrs; // current attribute string
    private boolean empty;      // is the current node empty
    private boolean closed;     // is the current node closed...

    /**
     * Create an XmlWriter on top of an existing java.io.Writer.
     */

    public XmlWriter(Writer writer) {
        this.writer = writer;
        this.closed = true;
        this.stack = new Stack();
    }

    /**
     * Begin to output an entity.
     *
     * @param String name of entity.
     */

    public XmlWriter writeEntity(String name) throws WritingException {
        try {
            closeOpeningTag();
            this.closed = false;
            this.writer.write("<");
            this.writer.write(name);
            stack.add(name);
            this.empty = true;
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    // close off the opening tag
    private void closeOpeningTag() throws IOException {
        if (!this.closed) {
            writeAttributes();
            this.closed = true;
            this.writer.write(">");
        }
    }

    // write out all current attributes
    private void writeAttributes() throws IOException {
        if (this.attrs != null) {
            this.writer.write(this.attrs.toString());
            this.attrs.setLength(0);
            this.empty = false;
        }
    }

    /**
     * Write an attribute out for the current entity.
     * Any xml characters in the value are escaped.
     * Currently it does not actually throw the exception, but
     * the api is set that way for future changes.
     *
     * @param String name of attribute.
     * @param String value of attribute.
     */

    public XmlWriter writeAttribute(String attr, String value) throws WritingException {

        // maintain api
        if (false) throw new XmlWritingException();

        if (this.attrs == null) {
            this.attrs = new StringBuffer();
        }
        this.attrs.append(" ");
        this.attrs.append(attr);
        this.attrs.append("=\"");
        this.attrs.append(escapeXml(value));
        this.attrs.append("\"");
        return this;
    }

    /**
     * End the current entity. This will throw an exception
     * if it is called when there is not a currently open
     * entity.
     */

    public XmlWriter endEntity() throws WritingException {
        try {
            if(this.stack.empty()) {
                throw new XmlWritingException("Called endEntity too many times. ");
            }
            String name = (String)this.stack.pop();
            if (name != null) {
                if (this.empty) {
                    writeAttributes();
                    this.writer.write("/>");
                } else {
                    this.writer.write("</");
                    this.writer.write(name);
                    this.writer.write(">");
                }
                this.empty = false;
            }
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    /**
     * Close this writer. It does not close the underlying
     * writer, but does throw an exception if there are
     * as yet unclosed tags.
     */

    public void close() throws WritingException {
        if(!this.stack.empty()) {
            throw new XmlWritingException("Tags are not all closed. "+
                "Possibly, "+this.stack.pop()+" is unclosed. ");
        }
    }

    /**
     * Output body text. Any xml characters are escaped.
     */

    public XmlWriter writeText(String text) throws WritingException {
        try {
            closeOpeningTag();
            this.empty = false;
            this.writer.write(escapeXml(text));
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    // Static functions lifted from generationjava helper classes
    // to make the jar smaller.
   
    // from XmlW
    static public String escapeXml(String str) {
        str = replaceString(str,"&","&amp;");
        str = replaceString(str,"<","&lt;");
        str = replaceString(str,">","&gt;");
        str = replaceString(str,"\"","&quot;");
        str = replaceString(str,"'","&apos;");
        return str;
    } 

    // from StringW
    static public String replaceString(String text, String repl, String with) {
        return replaceString(text, repl, with, -1);
    } 
    /**
     * Replace a string with another string inside a larger string, for
     * the first n values of the search string.
     *
     * @param text String to do search and replace in
     * @param repl String to search for
     * @param with String to replace with
     * @param n    int    values to replace
     *
     * @return String with n values replacEd
     */

    static public String replaceString(String text, String repl, String with, int max) {
        if(text == null) {
            return null;
        }

        StringBuffer buffer = new StringBuffer(text.length());
        int start = 0;
        int end = 0;
        while( (end = text.indexOf(repl, start)) != -1 ) {
            buffer.append(text.substring(start, end)).append(with);
            start = end + repl.length();

            if(--max == 0) {
                break;
            }
        }
        buffer.append(text.substring(start));

        return buffer.toString();
    }             

    // Two example methods. They should output the same XML:
    // <person name="fred" age="12"><phone>425343</phone><bob/></person>
    static public void main(String[] args) throws WritingException {
        test1();
        test2();
    }
    static public void test1() throws WritingException {
        Writer writer = new java.io.StringWriter();
        XmlWriter xmlwriter = new XmlWriter(writer);
        xmlwriter.writeEntity("person").writeAttribute("name", "fred").writeAttribute("age", "12").writeEntity("phone").writeText("4254343").endEntity().writeEntity("bob").endEntity().endEntity();
        xmlwriter.close();
        System.err.println(writer.toString());
    }
    static public void test2() throws WritingException {
        Writer writer = new java.io.StringWriter();
        XmlWriter xmlwriter = new XmlWriter(writer);
        xmlwriter.writeEntity("person");
        xmlwriter.writeAttribute("name", "fred");
        xmlwriter.writeAttribute("age", "12");
        xmlwriter.writeEntity("phone");
        xmlwriter.writeText("4254343");
        xmlwriter.endEntity();
        xmlwriter.writeEntity("bob");
        xmlwriter.endEntity();
        xmlwriter.endEntity();
        xmlwriter.close();
        System.err.println(writer.toString());
    }
}

C#에는 있는데 왜 자바에는 없는거냐..ㅡ.ㅡ



Posted by 김반장78
,
  • Escape sequences

    inside char and String literals include:
    ' ' space
    '\u003f' Unicode hex, (must be exactly 4 digits to give a 16-bit Unicode number ). \u2007 is Figure Space, a space as wide as a digit, to help in aligning numbers.
    '\n' newline, ctrl-J (10, x0A)
    '\b' backspace, ctrl-H (8, 0x08)
    '\f' formfeed, ctrl-L (12, 0x0C)
    '\r' carriage return, ctrl-M (13, 0x0D)
    '\t' tab, ctrl-I (9, 0x09)
    '\\' backslash,
    '\'' single quote (optional inside " "),
    '\"' double quote (optional inside ' '),
    '\377' octal (must be exactly 3 digits. You can get away with fewer, but then you create an ambiguity if the character following the literal just happens to be in the range 0..7.). This lets you get at only the 8-bit characters in the range 0..377 octal or 0..255 decimal or 0..255 decimal, which still gives you 16-bit Unicode.
    \007 bel, ctrl-G (7, 0x07)
    \010 backspace, ctrl-H (8, 0x08)
    \013 vt vertical tab, ctrl-K (11, 0x0B)
    \032 sub (used in DOS/CPM as eof), ctrl-Z (26, 0x1A)
    \033 esc ctrl-^ (27, 0x1B)
  •  

  • C# Escape sequences


  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \\ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)
  • C# \xn[n][n][n] 의 추가 설명
    16진수 이스케이프 시퀀스에는 다양한 자릿수의 16진수를 사용할 수 있습니다. 문자열 리터럴 "\x123"에는 16진수 값이 123인 문자 하나가 포함됩니다. 16진수 값이 12인 문자 다음에 문자 3이 오는 문자열을 만들려면 "\x00123"이나 "\x12" + "3"을 사용하십시오.

    Posted by 김반장78
    ,