Android 如何将数据写入文件

Android 如何将数据写入文件,android,file,Android,File,在以下几行中,我在“Environment.getExternalStorageDirectory()中创建了一个文件 我的问题是:如何将文本数据写入此创建的文件?您可以使用写入文件来将文本输出到文件。您可以使用具有不同有用方法的类来写入数据。您还可以从以下内容查看流: 下面是一个将数据写入文件的快速片段。请注意,它被设计为在一个单独的线程中运行,因此您不会在主UI线程中执行文件IO new Thread(new Runnable() { public void run() { St

在以下几行中,我在“Environment.getExternalStorageDirectory()中创建了一个文件


我的问题是:如何将文本数据写入此创建的文件?

您可以使用写入文件来将文本输出到文件。您可以使用具有不同有用方法的类来写入数据。您还可以从以下内容查看流


下面是一个将数据写入文件的快速片段。请注意,它被设计为在一个单独的线程中运行,因此您不会在主UI线程中执行文件IO

new Thread(new Runnable() {
  public void run() {
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
  }
}).start();

您要创建什么类型的文件?文本?二进制文件?我试过了,但是当我检查文件是否真的被创建时,我发现没有创建任何文件
//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_WORLD_READABLE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}
new Thread(new Runnable() {
  public void run() {
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
  }
}).start();