文件在android中读/写

时间:2016-04-15 11:51:51

标签: android

我使用的是Windows 7,Android SDK 2.0版。此应用程序有3个editViews用于输入数据,2个按钮用于保存和显示数据,但应用程序没有显示任何内容,我已经添加了两个用户权限读写

'package com.example.anshul.writing_to_external;

import android.os.Environment;
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.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

EditText edit_book,edit_pub,edit_price;
Button btnsave,btndisplay;
String state;
TextView displaytext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edit_book=(EditText)findViewById(R.id.edit_book);
    edit_pub=(EditText)findViewById(R.id.edit_pub);
    edit_price=(EditText)findViewById(R.id.edit_price);

    displaytext=(TextView)findViewById(R.id.display_text);

    btnsave=(Button)findViewById(R.id.btnsave);
    btndisplay=(Button)findViewById(R.id.btndisplay);

    btnsave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            state= Environment.getExternalStorageState();
            if(Environment.MEDIA_MOUNTED.equals(state)){
                String b_name=edit_book.getText().toString();
                String b_pub=edit_pub.getText().toString();
                String b_price=edit_price.getText().toString();
                String str="Book Name : "+b_name+"Book Publisher : "+b_pub+"Book Price : "+b_price;
                Toast.makeText(getBaseContext(),"Saved "+str,Toast.LENGTH_LONG).show();
                try{
                    File sdcard = getExternalFilesDir(null);
                    File directory=new File(sdcard.getAbsolutePath()+"/MyFiles/");
                    directory.mkdirs();


                    File file=new File(directory,"bookDetails.txt");
                    Toast.makeText(getBaseContext(),sdcard.canRead()?"Yes Read":"No Read",Toast.LENGTH_LONG).show();
                    FileOutputStream fout= new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fout);
                    osw.write(str);
                    osw.flush();
                    osw.close();
                    fout.close();

                    edit_book.setText("");
                    edit_pub.setText("");
                    edit_price.setText("");
                }
                catch (IOException e){
                    e.printStackTrace();
                }

        }
            else
            {
                Toast.makeText(getBaseContext(),"Memory Card Not Present",Toast.LENGTH_LONG).show();
            }}
    });

    btndisplay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            state= Environment.getExternalStorageState();
            if(Environment.MEDIA_MOUNTED.equals(state)){
                StringBuilder str = new StringBuilder();
                String sL;

                try{
                    File sdcard = getExternalFilesDir(null);
                    File directory=new File(sdcard.getAbsolutePath()+"/MyFiles/");

                    File file=new File(directory,"bookDetails.txt");
                    Toast.makeText(getBaseContext(),"Saved "+getFilesDir(),Toast.LENGTH_LONG).show();
                    Toast.makeText(getBaseContext(),sdcard.canWrite()?"Yes write":"No write",Toast.LENGTH_LONG).show();
                    FileInputStream fout= new FileInputStream(file);
                    InputStreamReader osw = new InputStreamReader(fout);
                    BufferedReader br = new BufferedReader(osw);

                    while ((sL=br.readLine())!=null){
                        str.append(sL);
                    }
                    br.close();
                    osw.close();
                    fout.close();

                    displaytext.setText(sL);
                }
                catch (IOException e){
                    e.printStackTrace();
                }

            }
            else
            {
                Toast.makeText(getBaseContext(),"Memory Card Not Present",Toast.LENGTH_LONG).show();
            }
        }
    });
    }
}`

1 个答案:

答案 0 :(得分:0)

这是因为在保存文件后,您无法立即阅读。

MediaScanner需要一些时间才能了解sdCard中保存的文件

使用此 -

       MediaScannerConnection.scanFile(this,
                new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });

其中file是File file = new File(path,FILE_NAME +" .txt");