파일 읽어오기
<% BufferedReader reader = null; try{ 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>
<h2>글쓰기</h2>
<form action = input.jsp method="post">
이름 : <input type ="text" name="name"><br/>
제목 : <input type="text" name="title"><br/>
<textarea cols="30" rows = "5" name = "content"></textarea><br/>
<input type="submit" value="저장">
</form>
//input 박스 안에 글자를 적고 누르면 input.jsp 로 날라갑니다
<h2> 글쓰기</h2>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String title = request.getParameter("title");
String content = request.getParameter("content");
String time = "output";
String filename = time + ".txt";
PrintWriter writer = null;
try{
String filePath = application.getRealPath("/WEB-INF/bbs/"+filename);
writer = new PrintWriter(filePath);
writer.printf("제목 : %s %n",title);
writer.printf("글쓴이 : %s %n",name);
writer.println(content);
out.print("저장되었습니다.");
}catch(IOException ioe){
out.println("파일에 데이터를 쓸 수 없습니다");
ioe.printStackTrace();
}finally{
try{
writer.close();
}catch(Exception e){
}}
%>
</body>
String time 이 파일의 이름이 됩니다 .filename 이 확장자를 붙여 줍니다. filePath 로 경로를 지정해 줍니다, out 객체는 _jsp.java 에 담겨잇는 내장객체이다, PrintWriter 객체가 printf 를 가지고 있다