|
本文是根据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){} //} }
|

文章整理:
站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!