Java文件编程

 

引入

import java.util.*;
import java.io.*;

public class ReadFile
{
    public static void main(String[] args)
    {
        File f = new File("args[0]");//用户输入文件名
        //在内存中创建一个文件对象
    }
}

//比较 comparable 可用于文件
public class Pair implements Compareable
{
    private int x,y;
    
    public boolean equals(Object o)
    {
        if(o.getClass() == Pair.class);
        {
            Pair p = (Pair)o;
            return (p.x == this.x && p.y == this.y)||(p.x == this.y && p.y == this.x);
        }
    }

    
}

注意几个字符串的区别:

String a = "abc";
//创建在常量池中
String a1 = new String String("abc");
//新的在堆中
String a2 = s2.intern();
//到常量缓冲池中找
String s = "abc" + 5;//调用append()函数,实现追加

文件类有的属性

  • 文件名
  • 文件大小
  • 文件时间:创建、修改时间
  • 文件权限
  • 比较文件
  • ......

可移植性:编程尽量不要使用绝对路径

文件类函数

文档

  • getName() 获得名字
  • isDirectory() 判断文件类型
  • isFile() 是不是文件而不是文件夹
  • lastModified() 最后一次修改,返回值long
  • list() 获得文件夹下的文件名称
  • RandAccessFile() 随机访问文件,支持读写
  • ......

节点流

Class InputStream 输入流

流的缺陷:流是单向的,只能读或者写

流的函数

  •  read() 从流中读一个字节,返回int,-1表示流结束
  • read(byte[] b,int off ,int len) 读指定长度的,从offset标记开始的文件数据

class OutputStream 

对应read有相应的write()函数

Class FileInputStream

public class copy
{
    public ststic void main (String[] args)
    {
        FileInputStream fis = new FileInputStream(args[0]);
        FilrOutputStream fos = new FileOutputStream(args[1]);

        int c = 0;
        byte[] buffer = new byte[8*1024];
        while((c = fis.read(buffer)) != -1)//c接收返回的字节个数
        {
            fos.write(buffer,0,c);
        }
        fis.close();fos.close();
    }
}

处理流

处理流是对其他流的操作

public class copy
{
    public ststic void main (String[] args)
    {
        FileInputStream fis = new FileInputStream(args[0]);
        
        BufferedInputStream bis = new BufferInputStream(fis);

        DataInputStream dis = new DataInputStream(bis);

        double d = dis.readDoubole();
        int i = dis.readInt();
    }
}

把学生类数据输出至文件

class test//保存学生信息
{
    main()
    {
    Student s = new Student();

    FileOutputStream fos = new FileOutputStream("students.dat");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(students);
    oos.flush();
    oos.close();bos.close();fos.close();
    }
}

注意:克隆函数

Student s1 = new Student();
Student s2 = (Student) s1.clone();//克隆函数是浅复制,都指向同一个位置
//必须有cloneable才能调用
public class Student implements Seriallizable cloneable{

}

 

ByteArrayInputStream

ByteArrayOutputStream

节点流,外部设备是内存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值