본문으로 바로가기

UTF-8 File 읽기

category ★프로그래밍☆/└ Java 2008. 5. 29. 01:22

어제 코딩을 하던 중 찾은 내용입니다.
내용은 제목 그대로 입니다.
출처는 아래 링크입니다.
http://cafe.naver.com/suninet.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=588

Introduction

In this section, you will learn what is UTF - 8 Encoded Data and how does that perform the work. First of all you have to know about the UTF-8. UTF-8, it stands for 8-bit Unicode Transformation Format. It represents the Unicode. In this program standard UTF-8 has been used to read string through the help of InputStreamReader class.

Here, this program uses the UTF-8 as you have known about the UTF-8 above. This program takes a file name, if the given file exists then read it's contents otherwise display the appropriate message like: "File does not exist".

BufferedReader i = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
The above code written in the program creates a instance of the BufferedReader class using the InputStreamReader and FileInputStream classes to read data or contents from the specified file in the specified encoded data format that has been mentioned in above given line of the code(UTF-8). This is thrown by the UnsupportedEncodingException exception if the given encoded data format does not support.

Here is the code of the program :

import java.io.*;

public class ReadUTF8{
  public static void main(String[] args)throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter File name : ");
    String str = in.readLine();
    File file = new File(str);
    if(!file.exists())
    {
      System.out.println("File does not exist");
      System.exit(0);
    }
    else
    {
      try{
        BufferedReader i = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
        String str1 = i.readLine();
        System.out.println("File text : "+ str1);
        System.out.println("Reading Process Completly Successfully.");
      }
     
      catch(UnsupportedEncodingException ue){
        System.out.println("Not supported : ");
      }
      catch(IOException e){
        System.out.println(e.getMessage());
      }
    }
  }
}