如何将数据写入 android 中的远程文本文件。我能够读取文本文件的内容,但无法向其中写入数据。我的目标是将文本文件的内容更改为新文件。我使用 xampp 作为远程服务器,因为我家里没有互联网连接。
这是我的代码:
package com.example.viewtextfromremote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView display;
Button change, refresh;
EditText edit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.tvDisplay);
change = (Button) findViewById(R.id.bChange);
refresh = (Button) findViewById(R.id.bRefresh);
edit = (EditText) findViewById(R.id.etChange);
try {
// Create a URL for the desired page
URL url = new URL("http://10.0.2.2/name.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = in.readLine();
in.close();
display.setText(str);
} catch (IOException e) {
display.setText("io");
}
change.setOnClickListener(this);
refresh.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bChange:
try {
String output = edit.getText().toString();
URL url = new URL("http://10.0.2.2/name.txt");
URLConnection con = url.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(output);
out.close();
} catch (Exception e) {
// TODO: handle exception
}
break;
case R.id.bRefresh:
try {
// Create a URL for the desired page
URL url = new URL("http://10.0.2.2/name.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = in.readLine();
in.close();
display.setText(str);
} catch (IOException e) {
display.setText("io");
}
break;
default:
break;
}
}
}