三个文件:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="MissingDefaultResource"> <!--<TextView--> <!--android:layout_width="wrap_content"--> <!--android:layout_height="wrap_content"--> <!--android:text="Hello World!"--> <!--app:layout_constraintBottom_toBottomOf="parent"--> <!--app:layout_constraintLeft_toLeftOf="parent"--> <!--app:layout_constraintRight_toRightOf="parent"--> <!--app:layout_constraintTop_toTopOf="parent" />--> <EditText android:id="@+id/editText2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginTop="8dp" android:text="CreateFile" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </android.support.constraint.ConstraintLayout>
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.aimee.editor"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!--<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
MainActivity.java
package com.example.aimee.editor; import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; //public class MainActivity extends AppCompatActivity{ // TextView textView;//声明为全局变量 //// @Override // public void onCreate(Bundle savedInstanceState){ // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main1); // final Button button1=(Button)findViewById(R.id.myButton1); // final Button button2=(Button)findViewById(R.id.myButton2); // final Button button3=(Button)findViewById(R.id.myButton3); // /*因为上面定义的Button对象被另外一个程序(setOnCLickListener)引用,需将该对象声明为常量,否则编译失败.*/ // textView=(TextView)findViewById(R.id.myTextView); // Context context=this.getBaseContext(); // final Drawable red_Drawable=ContextCompat.getDrawable(context,R.drawable.RED); // final Drawable blue_Drawable=ContextCompat.getDrawable(context,R.drawable.BULE); // final Drawable yellow_Drawable=ContextCompat.getDrawable(context,R.drawable.YELLOW); // // button1.setOnClickListener(new View.OnClickListener(){ // public void onClick(View v){ // String str="You have clicked"+button1.getText().toString(); // textView.setText(str); // if(textView.getBackground()!=red_Drawable) // textView.setBackground(red_Drawable); // } // }); // // button2.setOnClickListener(new View.OnClickListener(){ // public void onClick(View v){ // String str="You have clicked"+button2.getText().toString(); // textView.setText(str); // if(textView.getBackground()!=blue_Drawable) // textView.setBackground(blue_Drawable); // } // }); // // button3.setOnClickListener(new View.OnClickListener(){ // public void onClick(View v){ // String str="You have clicked"+button3.getText().toString(); // textView.setText(str); // if(textView.getBackground()!=yellow_Drawable) // textView.setBackground(yellow_Drawable); // } // }); // } // // public boolean onKeyDown(int keyCode, KeyEvent event){ // CharSequence charseq="You have pressed"; // charseq=charseq+"a key!"; // textView.setText(charseq); // return super.onKeyDown(keyCode,event); // } // // public boolean onKeyUp(int keyCode,KeyEvent event){ // CharSequence charseq="Change your color here!"; // textView.setText(charseq); // textView.setBackgroundColor(Color.WHITE); // return super.onKeyDown(keyCode,event); // } //} // //public class MainActivity extends AppCompatActivity { // private EditText file_name;//定义输入文件名的文本框 // private EditText file_content;//定义输入文件内容的文本框 // private Button read_button;//定义读取文件的按钮 // private Button save_button;//定义保存文件的按钮 // public static int LONGTIME=Toast.LENGTH_LONG;//定义Toast消息显示的时间 // //// @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main1);//使用activity_main初始化程序界面 // read_button=(Button)findViewById(R.id.read_file); // save_button=(Button)findViewById(R.id.save_file); // file_name=(EditText)findViewById(R.id.file_name); // file_content=(EditText)findViewById(R.id.file_content); // /*获取xml定义的控件对象read_button、save_button、file_name和file_content*/ // // save_button.setOnClickListener(new View.OnClickListener() { //// @Override // public void onClick(View view) { // String str_file_name=file_name.getText().toString();//获取保存的文件名 // if(str_file_name=="") { // Toast.makeText(getApplicationContext(), "文件名为空", LONGTIME).show(); // } else{ // String str_file_content=file_content.getText().toString();//获取file_content的内容 // try{ // save(str_file_name,str_file_content);//保存内容str_file_content到文件str_file_name // Toast.makeText(getApplicationContext(), "保存成功", LONGTIME).show(); // } // catch (Exception e){ // Toast.makeText(getApplicationContext(),"保存失败",LONGTIME).show(); // } // /*若保存成功,则显示保存成功的Toast消息,否则程序抛出异常,显示保存失败的Toast消息*/ // } // } // }); // /*注册save_button单击事件监听器。当单击该按钮时,保存当前编辑的文件*/ // // read_button.setOnClickListener(new View.OnClickListener() { //// @Override // public void onClick(View view) { // String str_file_name=file_name.getText().toString();//获取读取的文件名 // if(str_file_name=="")//判断是否指定文件名 // Toast.makeText(getApplicationContext(), "文件名为空", LONGTIME).show(); // else{ // try{ // String str_fiel_content=read(str_file_name);//读取文件str_file_name内容 // file_content.setText(str_fiel_content); // } // catch (Exception e){ // Toast.makeText(getApplicationContext(),"failed",LONGTIME).show(); // } // /*若保存成功,则显示保存成功的Toast消息,否则程序抛出异常,显示保存失败的Toast消息*/ // } // } // }); // } // /*注册read_button单击事件监听器。当单击该按钮时,根据文件名读取内容*/ // // public void save(String file,String fileContent) throws Exception{ // //Context类提供了系统核心操作借口,它是Activity的父类 // FileOutputStream fileOutputStream=openFileOutput(file, Context.MODE_PRIVATE); // //以MODE_PRIVATE模式获取指定文件的文件输出流 // fileOutputStream.write(fileContent.getBytes());//将fileContent写入文件 // } // /*方法save负责将指定的内容(fileContent)写入到文件*/ // // public String read(String file) throws Exception{ // byte[] buf=new byte[1024]; // int size=0; // FileInputStream fileInputStream=openFileInput(file);//获取指定文件的文件输入流 // ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); // //生成字节数据输入流对象,该对象实现按字节读取内容 // while((size=fileInputStream.read(buf))>0){ // byteArrayOutputStream.write(buf,0,size); // } // /*若fileInputStream有数据,则将其写入ByteArrayOutputStream对象byteArrayOutputStream中*/ // return byteArrayOutputStream.toString(); // } // /*方法read负责读取指定的文件*/ //} public class MainActivity extends AppCompatActivity{ private EditText editText2; private Button button1; private final int REQUESTCODE=101; String filePath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"save"; String fileName="/"+"save.txt"; // @Override // protected void onCreate(Bundle savedInstanceState){ // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main1); // initView(); // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText2=(EditText)findViewById(R.id.editText2); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { switch (v.getId()){ case R.id.button: Toast.makeText(MainActivity.this,editText2.getText().toString().trim(),Toast.LENGTH_LONG).show(); // writeTxtToFile(editText2.getText().toString().trim(),filePath,fileName); readTxtToFile(filePath,fileName); break; default: break; } // create(fileName,filePath); } catch (IOException e) { e.printStackTrace(); } } }); } public void create(String fileName,String filePath) throws IOException { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ int checkSelfPermission=checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); if(checkSelfPermission==PackageManager.PERMISSION_DENIED){ requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUESTCODE); } } File file=new File(filePath); if(!file.exists()){ Toast.makeText(MainActivity.this,filePath,Toast.LENGTH_LONG).show(); boolean isSuccess=file.mkdirs(); Toast.makeText(MainActivity.this,"文件夹创建成功",Toast.LENGTH_LONG).show(); }else{ String file_name=filePath+fileName; File f=new File(file_name); if(!f.exists()){ Toast.makeText(MainActivity.this,file_name,Toast.LENGTH_LONG).show(); f.createNewFile(); Toast.makeText(MainActivity.this,"文件创建成功",Toast.LENGTH_LONG).show(); } else{ Toast.makeText(MainActivity.this,"文件已存在",Toast.LENGTH_LONG).show(); } } } public void writeTxtToFile(String strcontent,String filePath,String fileName) throws IOException { Toast.makeText(MainActivity.this,fileName,Toast.LENGTH_LONG).show(); String strFilePath=filePath+fileName; String strContent=strcontent+" "; File file=new File(strFilePath); RandomAccessFile raf=new RandomAccessFile(file,"rwd"); raf.seek(file.length()); raf.write(strContent.getBytes()); raf.close(); } public void readTxtToFile(String filePath,String fileName) throws IOException { String strFilePath=filePath+fileName; File file=new File(strFilePath); RandomAccessFile raf=new RandomAccessFile(file,"rwd"); int j=0; while(raf.readLine()!=null){ j=j+1; } raf.seek(0); for (int i=0;i<j;i++){ Toast.makeText(MainActivity.this, new String(raf.readLine().getBytes("ISO-8859-1"),"utf8"), Toast.LENGTH_LONG).show(); } // Toast.makeText(MainActivity.this,raf.readLine(),Toast.LENGTH_LONG).show(); raf.close(); } // public File makeFilePath(String filePath,String fileName){ // File file=null; // makeRootDirectory(filePath); // try{ // file=new File(filePath+fileName); // if(!file.exists()){ // file.createNewFile(); // } // } catch (IOException e) { // e.printStackTrace(); // } // return file; // } // // public static void makeRootDirectory(String filePath){ // File file=null; // try{ // file=new File(filePath); // if(!file.exists()){ // file.mkdir(); // } // } // catch (Exception e){ // e.printStackTrace(); // } // } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ super.onRequestPermissionsResult(requestCode,permissions,grantResults); if(requestCode==REQUESTCODE){ if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0]== PackageManager.PERMISSION_GRANTED){ Toast.makeText(MainActivity.this,"111",Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"222",Toast.LENGTH_LONG).show(); } } } }
如果创建文件夹和文件,就打开Create(fileName,filePath)。
如果存入数据,就打开
writeTxtToFile(editText2.getText().toString().trim(),filePath,fileName);
如果读取数据,就打开
readTxtToFile(filePath,fileName);