简体   繁体   中英

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.

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 .

Update : You will also need a running server handling POST requests to update your counter.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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