您的位置:首页 > 移动开发 > Android开发

Android 中的文件存储

2016-06-18 01:52 375 查看
package cn.tttt.android_file;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String word = readFromFile();
Log.i("tttt", "word -> " + word);
}

public String readFromFile() {
StringBuffer result = new StringBuffer();
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;

try {
fis = openFileInput("helloworld.txt");
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);

int b;
while((b = br.read()) != -1) {
result.append((char) b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}

return result.toString();
}

public void writeToFile() {
FileOutputStream fos = null;
BufferedOutputStream bos = null;

String word = "public static void main(String[] args)";

try {
fos = openFileOutput("helloworld.txt", MODE_PRIVATE);
bos = new BufferedOutputStream(fos);
bos.write(word.getBytes());
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
bos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  file存储