简体   繁体   English

打开远程文件并写入

[英]Open remote file and write to it

I open a txt file on my server, get the Int and want to increment the int by 1 and write it to the file again. 我在服务器上打开一个txt文件,获取Int并想将int递增1,然后再次将其写入文件。

I get the file with this method: 我用这种方法得到文件:

    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;
        }
    }

now I simply increment the count and want to write it to the file. 现在,我只是简单地增加计数并想将其写入文件。
I figured out, that it is possible to write to a file with this method: 我发现,可以使用此方法写入文件:

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

But how I open the remote file? 但是如何打开远程文件? I dont find a way. 我找不到办法。 Thanks! 谢谢!

##### Edit: ##### #####编辑:#####
I have written this code: 我写了这段代码:

        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();

But it doesnt write the count to the file. 但是它不会将计数写入文件。

When you want to work with URLConnection you can follow the instructions here: Reading from and Writing to a URLConnection . 当您要使用URLConnection时,可以按照以下说明进行操作: 从URLConnection读取和写入URLConnection

Update : You will also need a running server handling POST requests to update your counter. 更新 :您还将需要运行中的服务器来处理POST请求以更新您的计数器。

According to me .When you are open remote file.Firstly you have to open connection than read file content. 据我说。当您打开远程文件时。首先您必须打开连接而不是读取文件内容。

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

than you can write file content. 比您可以写入的文件内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM