java IO 流(一)

2014-11-24 11:59:56 ? 作者: ? 浏览: 168
io流在java中与 Android中有很大的相似性,我们先看java中的IO流
一, 文件流:
File f = new File("e:" + File.separator + "test.txt");// separator是分割符,适用于不同 系统
if (f.exists()) {// f 存在
if (f.isFile()) {// 如果f是文件
// 打印相关信息
System.out.println("文件名称" + f.getName());
System.out.println("文件大小" + f.length());
System.out.println("文件路径" + f.getAbsolutePath());
// 输入流
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
// 通过获得文件大小读取文件
// int lenght = fis.available();//文件的大小
// byte [] bytes = new byte[lenght];
// String s = fis.read(bytes);
// System.out.println(s);
// 通过循环读取
byte[] bytes = new byte[1024];
int n = 0;
while ((n = fis.read(bytes)) != -1) {
String s = new String(bytes, 0, n);
System.out.println(f.getName() + "文件的内容是:" + s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (f.isDirectory()) {// 如果是文件夹,其实可以不要判断,这里为了显示更清楚
// 显示文件夹下的所有文件和文件夹
// String [] fs = f.list();//返回文件的名称列表
File[] files = f.listFiles();
for (File ff : files) {
System.out.println(ff);// 默认打印文件全路径
}
}
} else {// 不存在
// 新建
try {
f.createNewFile();// 创建一个相应文件
// 并在文件中写入一些信息
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
String s = "我是中国人\r\n";// "\n"表示换行,"\r"表示回车
String ss = "我叫钟志钢";
fos.write(s.getBytes());
fos.write(ss.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fos.close();// 一定要记得关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.mkdir();// 歌者创建一个文件夹
}
二,RandomAccessFile
完成随机读取功能,可读取指定位置的内容,文件中的所有内容都是按照字节存放的,都有固定的位置
RandomaccessFile(File f , String mode) mode:
r : 只读
w : 只写
rw : 读写模式,如果文件不存在,会自动创建
File f = new File("e:" + File.separator + "RandomAccessFile");
RandomAccessFile raf = null;
String name = null;
int age = 0;
String myname = null;
int myage = 0;
try {
raf = new RandomAccessFile(f, "rw");
name = "zhangsan";
age = 10;
raf.writeBytes(name);// 写入8字节
raf.writeInt(age);// 写入4个字节
name = "lishi ";
age = 20;
raf.writeBytes(name);// 写入8字节
raf.writeInt(age);// 写入4个字节
name = "wangwu ";
age = 28;
raf.writeBytes(name);// 写入8字节
raf.writeInt(age);// 写入4个字节
raf.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
raf = new RandomAccessFile(f, "r");// 只读的方式打开文件
byte[] b = new byte[8];// 创建byte数组
raf.skipBytes(12);// 路过12字符,读第二个
for (int i = 0; i < b.length; i++) {
b[i] = raf.readByte();// 一个一个字节读出来
}
myname = new String(b);
myage = raf.readInt();// 读取年龄
System.out.println("我的年龄是:" + myage + ",我的姓名是:" + myname);
raf.seek(0);// 回到开头,读第一个
for (int i = 0; i < b.length; i++) {
b[i] = raf.readB
-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: