文件与目录的操作

RandomAccessFile

对已存在的文件进行读写如果没有自动创建

返回值类型方法名简要说明
voidclose()关闭此随机访问文件流并释放与该流关联的所有系统资源。
FileChannelgetChannel()返回与此文件关联的唯一 FileChannel 对象。
FileDescriptorgetFD()返回与此流关联的不透明文件描述符对象。
longgetFilePointer()返回此文件中的当前偏移量。
longlength()返回此文件的长度。
intread()从此文件中读取一个数据字节。
intread(byte[] b)将最多 b.length 个数据字节从此文件读入 byte 数组。
intread(byte[] b, int off, int len)将最多 len 个数据字节从此文件读入 byte 数组。
booleanreadBoolean()从此文件读取一个 boolean。
bytereadByte()从此文件读取一个有符号的八位值。
charreadChar()从此文件读取一个字符。
doublereadDouble()从此文件读取一个 double。
floatreadFloat()从此文件读取一个 float。
voidreadFully(byte[] b)将 b.length 个字节从此文件读入 byte 数组,并从当前文件指针开始。
voidreadFully(byte[] b, int off, int len)将正好 len 个字节从此文件读入 byte 数组,并从当前文件指针开始。
intreadInt()从此文件读取一个有符号的 32 位整数。
StringreadLine()从此文件读取文本的下一行。
longreadLong()从此文件读取一个有符号的 64 位整数。
shortreadShort()从此文件读取一个有符号的 16 位数。
intreadUnsignedByte()从此文件读取一个无符号的八位数。
intreadUnsignedShort()从此文件读取一个无符号的 16 位数。
StringreadUTF()从此文件读取一个字符串。
voidseek(long pos)设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或覆盖式的写入操作。
voidsetLength(long newLength)设置此文件的长度。
intskipBytes(int n)尝试跳过输入的 n 个字节以丢弃跳过的字节。
voidwrite(byte[] b)将 b.length 个字节从指定 byte 数组写入到此文件,并从当前文件指针开始。
voidwrite(byte[] b, int off, int len)将 len 个字节从指定 byte 数组写入到此文件,并从偏移量 off 处开始。
voidwrite(int b)向此文件写入指定的字节。
voidwriteBoolean(boolean v)按单字节值将 boolean 写入该文件。
voidwriteByte(int v)按单字节值将 byte 写入该文件。
voidwriteBytes(String s)按字节序列将该字符串写入该文件。
voidwriteChar(int v)按双字节值将 char 写入该文件,先写高字节。
voidwriteChars(String s)按字符序列将一个字符串写入该文件。
voidwriteDouble(double v)使用 Double 类中的 doubleToLongBits 方法将双精度参数转换为一个 long,然后按八字节数量将该 long 值写入该文件,先定高字节。
voidwriteFloat(float v)使用 Float 类中的 floatToIntBits 方法将浮点参数转换为一个 int,然后按四字节数量将该 int 值写入该文件,先写高字节。
voidwriteInt(int v)按四个字节将 int 写入该文件,先写高字节。
voidwriteLong(long v)按八个字节将 long 写入该文件,先写高字节。
voidwriteShort(int v)按两个字节将 short 写入该文件,先写高字节。
voidwriteUTF(String str)使用 modified UTF-8 编码以与机器无关的方式将一个字符串写入该文件。

构造

RandomAccessFile(File file, String mode)

创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。

RandomAccessFile(String name, String mode)

创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。

mode
  • 此参数指定用以打开文件的访问模式。允许的值及其含意为:

  • “r” 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。

  • “rw” 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。

  • “rws” 打开以便读取和写入,对于 “rw”,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。

  • “rwd” 打开以便读取和写入,对于 “rw”,还要求对文件内容的每个更新都同步写入到底层存储设备。

File

抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等

File构造方法:

File(File parent, String child)

  根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例  

File(String pathname)

   通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。

File(String parent, String child)

   根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
  

