File类
封装文件本身信息,定义操作文件的方法
常用方法:
File(String pathname)
delete()
creatNewFile()
exists()
getName()
习题:判断某文件,存在则删除,不存在则创建
import java.io.File;
public class TestFile {
public static void main(String [] args)
{
File f = new File("1.txt");
System.out.println(f.canRead());
System.out.println(f.exists());
System.out.println(f.getAbsolutePath());
System.out.println(f.getName());
System.out.println(f.getParent());
System.out.println(f.getPath());
System.out.println(f.length());
System.out.println(f.toString());
if(f.exists())
{
f.delete();
}
else
{
try{f.createNewFile();
}
catch(Exception e){
}
}
System.out.println(f.canRead());
System.out.println(f.exists());
System.out.println(f.getAbsolutePath());
System.out.println(f.getName());
System.out.println(f.getParent());
System.out.println(f.getPath());
System.out.println(f.length());
System.out.println(f.toString());
}
}
RandomAccessFile类
仅限于操作文件,支持随机访问,擅长随机读写等长记录格式文件。
常用方法:
RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)
writeChars(String s)按字符序列将一个字符串写入该文件
writeInt(int v)写入整数
readChar()从文件读取一个字符
readInt()从文件读取32位整数
seek(long pos)跳转到pos的位置
skipBytes(ing n)向后跳n个字节
习题:存三名员工信息,先打印第二个人在打印第一个人第三个人
import java.io.RandomAccessFile;
public class TestRandomFile {
public static void main(String [] args)
{
RandomAccessFile f = null;
try
{
f = new RandomAccessFile("staffInfo.txt", "rw");
}
catch (Exception e)
{
e.printStackTrace();
}
Staff s1 = new Staff("zhangsan", 20);
Staff s2 = new Staff("lisi", 21);
Staff s3 = new Staff("wangwu", 122);
try{
f.writeChars(s1.name);
f.writeInt(s1.age);
f.writeChars(s2.name);
f.writeInt(s2.age);
f.writeChars(s3.name);//写入字符串
f.writeInt(s3.age);//写入整数
//取第二个人
f.seek(Staff.LEN*2+4);//跳到第二个人,unicode编码一个字符站两个字节,所以是8*2+4
String strName1 = "";
for(int i=0; i<Staff.LEN; i++)
{
strName1 += f.readChar();
}
System.out.println(strName1+":"+f.readInt());
//取第一个人
f.seek(0);
strName1 = "";
for(int i=0; i<Staff.LEN; i++)
{
strName1 += f.readChar();
}
System.out.println(strName1+":"+f.readInt());
//取第三个人
f.skipBytes(Staff.LEN*2+4);
strName1 = "";
for(int i=0; i<Staff.LEN; i++)
{
strName1 += f.readChar();
}
System.out.println(strName1+":"+f.readInt());
f.close();//关闭文件
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Staff
{
String name = null;
int age;
public static final int LEN = 8;//姓名给8个字符的长度
Staff(String name, int age)
{
if(name.length() > LEN)//多退少补
{
name = name.substring(0, 8);
}
else
{
while(name.length() < LEN)
{
name += "\u0000";
}
}
this.name = name;
this.age = age;
}
}