JSP中读文件和写文件的例子(转帖)

转自:(http://www.programfan.com/article/showarticle.asp?id=2495


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

<html>

  <head>

    <title>Lion互动网络==》JSP中读文件和写文件的例子</title>

  </head>

  <body>

   <%

//写文件

String str = "WWW.LIONSKY.NET";

String filename = request.getRealPath("lionsky.txt");

java.io.File f = new java.io.File(filename);

if(!f.exists())//如果文件不存,则建立

{

  f.createNewFile();

}

try

{

  PrintWriter pw = new PrintWriter(new FileOutputStream(filename));

  pw.println(str);//写内容

  pw.close();

}

catch(IOException e)

{

  out.println(e.getMessage());

}

//读文件

java.io.FileReader fr = new java.io.FileReader(f);

char[] buffer = new char[10];

int length; //读出的字符数(一个中文为一个字符)

//读文件内容

out.write(filename+"<br>");

while((length=fr.read(buffer))!=-1)

{

  //输出

  out.write(buffer,0,length);

}

fr.close();

%>

  </body>

</html>

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( ProgramFan.Com )