2012-12-15 29 views
1

嘿,夥計我試圖讓我的代碼,一旦運行;它會插入到WebContent目錄中已經創建的.txt文檔中。我在Apache Tomcat v7.0中運行 - 在Eclispe中構建。在tomcat servlet中有java的問題編輯一個.txt文件

CODE:

public static void insertWinner(String winner) throws IOException{ 

     String filename= "Winner.txt"; 
     FileWriter fw = new FileWriter(filename,true); //the true will append the new data 
     fw.write("Winner is" + winner);//appends the string to the file 
     fw.close(); 

    } 

這是被稱爲BandIO一個java文件BandListServ.java呼籲servlet來插入一個字符串值到上面的代碼中完成的。

當我這樣做時,什麼都沒有發生,不知道爲什麼。

讓我知道如果您需要其他信息,再次感謝!

編輯

我改成這樣 -

public static void insertWinner(String winner) throws IOException{ 


     FileWriter out = new FileWriter("Winner.txt"); 
     out.write("Hello"); 
     out.close(); 
     out = new FileWriter("Winner.txt", true); 
     out.write(", world!"); 
     out.close(); 

    } 

編輯:

好了,所以我想這個servlet的文件,但沒有雪茄裏面..

   response.setContentType("text/html"); 


      String filename = "Winner.txt"; 

      ServletContext context = getServletContext(); 


      InputStream is = context.getResourceAsStream(filename); 
      if (is != null) { 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader reader = new BufferedReader(isr); 
       PrintWriter writer = response.getWriter(); 
       String text = "Winner is"; 


       while ((text = reader.readLine()) != null) { 
        writer.println(text); 
       } 
      } 

回答

2

在原則上訪問文件系統是用

File file = getServletContext().getRealPath("/Winner.txt"); 

此文件可能爲空,即當Web應用程序部署爲.war(如此zip格式)時,並且Web服務器未配置爲解包戰爭。

在你的情況下,文件可能有一個併發問題,需要一些鎖定。也許你應該使用數據庫表。

同樣在下次部署時文件可能會丟失。

+0

嗯,我只是試圖通過不是servlet本身的.java文件訪問該文件,所以getServletContext()不起作用... –

+0

但是不能使用相對路徑,並且Web內容目錄是已知的只能通過ServletContext。例如,您可以在屬性文件中配置硬完整路徑。 –

+2

您需要將'ServletContext'的對象引用傳遞給該方法。看看SO線程 - http://stackoverflow.com/questions/2728877/how-do-i-get-servletcontext-object-in-a-simple-class-file – adatapost