【问题标题】:write text file in res/raw folder在 res/raw 文件夹中写入文本文件
【发布时间】:2016-12-25 10:43:57
【问题描述】:

我在文件夹 res/raw 名称“pass.txt”中有一个文本文件,其中有一些数据我想删除这些数据并在其中输入新数据....可以在上面写入数据吗?否则存储我的文本文件的正确路径是什么,以便我可以轻松地在其上读取/写入数据......以及从中读取和写入数据的代码是什么?下面是我只能从这个文本文件中读取数据的代码

InputStream fr = getResources().openRawResource(R.raw.pass);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fr));
                    String s=br.readLine().toString().trim();

【问题讨论】:

  • 您无法将文件写入原始文件夹。它的只读...

标签: android text-files file-handling


【解决方案1】:

项目中原始目录中包含的资源将打包在您的 APK 中,并且在运行时不可写入。

查看内部或外部数据存储 API 以读写文件。

https://developer.android.com/training/basics/data-storage/files.html

【讨论】:

    【解决方案2】:

    您可以使用 Android 内部存储来读取和写入文件...因为 res/raw 是只读的...您不能在运行时更改内容。

    代码如下:

    创建文件

     String MY_FILE_NAME = “mytextfile.txt”;
    // Create a new output file stream 
    FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
    // Create a new file input stream.
    FileInputStream fileis = openFileInput(My_FILE_NAME);
    

    从文件中读取:

     public void Read(){
    static final int READ_BLOCK_SIZE = 100;
    try {
                FileInputStream fileIn=openFileInput("mytextfile.txt");
                InputStreamReader InputRead= new InputStreamReader(fileIn);
    
                char[] inputBuffer= new char[READ_BLOCK_SIZE];
                String s="";
                int charRead;
    
                while ((charRead=InputRead.read(inputBuffer))>0) {
                    // char to string conversion
                    String readstring=String.copyValueOf(inputBuffer,0,charRead);
                    s +=readstring;                 
                }
                InputRead.close();
                Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    

    写入文件:

    public void Write(){
    try {
            FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write("TEST STRING..");
            outputWriter.close();
    
            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!",
            Toast.LENGTH_SHORT).show();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    【讨论】:

    • openFileOutput 和 openFileInput 不工作显示错误
    • 你必须导入 java.io.FileInputStream;并导入 java.io.FileOutputStream;
    • 如果你不在Activity中...你必须在openFile之前写getApplicationContext()
    • 在你测试了代码并且它对你有用之后,你的接受投票应该终于来了...不是在回答一个问题后很快...
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多