Java I/O操作

文件I/O操作在java.io包中

读取文件

使用FileInputStream字节流读取文件

class Test{
    public static void main(String []args){
        try {
            FileInputStream fis = new FileInputStream("test.txt");
            byte[] data = new byte[1024];
            while (fis.read(data) != -1) {
                String s = new String(data);
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用Reader字符流读取文件

class Test {
    public static void main(String []args) {
        try (FileReader fr = new FileReader("test.txt");
             BufferedReader br = new BufferedReader(fr)) {
            String s;
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

写入文件

使用FileOutputStream写入文件

class Test{
    public static void main(String []args){
        try {
            FileOutputStream fos = new FileOutputStream("test.txt");
            fos.write("abc".getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用Writer字符流写入文件

class Test {
    public static void main(String []args) {

    }
}

文件操作

使用File进行文件操作

class Test{
    public static void main(String []args){
        try {
            File f = new File("cooy.png");
            f.createNewFile();
            System.out.println(f.length()); // 0
            System.out.println(f.canExecute()); // true
            System.out.println(f.canRead()); // true
            System.out.println(f.canWrite()); // true
            System.out.println(f.isFile()); // true
            System.out.println(f.isDirectory()); // false
            f.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

对象序列化

将对象写入文件

Serializable接口

只有实现了Serializable接口的类才能序列化
Serializable接口中没有方法,仅用于标记

class Student implements Serializable {
    private String stu_id;
    private String name;
    private Date birthday;
    private float stu_score;
}

读写对象

使用ObjectInputStreamObjectOutputStream读写对象

Object obj;
try (FileInputStream fis = new FileInputStream(fname);
     ObjectInputStream ois = new ObjectInputStream(fis)) {
    obj = ois.readObject();
} catch (Exception e) {
    e.printStackTrace();
}
Serializable obj = new Student();
try (FileOutputStream fos = new FileOutputStream(fname);
     ObjectOutputStream oos = new ObjectOutputStream(fos)) {
    oos.writeObject(obj);
} catch (Exception e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值