简体   繁体   English

使用Android应用程序中的内部存储传递数据

[英]Pass data using the internal storage in an android application

I tried to implement this example to write and read data from internal storage, but when I'm trying to read written data from the same Android application it does not give me any result. 我尝试实现此示例以从内部存储中写入和读取数据,但是当我尝试从相同的Android应用程序读取写入的数据时,它不会给我任何结果。 What can be the error?? 可能是什么错误? Following is the code I have used. 以下是我使用的代码。

public class SecondScreen extends Activity {

  String FILENAME = "hello_file";
  String string = "hello world!";



  /** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.secondscreen);

  //Using the Internal Storage
    try{
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();

    }

    catch(Exception e){

    }


     TextView result;
     result = (TextView)findViewById(R.id.status);

 try{

     String test = "";
     FileInputStream fis = openFileInput("hello_file");
     fis.read(test.getBytes());
     fis.close();
     result.setText(test);

    }

    catch(Exception e){

    }


}

manifest file : 清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wrd.ws"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".ReadWriteDataActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>

The updated code : 更新的代码:

public class ReadWriteDataActivity extends Activity {
    TextView tv;
String line;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    writeFileToInternalStorage();
    readFileFromInternalStorage();
    tv = (TextView) findViewById(R.id.textView);

// tv.setText(line); // tv.setText(line);

}
private void writeFileToInternalStorage() 
{
    String eol = System.getProperty("line.separator");
    BufferedWriter writer = null;
    try 
    {

         File myFile = new File("/sdcard/mysdfile.txt");
         myFile.createNewFile();



      writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE)));
      writer.write("This is a test1."+ eol);
      writer.write("This is a test2." + eol);
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
      if (writer != null) 
      {
        try 
        {
            writer.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
      }
    }
}



private void readFileFromInternalStorage() 
{
    String eol = System.getProperty("line.separator");
    BufferedReader input = null;
    try 
    {
        input = new BufferedReader(new InputStreamReader(openFileInput("myFile.txt")));
        //String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = input.readLine()) != null) 
        {
            buffer.append(line + eol);
        }
         tv.setText(buffer.toString().trim());
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        if (input != null) 
        {
            try 
            {
                input.close();
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

Thanks! 谢谢!

I would like to suggest you to use BufferedWriter and BufferedReader class while dealing with Flie API. 我建议您在处理Flie API时使用BufferedWriterBufferedReader类。 have a look at following methods, 看一下下面的方法,

Writing in File 写文件

private void writeFileToInternalStorage() 
{
    String eol = System.getProperty("line.separator");
    BufferedWriter writer = null;
    try 
    {
      writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile", MODE_WORLD_WRITEABLE)));
      writer.write("This is a test1." + eol);
      writer.write("This is a test2." + eol);
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
      if (writer != null) 
      {
        try 
        {
            writer.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
      }
    }
}

Reading File 读取文件

private void readFileFromInternalStorage() 
{
    String eol = System.getProperty("line.separator");
    BufferedReader input = null;
    try 
    {
        input = new BufferedReader(new InputStreamReader(openFileInput("myfile")));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = input.readLine()) != null) 
        {
            buffer.append(line + eol);
        }
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        if (input != null) 
        {
            try 
            {
                input.close();
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

Looks like you have problem in the below code: 看起来您在以下代码中有问题:

String test = "";
FileInputStream fis = openFileInput("hello_file");
fis.read(test.getBytes());

You are passing test.getBytes() and test is of in-sufficient size. 您正在传递test.getBytes()并且test的大小不足。 So the fix is to read bytes in an array. 因此解决方法是读取数组中的字节。

byte[] allBytes = new byte[100];
int indexInAllBytes = 0;
int bytesRead = 0;
FileInputStream fis = openFileInput("hello_file");

while(bytesRead != -1) {
  bytesRead = fis.read(allBytes, indexInAllBytes, allBytes.length);

  indexInAllBytes+=bytesRead;

  if(indexInAllBytes >= allBytes.length) {
     // We are exceeding the buffer size. Need bigger bytes array
     break;
  }
  // Also you can convert into string using StringBuilder.
}

NOTE: BufferedReader(s) are good for reading/writing text files. 注意:BufferedReader非常适合读取/写入文本文件。 If you want binary files then you can use the above logic with slight improvements. 如果需要二进制文件,则可以使用上面的逻辑进行一些改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM