您的位置:首页 > 其它

IO输入与输出1

2011-01-23 00:09 169 查看

IO输入与输出(一)

1.键盘被当做一种特殊的输入文件使用,I代表的是键盘,显示器被当做一种特殊的输出文件使用,即O代表的是显示器;
2.file类io包中唯一代表磁盘文件本身信息的的类,而不是文件中的内容,比如说文件的创建时间,而且定义了一些与平台无关的方法来操作文件;

3.file中定义了一些常用方法,不如查看文件名称,文件路径等等,下面有一个例子(判断某个文件是否存在,如果存在就将它删除,如果不存在就将它删除)。

package com.hjw;

import java.io.File;
import java.io.IOException;

public class FileTest {

/**判断一个文件是否存在,如果存在就删除,
* 如果不存在就创建此文件
* @param args
*/
public static void main(String[] args) {
fileTest();
}
private static void fileTest(){
File f=new File("aa//a.txt");
if(f.exists()){
f.delete();
}else{
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("fileName:"+f.getName());
//得到文件的相对路径
System.out.println("filepath:"+f.getPath());
//得到绝对路径下的文件
System.out.println("AbsoluteFile:"+f.getAbsoluteFile());
//得到文件的上一级
System.out.println("parent:"+f.getParent());
//得到文件上一级的相对路径
System.out.println("parentFile:"+f.getParentFile());
System.out.println("AbsolutePath:"+f.getAbsolutePath());
System.out.println(f.exists()? "exist":"not exist");
System.out.println(f.canRead()? "read":"not read");
System.out.println(f.canWrite()? "write":"not write");
//判断f是否是一个目录
System.out.println(f.isDirectory()? "directory":"not directory");
System.out.println();
}
}
4.java中有个RandomAccessFile类

a)RandomAccessFile类提供了众多的文件访问方法;

b)RandomAccessFile类支持随机访问方式,从指示器指示的当前位置开始;

c)RandomAccessFile类在读写等长记录格式的文件时有很大的优势;

d)RandomAccessFile类仅限于操作文件,不能访问其他的io设备,
e)RandomAccessFile类两种构造方法:
new RandomAccessFile("f","rw");//读写方式
new RandomAccessFile("f","r");//只读方式

例子:(通过RandomAccessFile类对文件进行读写操作)

public static void main(String[] args) {
// 定义三条记录
Employee e1 = new Employee("zhangsan", 23);
Employee e2 = new Employee("lisi", 22);
Employee e3 = new Employee("wangwu", 21);
try {
// 把内容通过randomAccessFile写入到文件中
RandomAccessFile ra = new RandomAccessFile("employee.txt", "rw");
ra.write(e1.getName().getBytes());
ra.writeByte(e1.getAge());
ra.write(e2.getName().getBytes());
ra.writeByte(e2.getAge());
ra.write(e3.getName().getBytes());
ra.writeByte(e3.getAge());
ra.close();
// 把文件读出来
byte[] bt = new byte[8];
int len = 0;
String strName = null;
RandomAccessFile raf = new RandomAccessFile("employee.txt", "r");

raf.skipBytes(9);
len = raf.read(bt);
strName = new String(bt, 0, len);
System.out.println(strName + ":" + raf.read());

raf.seek(0);
len = raf.read(bt);
strName = new String(bt, 0, len);
System.out.println(strName + ":" + raf.read());

raf.skipBytes(9);
len = raf.read(bt);
strName = new String(bt, 0, len);
System.out.println(strName + ":" + raf.read());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

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