一. JAVA中的各种IO流:
1.流的选择
选择条件的区别:
以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
以字符为单位读取文件,常用于读文本,数字等类型的文件.
至于是否选择用Buffer来对文件输入输出流进行封装,就要看文件的大小,若是大文件的读写,则选择Buffer这个桶来提供文件读写效率。
在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。而ByteArrayInputStream又把字节数组中的字节以流的形式读出,实现了对同一个字节数组的操作.
2.ByteArrayInputStream(比较少用)和ByteArrayOutputStream
public static void main(String[] args) {
int a = 0;
int b = 1;
int c = 2;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(a);
bout.write(b);
bout.write(c);
byte[] buff = bout.toByteArray();
for (int i = 0; i < buff.length; i++)
System.out.println(buff[i]);
System.out.println("***********************");
ByteArrayInputStream bin = new ByteArrayInputStream(buff);
while ((b = bin.read()) != -1) {
System.out.println(b);
}
}
综合DataOutputStream&DataInputStream的作用和功能,与ByteArrayOutputStream和ByteArrayInputSream使用将更方便.此时DataOutputStream&DataInputStream封闭了字节流,以适当的形式读出了字节数组中的数据.如下所示:
public static void main(String[] args) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
String name = "xxy";
int age = 84;
dout.writeUTF(name);
dout.writeInt(age);
byte[] buff = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(buff);
DataInputStream dis = new DataInputStream(bin);
String newName = dis.readUTF();
int newAge = dis.readInt();
System.out.println(newName + ":" + newAge);
}
二. SD卡的操作(权限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>)
1.判断SD卡的状态:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
2.得到SD卡的路径
File SDFile = Environment.getExternalStorageDirectory();