读写应用的data/data的files目录的文件

@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		String valueString = "dfjkdjfkdjfjieurieuriewuorewioreir";
		try {
			writeDateFile("name", valueString.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			String value = readDateFile("name");
			Log.d("test", "___value__" + value);
			Log.d("test", "___value.length()__" + value.length());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 将文件写入应用的data/data的files目录下
	public void writeDateFile(String fileName, byte[] buffer) throws Exception {
		byte[] buf = fileName.getBytes("iso8859-1");
		fileName = new String(buf, "utf-8");
		// Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
		// Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
		// Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
		// MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
		// 如果希望文件被其他应用读和写,可以传入:
		// openFileOutput("output.txt", Context.MODE_WORLD_READABLE +
		// Context.MODE_WORLD_WRITEABLE);
		FileOutputStream fos = FilesDemoActivity.this.openFileOutput(fileName,
				Context.MODE_PRIVATE);// 添加在文件后面
		fos.write(buffer);
		fos.close();
	}

	// 读取应用的data/data的files目录下文件数据
	public String readDateFile(String fileName) throws Exception {
		FileInputStream fis = FilesDemoActivity.this.openFileInput(fileName);
		String result = streamRead(fis);// 返回一个字符串
		return result;
	}

	private String streamRead(InputStream is) throws IOException {
		int buffersize = is.available();// 取得输入流的字节长度
		byte buffer[] = new byte[buffersize ];
		is.read(buffer);// 将数据读入数组
		is.close();// 读取完毕后要关闭流。
		String result = EncodingUtils.getString(buffer, "UTF-8");// 设置取得的数据编码,防止乱码
		return result;
	}

猜你喜欢

转载自justwyy.iteye.com/blog/1769430