从手机内存rom中读取数据

package com.example.dataread;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity implements OnClickListener {


private EditText username;
private EditText userpwd;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

username = (EditText)findViewById(R.id.editText1);
userpwd = (EditText)findViewById(R.id.editText2);
login = (Button)findViewById(R.id.button1);

login.setOnClickListener(MainActivity.this);

try {
File file = new File("/data/data/com.example.datasave/files/context.txt");

FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int len;
while((len =in.read(buffer))!= -1){

bos.write(buffer, 0, len);
}

byte[] result = bos.toByteArray();

String context = new String(result);

String[] array = context.split(":");
System.out.println(context);
username.setText(array[0]);
userpwd.setText(array[1]);
} catch (Exception e) {
// TODO: handle exception
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.main, menu);
return true;
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
System.out.println("fsdg");
File file = new File("/data/data/com.example.datasave/files/context.txt");
try {
FileOutputStream fos = new FileOutputStream(file);

fos.write("haha:123".getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;


}

}


}


    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


            android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >
   


            android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />




                    android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加" 
            />





一定要注意所读程序的权限,权限参考将数据写入手机内存rom中点击打开链接

你可能感兴趣的:(android基础)