欢迎光临
我们一直在努力

jsp+java类+servlet实现文件读取、写入的功能(一)-JSP教程,Jsp/Servlet

建站超值云服务器,限时71元/月

本文是根据tomcat平台下实现而做,文件目录为:

 tom_home\webapps\news下:

└html
└web-inf
└classes
   └com
      └fileman.class
      └fileservlet.class
 └web.xml

首页我们先实现文件读取的类:fileman.java

//fileman.java 读写文件的一个类
package com;
import java.io.*;

public class fileman{
private string currentrecord = null;//保存文本的变量
private bufferedreader file; //bufferedreader对象,用于读取文件数据
private string path;//文件完整路径名
public fileman() {
}
//readfile方法用来读取文件filepath中的数据,并返回这个数据
public string readfile(string filepath) throws filenotfoundexception
{
path = filepath;
//创建新的bufferedreader对象
file = new bufferedreader(new filereader(path));
string returnstr =null;
try
{
//读取一行数据并保存到currentrecord变量中
currentrecord = file.readline();
}
catch (ioexception e)
{//错误处理
system.out.println(“读取数据错误.”);
}
if (currentrecord == null)
//如果文件为空
returnstr = “没有任何记录”;
else
{//文件不为空
returnstr =currentrecord;
}
//返回读取文件的数据
return returnstr;
}

//写入文件
public void writefile(string filepath,string tempcon) throws filenotfoundexception
{
path = filepath;

try {
//创建printwriter对象,用于写入数据到文件中
printwriter pw = new printwriter(new fileoutputstream(filepath));
//用文本格式打印整数writestr
pw.println(tempcon);
//清除printwriter对象
pw.close();
} catch(ioexception e) {
//错误处理
system.out.println(“写入文件错误”+e.getmessage());
}
}

/*下面这一般你可以用来测试java应用程序来读取文件,将前面的”//”去掉后你可以运行:java fileman 来测试。*/
//public static void main(string args[])
//{
 //fileman fm=new fileman();
 //try
 //{
 //fm.writefile(“test.txt”,”asf”);
 //}
 //catch(filenotfoundexception e){}
//}
}


赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » jsp+java类+servlet实现文件读取、写入的功能(一)-JSP教程,Jsp/Servlet
分享到: 更多 (0)

相关推荐

  • 暂无文章