当前位置: 移动技术网 > IT编程>开发语言>Java > jsp文件操作之写入篇

jsp文件操作之写入篇

2017年12月12日  | 移动技术网IT编程  | 我要评论

你的选择简谱,炫舞音律,风色幻想7官网

 
    文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的。
  这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松写文本文件,注意请建立一个test目录到web根目录下,程序将会建立一个afile.txt文件,javabean文件编译后将class文件放到对应的class目录下(tomcat环境)。
  有了在jsp下读取和写入文件的方法,要做出一个简单的计数器来相信不是一件困难的事情了,大家可以尝试一下:)

writeover.jsp

<html>
<head>
<title>写一个文件</title>
</head>
<body bgcolor="#000000">
<%--创建javabean并设置属性 --%>
<jsp:usebean id="writer" class="writeover" scope="request">
<jsp:setproperty name="writer" property="path" value="/test/afile.txt" />
<jsp:setproperty name="writer" property="something" value="初始化somthing属性" />
</jsp:usebean>

<h3>写一个文件</h3>

<p>
<%--设置要写入的字符串 --%>
<% writer.setsomething("写点东西到文件"); %>
<%--读取上面设置的字符串 --%>
<% out.print(writer.getsomething()); %>
<%--调用writer的writesomething方法写入文件并返回成功或者出错信息 --%>
<% out.print(writer.writesomething()); %>

</p>
</body>
</html>

//writeover.java javabean文件
import java.io.*;


public class writeover {

private string path; //文件路径
private string something;//写入的字符串
//初始化
public writeover() {
path = null;
something = "缺省文字";
}

//设置文件路径
public void setpath(string apath) {
path = apath;
}

//得到文件路径
public string getpath() {
return path;
}
//得到字符串
public void setsomething(string asomething) {
something = asomething;
}
//设置字符串
public string getsomething() {
return something;
}
//写入字符串到文件中,成功则返回success字符串
public string writesomething() {
try {
    
     file f = new file(path);
     printwriter out = new printwriter(new filewriter(f));
     out.print(this.getsomething() + "
");
     out.close();
     return "success.";
} catch (ioexception e) {
     return e.tostring();
}    
}
}
  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网