![](/img/trans.png)
[英]How to open a path in remote machine and write a file in that path using java
[英]Open remote file and write to it
我在服务器上打开一个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();
但是它不会将计数写入文件。
当您要使用URLConnection时,可以按照以下说明进行操作: 从URLConnection读取和写入URLConnection 。
更新 :您还将需要运行中的服务器来处理POST请求以更新您的计数器。
据我说。当您打开远程文件时。首先您必须打开连接而不是读取文件内容。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
比您可以写入的文件内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.