2012-01-31 151 views
1

我在我的服務器上打開一個txt文件,獲取Int並希望將int遞增1並將其再次寫入該文件。打開遠程文件並寫入它

我得到的文件,這種方法:

public int getCount() { 
     try { 
URL updateURL = new URL("http://myserver.gov/text.txt"); 
URLConnection conn = updateURL.openConnection(); 
InputStream is = conn.getInputStream(); 
BufferedInputStream bis = new BufferedInputStream(is); 
ByteArrayBuffer baf = new ByteArrayBuffer(50); 

int current = 0; 
while((current = bis.read()) != -1){ 
    baf.append((byte)current); 
} 

/* Convert the Bytes read to a String. */ 
String tmp = new String(baf.toByteArray()); 
int count = Integer.valueOf(tmp); 
return count; 
     } catch(Exception e) { 
      Log.e(TAG, "getAdCount Exception = " + e); 
      e.printStackTrace(); 
      return -1; 
     } 
    } 

現在我簡單的增加計數並希望將其寫入文件。
我想通了,這是可以寫一個文件用這種方法:

 BufferedWriter out = new BufferedWriter(new FileWriter("text.txt")); 
     out.write(count); 
     out.close(); 

但我怎麼打開遠程文件?我沒有找到辦法。謝謝!

#####編輯:#####
我寫了這個代碼:

 URL url = new URL("http://myserver.gov/text.txt"); 
     URLConnection con = url.openConnection(); 
     con.setDoOutput(true); 
     OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); 
     out.write(count); 
     out.close(); 

但它不寫計數的文件。

+0

我有什麼選擇? – Leandros 2012-01-31 15:02:11

+0

我的不好,一秒鐘我以爲你不得不將文件傳輸到另一臺服務器,我會刪除我的意見 – Gevorg 2012-01-31 15:13:00

回答

1

當您想使用URLConnection時,您可以按照此處的說明操作:Reading from and Writing to a URLConnection

更新:您還需要一個正在運行的服務器來處理POST請求以更新您的計數器。

+0

謝謝。我使用了參考文獻,並編寫了下面的代碼:\t \t \t'URL url = new URL(「http://myserver.gov/text.txt」); \t \t \t URLConnection con = url.openConnection(); \t \t \t con.setDoOutput(true); ();}};}};}}}} OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); \t \t \t out.write(count); \t \t \t out.close();' 但是他們沒有把計數寫到它。 – Leandros 2012-01-31 14:34:25

+0

什麼服務器正在運行?它如何處理髮布的請求? – mtsz 2012-01-31 16:09:28

+0

這是一個簡單的網絡空間。 – Leandros 2012-01-31 16:13:40

0

據我說,當你打開遠程文件時,首先你必須打開連接而不是讀取文件內容。

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity(); 

比你可以寫文件內容。