采得百花成蜜后,为谁辛苦为谁甜。这篇文章主要讲述安卓存储之文件存储方式j相关的知识,希望能为你提供帮助。
支持往文件中读写数据,创建新的文件
【安卓存储之文件存储方式j】Main
package com.chuanxidemo.shaoxin.demo06; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Created by shaoxin on 2017/2/23. */public class Main extends AppCompatActivity { private Button read; private Button write; private FileOutputStream outputStream; private FileInputStream inputStream; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); read = (Button) findViewById(R.id.read); write = (Button) findViewById(R.id.write); read.setOnClickListener(new MyClick()); write.setOnClickListener(new MyClick()); }public class MyClick implements View.OnClickListener {@Override public void onClick(View v) { switch (v.getId()) { case R.id.write: try { outputStream = openFileOutput("test.txt", MODE_APPEND); outputStream.write("123".getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } break; case R.id.read: try { inputStream = openFileInput("test.txt"); byte[] bytes = new byte[1024]; int num = 0; int i =0; while ((num = inputStream.read())!=-1){ bytes[i]= (byte) num; i++; } Log.i("msg", "onClick: "+new String(bytes,0,i)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } break; } } } }
main.xml
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> < Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="读文件" /> < Button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="写文件" /> < /LinearLayout>
推荐阅读
- Android开发(《Gradle Recipes for Android》阅读笔记(翻译)4.5——使用Android Libraries)
- android学习路线图
- Android中动画的移动起始位置
- 用eclipse开发Android,用Genymotion测试时报错adb发生错误
- Android NDK开发——应用监听自身卸载,弹出用户反馈调查
- Android SDK开发包国内下载地址
- Android native thread相关
- macaca环境搭建(web 和 android)
- android去掉EditView的默认焦点问题