将字符串数据追加(添加)到 Android 应用程序中的 SD 卡文本文件

Append (add) String data to an SD Card text file in an Android application(将字符串数据追加(添加)到 Android 应用程序中的 SD 卡文本文件)

本文介绍了将字符串数据追加(添加)到 Android 应用程序中的 SD 卡文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里只是一个简短的点.尽管我的代码似乎可以使用在内部或外部(SD 卡)存储中写入 mytext.txt 文件的标准技术将字符串数据等存储在新文件中,但我的应用程序对我来说更有用通过重复允许用户重复该过程(例如用户输入和按钮保存)或关闭应用程序并重新开始,将更多数据添加到同一目录中的同一文件,因此除非用户选择手动删除,否则数据将永久保留那个数据.使用条件语句检查文件或目录是否存在似乎对情况没有影响,我得到与以前相同的结果(一个答案).还要改变一种写入方法,例如 osw.write(myStr);到 osw.append(myStr);保持不变.代码或应用程序中没有错误.这是 MainActivity Java 文件中的典型代码

Just a quick point here. Although my code seems to be okay storing String data etc. in a new file using the standard techniques of writing to a mytext.txt file in an internal or external (SD Card) storage, it is of more use to me for my App to add more data to the same file in the same directory by repeating allowing the user to repeat the process (e.g. a user input and button save) or closing the App and starting over again, so the data permanently remains unless the user chooses to manually delete that data. Using conditional statements to check if the file or directory exists appears to make no difference to the situation and I get the same result as before (one answer). Also changing a writing method such as osw.write(myStr); to osw.append(myStr); remains the same. There are no errors in the code or application. Here is typical code in part of the MainActivity Java file

//earlier code
try
{
    File sdCard = Environment.getExternalStorageDirectory();
    File directory = new File (sdCard.getAbsolutePath() +
    "/MyFiles");
    if (!directory.exists())
    {
        directory.mkdirs();
    }

    File file = new File(directory, "mytext.txt");
     if (!file.exists()) 
     {    
         file.createNewFile();
     } 
    FileOutputStream fOut = new FileOutputStream(file);

    OutputStreamWriter osw = new
            OutputStreamWriter(fOut);

//---write the string to the file---
osw.write(myStr);
osw.flush();
osw.close();

}
catch (IOException ioe)
{
ioe.printStackTrace();
}

// continued code ...

ps.在我的设备上,mytext.txt 文件存储在内部存储中(可能名称为 sdcard0 ?),而不是期望它位于可访问/可移动的 SD 卡中.

ps. On my device, the mytext.txt file is stored in Internal storage (possible name sdcard0 ?) rather than expecting it to be in the the accessible/removable SD Card.

推荐答案

改变

FileOutputStream fOut = new FileOutputStream(file);

FileOutputStream fOut = new FileOutputStream(file, true);

见http://developer.android.com/reference/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)

see http://developer.android.com/reference/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)

这篇关于将字符串数据追加(添加)到 Android 应用程序中的 SD 卡文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将字符串数据追加(添加)到 Android 应用程序中的 SD 卡文本文件

基础教程推荐