Android读写文件、写文件到SD卡

主界面:MainActivity.java

package com.example.logindialogSD;

import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.logindialog.R;
import com.example.logindialogSD.service.LoginService;

public class MainActivity extends ActionBarActivity {
	private static final String TAG = "loginDialog";
	private EditText et_username;
	private EditText et_password;
	private CheckBox cb;
	private RadioGroup rg_mode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		cb = (CheckBox) findViewById(R.id.cb);
		rg_mode = (RadioGroup) findViewById(R.id.rg_mode);
		Map<String, String> userinfo = null;
		if ((userinfo = LoginService.getSavedUserInfo(this)) != null) {
			et_username.setText(userinfo.get("username"));
			et_password.setText(userinfo.get("password"));
		}
	}

	public void login(View view) {
		String username = et_username.getText().toString().trim();
		String password = et_password.getText().toString().trim();
		int id = rg_mode.getCheckedRadioButtonId();
		int mode = Context.MODE_PRIVATE;
		switch (id) {
		case R.id.rd_private:
			break;
		case R.id.rd_readable:
			mode = Context.MODE_WORLD_READABLE;
			break;
		case R.id.rd_writeable:
			mode = Context.MODE_WORLD_WRITEABLE;
			break;
		case R.id.rd_public:
			mode = Context.MODE_WORLD_READABLE
			+ Context.MODE_WORLD_WRITEABLE;
			break;

		default:
			break;
		}
		if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
			Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
		} else {
			if (cb.isChecked()) {
				Log.i("ZYL", "保存用户名和密码");
				boolean result = LoginService.saveUserInfo(this, username,
						password,mode);
				if (result) {
					Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
				} else
					Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
				
			}

		}

	}
}

附带的activity_main.xml

<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请输入用户名:" />

    <EditText
        android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请输入密码:" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

    <RadioGroup
        android:orientation="horizontal"
        android:id="@+id/rg_mode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >

        <RadioButton
            android:id="@+id/rd_private"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="私有" />

        <RadioButton
            android:id="@+id/rd_readable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="可读" />

        <RadioButton
            android:id="@+id/rd_writeable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="可写" />

        <RadioButton
            android:id="@+id/rd_public"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="公开" /> 
        
    </RadioGroup>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="记住密码" >
        </CheckBox>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:onClick="login"
            android:text="登陆" />
    </RelativeLayout>

</LinearLayout>

保存文件到手机卡LoginService.java:

package com.example.logindialog.service;

import java.io.BufferedReader;

public class LoginService {
	/**
	 * 保存用户名和密码的业务方法
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 是否成功
	 */
	public static boolean saveUserInfo(Context context, String username,
			String password, int mode) {
		try {
			// File file = new
			// File("data/data/com.example.logindialog/info.txt");
			// context.getFIlesDir - > data/data/包名/files
			// File file = new File(context.getFilesDir(), "info.txt");
			// FileOutputStream fos = new FileOutputStream(file);
			// zhang##123
			switch (mode) {
			//只能由自己程序读写
			case Context.MODE_PRIVATE:
				mode = Context.MODE_PRIVATE;
				break;
			//可读
			case Context.MODE_WORLD_READABLE:
				mode = Context.MODE_WORLD_READABLE;
				break;
			//可写
			case Context.MODE_WORLD_WRITEABLE:

				mode = Context.MODE_WORLD_WRITEABLE;
				break;
			//可读写
			case Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE:

				mode = Context.MODE_WORLD_READABLE
						+ Context.MODE_WORLD_WRITEABLE;
				break;

			default:
				mode = Context.MODE_PRIVATE;
				break;
			}
			FileOutputStream fos = context.openFileOutput("private", mode);
			fos.write((username + "##" + password).getBytes());
			fos.close();// (可能close的时候会flush一下)
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static Map<String, String> getSavedUserInfo(Context context) {
		FileInputStream fis;
		try {
			fis = new FileInputStream(new File(context.getFilesDir(),
					"info.txt"));
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String str = br.readLine();
			String[] infos = str.split("##");
			Map<String, String> userinfo = new HashMap<String, String>();
			userinfo.put("username", infos[0]);
			userinfo.put("password", infos[1]);
			return userinfo;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}

注意,android只能读写自己包的文件...访问其他包会报错

关于Linux访问权限科普:

Linux文件访问权限                                                               
        -         ---            ---             ---           (共10个)
当前用户   当前用户 当前用户组 其他用户
  - | d        rwx           rwx              rwx         
-------------------解释------------------
-文件           r可读        
r可读          r可读
d可读          w可写       
w可写        w可写
                    x可执行    
x可执行     x可执行

------example------------------

- rw- rw- rw-       0 110 110 110 ->  6 6 6 (八进制)       当前用户、用户组、其他用户可访问
d rw- rw- ---       1 110 110 000 ->  1 6 6 0 (八进制)     当前用户、用户组可访问 | 其他用户不可访问
 
所以更改Linux文件访问权限的时候可以使用 chmod(changeMode)来更改
如 chmod 666 zyl.txt      这样的话所有用户的程序都能访问这个程序了 

详情:http://blog.csdn.net/me10zyl/article/details/26883579

读写SD卡文件LoginService.java

package com.example.logindialogSD.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;

public class LoginService {
	/**
	 * 保存用户名和密码的业务方法
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 是否成功
	 */
	public static boolean saveUserInfo(Context context, String username,
			String password, int mode) {
		try {
			// File file = new
			// File("data/data/com.example.logindialog/info.txt");
			// context.getFIlesDir - > data/data/包名/files
			if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
				File file = new File(Environment.getExternalStorageDirectory(),"sdinfo.txt");
//				File file = new File("sdcard/sdinfo.txt");
				FileOutputStream fos = new FileOutputStream(file);
				// zhang##123
				// switch (mode) {
				// case Context.MODE_PRIVATE:
				// mode = Context.MODE_PRIVATE;
				// break;
				// case Context.MODE_WORLD_READABLE:
				// mode = Context.MODE_WORLD_READABLE;
				// break;
				// case Context.MODE_WORLD_WRITEABLE:
				//
				// mode = Context.MODE_WORLD_WRITEABLE;
				// break;
				// case Context.MODE_WORLD_READABLE +
				// Context.MODE_WORLD_WRITEABLE:
				//
				// mode = Context.MODE_WORLD_READABLE
				// + Context.MODE_WORLD_WRITEABLE;
				// break;
				//
				// default:
				// mode = Context.MODE_PRIVATE;
				// break;
				// }
				// FileOutputStream fos = context.openFileOutput("private",
				// mode);
				fos.write((username + "##" + password).getBytes());
				fos.close();// (可能close的时候会flush一下)
				return true;
			} else
			{
				Toast.makeText(context, "SD卡不可用", Toast.LENGTH_SHORT).show();
				return false;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("resource")
	public static Map<String, String> getSavedUserInfo(Context context) {
		FileInputStream fis;
		try {
			fis = new FileInputStream(new File("sdcard/sdinfo.txt"));
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String str = br.readLine();
			String[] infos = str.split("##");
			Map<String, String> userinfo = new HashMap<String, String>();
			userinfo.put("username", infos[0]);
			userinfo.put("password", infos[1]);
			return userinfo;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}

因为SD卡权限是d --- rwx r-x

对于别的用户是可读不可写..所以写的时候必须要权限android.permission.WRITE_EXTERNAL_STORAGE

不过Android4.0以后为了防止恶意程序上传用户隐私,用户可勾选SD卡读取保护。这时需要权限android.permission.READ_EXTERNAL_STORAGE

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值