File常用方法
canExecute()测试应用程序是否可以执行此抽象路径名表示的文件。
canRead()测试应用程序是否可以读取此抽象路径名表示的文件。
canWrite()测试应用程序是否可以修改此抽象路径名表示的文件。
compareTo(File pathname)按字母顺序比较两个抽象路径名。
createNewFile()当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
delete()删除此抽象路径名表示的文件或目录。
deleteOnExit()在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
equals(Object obj)测试此抽象路径名与给定对象是否相等。
exists()测试此抽象路径名表示的文件或目录是否存在。
getAbsoluteFile()返回此抽象路径名的绝对路径名形式。
getAbsolutePath()返回此抽象路径名的绝对路径名字符串。
getCanonicalFile()返回此抽象路径名的规范形式。
getCanonicalPath()返回此抽象路径名的规范路径名字符串。
getFreeSpace()返回此抽象路径名指定的分区中未分配的字节数。
getName()返回由此抽象路径名表示的文件或目录的名称。
getParent()返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
getParentFile()返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。
getPath()将此抽象路径名转换为一个路径名字符串,更多关于File的使用帮助可以参考引用文章。
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
*@Endless
*@遍历指定目录所有文件
*/
public class IOFiles {
    public static void main(String[] args) throws IOException {
        File f1=new File("E:\\");
        outpath(f1);
    }
    public static void outpath1(File x){ //方式一
        File[]a=x.listFiles();
        for(File s: a){
            if(s.isDirectory()){
                System.out.println(s.getName());
                outpath(s);//递归
            }else{
                System.out.println(s.getPath()+s.getName());
            }
        }
    }
    public static void outpath2(File f1){//方式二
        Arrays.asList(f1.listFiles()).forEach(x->{if(x.isDirectory()){
            System.out.println("该文件夹下有"+x.listFiles().length+"个文件");
            System.out.println(x.getName());
            outpath(x);
        }else{
            System.out.println(x.getPath()+x.getName());
        }
        });
    }


}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

/***
 * @author Endless
 * @version 读取文件前两行并追加到文件末尾
 */
public class IOFiles {
    public static void main(String[] args) throws IOException {
        File file = new File("E:/223.txt");
        // file.createNewFile();
        BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));// 读取文件
        String x = "";
        for (int i = 0; i < 2; i++) {
            x += read.readLine() + "\r\n";
        }
        System.out.println(x);
        FileOutputStream fos = new FileOutputStream(file, true);
        fos.write(x.getBytes("GBK"));// 写文件
        read.close();
        fos.close();
        BufferedReader reads = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));// 读取文件
        while ((x = reads.readLine()) != null) {// 读行
            System.out.println(x);
        }
        reads.close();
        System.out.println("============================");
        RandomAccessFile rf = new RandomAccessFile("E:" + File.separator + "时代.txt", "rw");
        rf.seek(0);// 设置指针位置,若此位置存在数据,则写入操作覆盖原有数据
        x = "";
        String y = "";
        for (int i = 0; i < 2; i++) { // 从指针位置开始读两行
            x += rf.readLine() + "\r\n";// 每读一行追加换行符并累加到x
        }
        y = new String(x.getBytes("ISO-8859-1"), "gbk");// x转换编码格式赋值给y
        System.out.println(y);// 打印
        rf.seek(rf.length());// 设置指针的位置为文件尾
        rf.write(y.getBytes("GBK"));// 在当前指针位置写入数据

        RandomAccessFile rfs = new RandomAccessFile("E:\\时代.txt", "rw");
        String line = "";
        while ((line = rfs.readLine()) != null) {// 遍历所有行并输出
            System.out.println(new String(line.getBytes("ISO-8859-1"), "gbk"));
        }
        rfs.close();// 销毁此对象以回收内存空间
    }
}

合并文本文件

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

/**
*@2017年8月31日@下午7:50:15
*@Administrator
*@合并文件
*/
public class sequence {
public static void main(String[] args) throws IOException {
      Vector<FileInputStream> v = new Vector<FileInputStream>();  
      v.add(new FileInputStream("D:\\使用说明.txt"));  
      v.add(new FileInputStream("D:\\unlock.log"));  
      Enumeration<FileInputStream> en = v.elements();  
      SequenceInputStream sis = new SequenceInputStream(en);  
      FileOutputStream fos = new FileOutputStream("E:\\999.txt");  
      byte[] buf = new byte[1024];  
      int len = 0;  
      while((len=sis.read(buf))!=-1)  
      {  
          fos.write(buf,0,len);  
      }  
      fos.close();  
      sis.close();
    }
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
*@2017年8月31日@上午10:51:54
*@Administrator
*@复制一个文件
*/
public class copys {
    public static void main(String[] args) throws IOException {
        String oldpath="D:\\instantclient-basic-nt-11.2.0.4.0.zip";
        String newpath="D:\\www\\wqqqq\\instant.zip";
        copy(oldpath,newpath);

    } 

    static void copy(String old,String news) throws IOException{
        File oldfile=new File(old);
        File newfile=new File(news);
        if(newfile.exists()){//如果已存在此文件则删除/重命名
            //newfile.delete();
            File rename=new File(newfile.getParent()+"\\"+newfile.getName().replace(".", "(1)."));
            newfile.renameTo(rename);
        }
        if(!newfile.exists()){//如果不存在则建立一级或者多级父目录
            newfile.getParentFile().mkdirs();
        }
        if(oldfile.isFile()){
            InputStream in=new FileInputStream(oldfile);
            FileOutputStream out=new FileOutputStream(newfile);
            byte[]read=new byte[2048];
            int readlength=0;
            while((readlength=in.read(read))!=-1){
                out.write(read,0,readlength);
            }
            in.close();
            out.close();
            System.out.println("文件复制成功!"+old);
        }else{
             System.out.println(old+"不是有效的文件");
         }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值