關於applet寫入檔案的處理 (轉)

worldblog發表於2007-12-02
關於applet寫入檔案的處理 (轉)[@more@]duke原創於嬌娃網上家園
關於applet寫入的處理

眾所都知見於性考慮,applet在ie、scape中沒有寫入檔案的能力,包括本地、檔案。那麼我們怎樣才能實現一些資料的保留呢?(象本程式碼中記錄積分的功能)。

一個方法是透過伺服器端的寫入檔案,applet端的程式碼如下:


private void Send(){
message=re+"#"+tf.getText ();
showStatus("Message send");
String queryString="/servlet/javaduke.servlet.SaveServlet?message="+
URLEncoder.encode(message);
p("Attempting to send:"+message);
try{
connect=(new URL(chatURL,queryString)).openConnection();
showStatus("開啟連線");
showStatus(connect.toString ());
System.out.println("open connection");
connect.setDefaultUseCaches(false);
connect.setUseCaches (false);
connect.setDoInput (true);
connect.setDoOutput(false);
System.out.println("dooutput false");
connect.connect();
System.out.println("open stream");
p("Made connection to"+connect);
showStatus("試圖連線、讀取回應");
InputStreamReader reader=new InputStreamReader(connect.getInputStream ());
BufferedReader in=new BufferedReader(reader);
message=in.readLine ();
while(message!=null){
tf.setText(message);
message=in.readLine ();
}
showStatus("對話成功");
}
catch(MalformedURLException e2){
System.err.println ("MalformedURLException!");
e2.printStackTrace (System.err );
showStatus("MalformedURLException");
}
catch(IOException e1){
System.err.println ("IOException");
e1.printStackTrace (System.err);
showStatus(e1.toString ());
}
}
server端程式碼如下!
Servlet寫入檔案(成功)

import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class SaveServlet extends HttpServlet {
String counter,counter2;
//Initialize global variables
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
//Service the request
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

File file=new File("/members/YourID/servlet/gamelog.txt");
RanAccesile raf;
if(!file.exists()){
raf=new RandomAccessFile(file,"rw");
counter="210#javaduke ";
raf.seek(0);
raf.writeBytes(counter);
raf.close();
}
else{
counter=request.getParameter("message");
raf=new RandomAccessFile(file,"rw");
raf.seek(0);
raf.writeBytes(counter);
raf.close();
}
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.print("Saved OK!");
out.close();


}

//Get Servlet information
public String getServletInfo() {
return "game.SaveServlet Information";
}
}




來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-987222/,如需轉載,請註明出處,否則將追究法律責任。

相關文章