Reputation: 16825
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.
Upvotes: 1
Views: 9136
Reputation: 2855
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.
Upvotes: 1
Reputation: 35
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.
Upvotes: 0