在读取/写入文件到内部/外部存储android时使用啥类和方法?

Posted

技术标签:

【中文标题】在读取/写入文件到内部/外部存储android时使用啥类和方法?【英文标题】:What class and method to use while reading/writing a file to internal/external storage android?在读取/写入文件到内部/外部存储android时使用什么类和方法? 【发布时间】:2013-09-01 22:59:00 【问题描述】:

我有很多谷歌,阅读 javadoc,并搜索不同的论坛,包括阅读问题,但没有找到我问题的正确答案。下面的代码 sn-p 工作正常,但我想确切地知道在 android 中用于读/写文件的函数。一种可以使用OutputStream,FileOutputSteam.write()写入内部存储,另一种是使用OutputStreamWriter(FileOutputSteam).write(),再使用BufferedWriter(OutputStreamWriter).write(),最后使用PrintWriter.write()。

对于 InputStream 的情况,是否使用 InputStream、FileInputSteam.read()、InputSreamReader(FileInputStream).read()、BufferedReader(InputStreamReader) 也是如此。

我想知道哪种方法最合适。请帮我解决这个问题。

public class MainActivity extends Activity 

private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "students.txt";
private EditText stdId;
private Button Insert;
private Button Search;
private Button Update;
private Button Delete;

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

    final String TAG = MainActivity.class.getName(); //output: com.fyp2.testapp.MainActivity

    //value used for insert/delete/search
    stdId = (EditText) findViewById(R.id.editTxtId);

    //insert value in application sandbox file
    Insert = (Button) findViewById(R.id.btnInsert);
    Insert.setOnClickListener(new View.OnClickListener() 

        public void onClick(View v) 

            String IdToInsert = stdId.getText().toString().trim();
            if(IdToInsert.length() > 0) 
                myInsertFunc(IdToInsert);
            
            else 
                Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
                stdId.requestFocus();
               
        
    );

    //search value from application sandbox file
    Search = (Button) findViewById(R.id.btnSearch);
    Search.setOnClickListener(new View.OnClickListener() 

        public void onClick(View v) 

            String IdToSearch = stdId.getText().toString().trim();
            if(IdToSearch.length() > 0) 
                mySearchFunc(IdToSearch);
            
            else 
                Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
                stdId.requestFocus();
            
        
    );


    //delete value from application sandbox file
    Delete = (Button) findViewById(R.id.btnDelete);
    Delete.setOnClickListener(new View.OnClickListener() 

        public void onClick(View v) 

            String IdToDelete = stdId.getText().toString().trim();
            if(IdToDelete.length() > 0) 
                myDeleteFunc(IdToDelete);
            
            else 
                Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
                stdId.requestFocus();
            
        
    );


//function to insert
private void myInsertFunc(String data) 
    //If student id already exist don't write it again -> Not handled at the moment
    //Other exceptions may not have been handled properly
    try 
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_APPEND));
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        bufferedWriter.append(data);
        bufferedWriter.newLine();

        Toast.makeText(getApplicationContext(), "Student ID: " + data + " Inserted Successfully!", Toast.LENGTH_SHORT).show();

        bufferedWriter.close();
        outputStreamWriter.close();
    
    catch (IOException e) 
        Log.e(TAG, "File write failed: " + e.toString());
     


//function to search
private void mySearchFunc(String data) 
    //Id id not found show toast to user -> Not handled at the moment
    try 
        InputStream inputStream = openFileInput(FILENAME);

        if (inputStream != null) 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            while ((receiveString = bufferedReader.readLine()) != null) 
                if(receiveString.contains(data))
                
                    Toast.makeText(getApplicationContext(), "Found Student ID: " + data , Toast.LENGTH_SHORT).show();
                    break;
                
            

            bufferedReader.close();
            inputStream.close();
        
    
    catch (FileNotFoundException e) 
        Log.e(TAG, "File not found: " + e.toString());
     catch (IOException e) 
        Log.e(TAG, "Can not read file: " + e.toString());
    


private void myDeleteFunc(String data) 
    /* I have found a solution to delete a specific line from the file.
     * But the problem is that it needs to scan the whole file line by line and copy the file contents that not matches the string to temp file.
     * This solution can reduce the effeciency. Consider search 20,000 records in a file.
     * Need to work around on it.
     */


private void myUpdateFunc(String data) 
    /* Same goes to the update process...
     * Need to scan all records and copy content in temp file and put the updated data in that file.
     * Need to work around on this issue too...
     */


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

【问题讨论】:

【参考方案1】:

它们都有一个目的。有最好的方法,因为每个作家都是有原因的。如果您有多次读/写/刷新,通常任何缓冲的东西都会更有效。

Android 和 Java 文档都有帮助,Java 文档为您提供了对这些作者的更多描述。查看这些文档。尝试阅读更详细的javase6:

Android_FileWriter

Java_FileWriter

Android_OutputStreamWriter

Java_OutputStreamWriter

Android_BufferedWriter

Java_BufferedWriter

【讨论】:

以上是关于在读取/写入文件到内部/外部存储android时使用啥类和方法?的主要内容,如果未能解决你的问题,请参考以下文章

在Android中将文件写入外部存储失败

Android——Android10的分区存储(Scoped Storage)

将json数据写入和读取到内部存储android

无法在文件夹中写入外部存储下载 - Android

如何使用 android studio 从应用程序中的内部或外部存储(SD 卡)读取文件?

Xamarin Forms:在 Android 设备的内部存储中写入文件