写文件1
try {
//打开文件输出流(输入输出的问题一直让我很纠结,现在才懂了,
输入输出是相对于计算机的内存,外存来说的 程序运行以后是在内存中,所以输出流就是内存向外存输出(由内而外才是出对吧),
就是程序向外输出东西,自然就是写出去了)
FileOutputStream fos = c.openFileOutput(filename,Context.MODE_APPEND);//文件操作 MODE_APPEND追加, MODE_PRIVATE 覆盖
fos.write((id +" "+ name +" "+ password +" ").getBytes());//写文件
fos.close();//关闭输出流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
写文件2
public void save(Context c ){
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = c.openFileOutput("文件名", Context.MODE_APPEND);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write("数据");
}
catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(out != null)
out.close();
if(writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读文件
StringBuilder sb = new StringBuilder();//定义一个StringBuilder 来存储数据
List<User> userList = new ArrayList<>() ;
try {
FileInputStream fis = c.openFileInput(filename);//输入流
byte[] buff = new byte[fis.available()];//创建一个byte数组 大小为文件的大小
int len = 0;
len = fis.read(buff);//记录读取字节成功的个数
fis.close();
sb.append(new String(buff,0,len));//添加到StringBuilder中
String[] data = sb.toString().split(" ");//根据空格分开数据
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
另外一种读文件操作
try {
FileInputStream inStream = c.openFileInput(FILENAME);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inStream.read(buf)) != -1) {//读到最后返回-1
sb.append(new String(buf, 0, len));
}
inStream.close();
ArrayList<String> list = new ArrayList(Arrays.asList(sb.toString().split("\t"))); //StringBuilder 转字符串数组 转动态数组
if (list != null) {
for (String str : list) {
Item item = new Item();
item.setMessage(str);
item.setPhoto(R.drawable.photo0);
itemArrayList1.add(item);
}
}
}
catch(Exception e){
e.printStackTrace();
}
public String load(Context c ) {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = c.openFileInput("文件名");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}