有谁能告诉我如何在Android中向已有数据的文件追加数据?
我编写了一些代码,但它没有起作用。这是我的活动:
package updatefile.developer.com.updatefiledemo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.nio.Buffer;
public class MainActivity extends ActionBarActivity {
Button create,update;
String data = "This is a sample";
File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
create = (Button)findViewById(R.id.btn_create);
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File folder = new File("/sdcard/demo");
folder.mkdirs();
file = new File("/sdcard/demo/demotext.txt");
try {
FileOutputStream fileinput = new FileOutputStream(file);
PrintStream printstream = new PrintStream(fileinput);
printstream.print(data+"\n");
fileinput.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
update = (Button)findViewById(R.id.btn_update);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
try {
OutputStreamWriter file_writer = new OutputStreamWriter(new FileOutputStream(file,true));
BufferedWriter buffered_writer = new BufferedWriter(file_writer);
buffered_writer.write("This is a appended text");
buffered_writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}