프로그래밍/JSP Servlet

JSP/Servlet - 파일에서 입력받기

가카리 2015. 12. 15. 21:49
반응형

 

jsp에서 파일 읽기는 자바와 상당히 비슷하다.

 

예제를 보자

 

input.txt

 

내이름은 가카리입니다.

감사합니다.

 

FileReader.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%@page import="java.io.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    <%

        BufferedReader reader = null;

        try{

            //input.txt파일의 경로를 가져옴

            String filePath = application.getRealPath("/WEB-INF/input.txt");

            //파일을 엽니다.

            reader = new BufferedReader(new FileReader(filePath));

            

            //파일을 실제로 읽는 부분

            while(true){

                String str = reader.readLine();//한줄씩 읽습니다.

                if(str == null)

                    break;

                out.println(str + "<BR>");//읽는 데이터를 웹으로 보냄

            }

        }catch(FileNotFoundException fnfe){

            out.println("파일 존재하지 않음");

        }catch(IOException ioe){

            out.println("파일을 읽을수 없음");

        }

        finally{

            try{

                reader.close();

            }catch(Exception e){

                

            }

        }

    

    %>

</body>

</html>

실행화면

반응형