2012-01-31 88 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(); 

比你可以写文件内容。