【问题标题】:How to append data in a file in android如何在android中的文件中追加数据
【发布时间】:2015-05-28 16:57:48
【问题描述】:

谁能告诉我如何将数据附加到 Android 中已有数据的文件中?

我写了一些代码,但它不起作用。这是我的活动:

package updatefile.developer.com.updatefiledemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.nio.Buffer;

public class MainActivity extends ActionBarActivity {
    Button create,update;
    String data = "This is a sample";
    File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        create = (Button)findViewById(R.id.btn_create);
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File folder = new File("/sdcard/demo");
                folder.mkdirs();
                file = new File("/sdcard/demo/demotext.txt");
                try {
                    FileOutputStream fileinput = new FileOutputStream(file);
                    PrintStream printstream = new PrintStream(fileinput);
                    printstream.print(data+"\n");
                    fileinput.close();
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        });

        update = (Button)findViewById(R.id.btn_update);
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }

                try {
                    OutputStreamWriter file_writer = new OutputStreamWriter(new FileOutputStream(file,true));
                    BufferedWriter buffered_writer = new BufferedWriter(file_writer);
                    buffered_writer.write("This is a appended text");
                    buffered_writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

标签: android file append


【解决方案1】:
File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
            writer.append(data);
            writer.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

【讨论】:

    【解决方案2】:

    您唯一需要做的就是简单地添加一个"true" to FileOutputStream 喜欢

    FileOutputStream fileinput = new FileOutputStream(file,true);
    

    这是文档

    构造一个写入文件的新 FileOutputStream。如果追加是 true 并且文件已经存在,它将被追加到;否则它 将被截断。如果文件不存在,将创建该文件。

    【讨论】:

      【解决方案3】:

      FileOutputStream fileinput = new FileOutputStream(file, true);

      这是一个简单的错误,因为没有将 append 标志设置为 true。只需将其设置为true。

      默认行为是覆盖文件内容:)

      【讨论】:

      • 谢谢老兄,它就像魅力一样工作,我把它放在 FileOutputStream fileinput = new FileOutputStream(file,true);谢谢老兄的回答
      【解决方案4】:
      import java.io.BufferedReader;
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.PrintWriter;
      import android.app.Activity;
      import android.os.Bundle;
      import android.os.Environment;
      import android.util.Log;
      import android.widget.TextView;
      
       public class WriteSDCard extends Activity {
      
       private static final String TAG = "MEDIA";
       private TextView tv;
      
        /** Called when the activity is first created. */
      @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);     
          tv = (TextView) findViewById(R.id.TextView01);
          checkExternalMedia();
          writeToSDFile();
          readRaw();
       }
      
      /** Method to check whether external media available and writable. This is adapted from
         http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
      
       private void checkExternalMedia(){
            boolean mExternalStorageAvailable = false;
          boolean mExternalStorageWriteable = false;
          String state = Environment.getExternalStorageState();
      
          if (Environment.MEDIA_MOUNTED.equals(state)) {
              // Can read and write the media
              mExternalStorageAvailable = mExternalStorageWriteable = true;
          } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
              // Can only read the media
              mExternalStorageAvailable = true;
              mExternalStorageWriteable = false;
          } else {
              // Can't read or write
              mExternalStorageAvailable = mExternalStorageWriteable = false;
          }   
          tv.append("\n\nExternal Media: readable="
                  +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
      }
      
      /** Method to write ascii text characters to file on SD card. Note that you must add a 
         WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
         a FileNotFound Exception because you won't have write permission. */
      
      private void writeToSDFile(){
      
          // Find the root of the external storage.
          // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal
      
          File root = android.os.Environment.getExternalStorageDirectory(); 
          tv.append("\nExternal file system root: "+root);
      
          // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
      
          File dir = new File (root.getAbsolutePath() + "/download");
          dir.mkdirs();
          File file = new File(dir, "myData.txt");
      
          try {
              FileOutputStream f = new FileOutputStream(file);
              PrintWriter pw = new PrintWriter(f);
              pw.println("Hi , How are you");
              pw.println("Hello");
              pw.flush();
              pw.close();
              f.close();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
              Log.i(TAG, "******* File not found. Did you" +
                      " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
          } catch (IOException e) {
              e.printStackTrace();
          }   
          tv.append("\n\nFile written to "+file);
      }
      
      /** Method to read in a text file placed in the res/raw directory of the application. The
        method reads in all lines of the file sequentially. */
      
      private void readRaw(){
          tv.append("\nData read from res/raw/textfile.txt:");
          InputStream is = this.getResources().openRawResource(R.raw.textfile);
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr, 8192);    // 2nd arg is buffer size
      
          // More efficient (less readable) implementation of above is the composite expression
          /*BufferedReader br = new BufferedReader(new InputStreamReader(
                  this.getResources().openRawResource(R.raw.textfile)), 8192);*/
      
          try {
              String test;    
              while (true){               
                  test = br.readLine();   
                  // readLine() returns null if no more lines in the file
                  if(test == null) break;
                  tv.append("\n"+"    "+test);
              }
              isr.close();
              is.close();
              br.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
          tv.append("\n\nThat is all");
      }
      }
      
      also add below permission in manifeast file
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
      

      【讨论】:

        【解决方案5】:

        在 Kotlin 中,您可以通过将 Context.MODE_APPEND 作为 openFileOutput 的第二个参数传递来将数据附加到文件中。它看起来像这样:

        test_button.setOnClickListener {
                    main.openFileOutput(filename, Context.MODE_APPEND).use {
                        it.write("test".toByteArray())
                    }
                }
        

        有一些related info in the Android docs

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-23
          • 1970-01-01
          • 2016-06-07
          • 1970-01-01
          • 2016-03-18
          • 1970-01-01
          • 2013-01-22
          • 2021-11-17
          相关资源
          最近更新 更多