Servlet對檔案的讀寫操作,servlet讀寫操作

來源:互聯網
上載者:User

Servlet對檔案的讀寫操作,servlet讀寫操作

(1)如何在serlvet中讀取檔案的內容

package com.tsinghua;import java.io.*;import javax.servlet.http.*;public class ServletFileTest1 extends HttpServlet {  public void doGet(HttpServletRequest req,HttpServletResponse res){  try { //中文亂碼res.setContentType("text/html;charset=gbk");PrintWriter pw=res.getWriter();  //建立一個FileReaderFileReader  f=new FileReader("f:\\myCounter.txt");    BufferedReader bw=new BufferedReader(f);      //讀出一行資料 或者使用for迴圈都區全部內容String numVal=bw.readLine();  //一定要關閉檔案流   bw.close();pw.println("從檔案中讀取的資料是:"+numVal);  } catch (Exception ex) {  ex.printStackTrace();  }  }  public void doPost(HttpServletRequest req,HttpServletResponse res){  this.doGet(req,res); }    }

(2)如何在serlvet中操作檔案寫入資料

package com.tsinghua;import java.io.*;import javax.servlet.http.*;public class ServletFileTest2 extends HttpServlet {  public void doGet(HttpServletRequest req,HttpServletResponse res){  try {  //中文亂碼res.setContentType("text/html;charset=gbk");PrintWriter pw=res.getWriter();  //建立一個FileWriter  看記憶體資料 ->  磁碟檔案(寫入,輸出) //看記憶體資料 <-  磁碟檔案(讀入,輸入)FileWriter  f=new FileWriter("f:\\myCounter.txt");        BufferedWriter bw=new BufferedWriter(f);        //在檔案中寫入資料    bw.write("1");        //關閉檔案流    bw.close();        pw.println("在檔案中寫入了資料");      } catch (Exception ex) {  ex.printStackTrace();  }  }  public void doPost(HttpServletRequest req,HttpServletResponse res){  this.doGet(req,res); }    }




怎定義一個Servlet,讀取一個文字檔的內容,並且在頁面上列印檔案的內容

Serverlet裡的路徑,和你的項目路徑是不一樣的。
前者是容器裡的路徑,也就是你的項目發布到Tomcat或者其他server上的路徑
後者是你本地workspace路徑

你可以用這個方法來獲得絕對路徑
File f = new File("");

String absolutePath = f.getAbsolutePath();

System.out.println(absolutePath);

//read jms properties
File configFile = new File(absolutePath+"\\your_file_name.txt");

if (configFile == null) {
throw new Exception("Configuration File Not Found: facs_fasg.properties");
}
InputStream propertiesInStream = configFile.toURL().openStream();
 
java servlet中檔案讀取速度怎這慢!

你請求的網頁第一次訪問是會很慢,因為tomcat需要編譯jsp為servlet,你試一下第二次訪問是不是會快一些了,如果還是慢,你把jsp裡的邏輯代碼貼出來,看是不是有什麼迴圈之類的,亂碼問題應該是你jsp裡的編碼有問題,一般來說建議jsp編碼為UTF-8,設定方式見如下代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.