Android中新建文件并将EditText中的内容保存其中

来源:互联网 发布:mysql免安装版下载 编辑:程序博客网 时间:2024/05/29 19:45
package com.example.ioopt;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{
EditText write;
Button save;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
write=(EditText) findViewById(R.id.write);
save=(Button) findViewById(R.id.save);
save.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/******************************************************************************/
/*******在模拟器中的sdcard中新建一个Txt文档*************/
File file=new File("/mnt/sdcard/testdddddddddd.txt");
if(!file.exists())
{
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(MainActivity.this, "文件已存在", Toast.LENGTH_SHORT).show();

}

/******************************************************************************/

/*********************************以下部分是IO流-----字节流------输出操作*********************************************/

byte []context=new byte[100];
FileOutputStream out=null;
try {
out=new FileOutputStream(file); 
String line=write.getText().toString().trim();
//将EditText中的文字保存到文档中。
context=line.getBytes();
out.write(context, 0,context.length);

System.out.println(context);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
0 0
原创粉丝点击