---
title: "存储方式二:文件（文本文件）"
author: "DanielHan"
date: "2014-07-08T13:37:40Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2014-07-08T11:57:04Z"
id: 2089394
url: "https://danielhan.iteye.com/blog/2089394"
---

**一.写**

```java

		FileOutputStream output=null;
		try {
			output=openFileOutput("1.txt", MODE_PRIVATE);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PrintStream print=new PrintStream(output);
		print.println("姓名：DanielHan");
		print.println("年龄：10");
		print.close();

```


**二.读**

```java

private TextView txt=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		txt=(TextView)findViewById(R.id.txt);
		FileInputStream input=null;
		try {
			input=openFileInput("1.txt");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Scanner scanner=new Scanner(input);
		while(scanner.hasNext()){
			txt.append(scanner.next()+"\n");
		}
		scanner.close();
	}

```

结果：

![](http://dl2.iteye.com/upload/attachment/0098/8747/c5ce0ca2-0767-307f-98ab-a006faa67898.png)

**三.向sdcard写**

```java

		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			File file=new File(Environment.getExternalStorageDirectory()+File.separator+"files/2.txt");
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			PrintStream print=null;
			try {
				print = new PrintStream(new FileOutputStream(file));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			print.println("姓名：DanielHan");
			print.println("年龄：10");
			print.close();
		}else{
			Toast.makeText(this, "没有sdcard",Toast.LENGTH_SHORT).show();
		}

```