Java IO笔记

操作文件的类–File

  • 在整个IO包中,唯一与文件本身有关的就是File类,使用File类可以进行创建或删除文件等操作。
  • File类常用构造方法:
//实例化File类时,必须设置好路径
public File(String pathName);
  • File类中的常用方法和常量
方法或常量描述
public static final String pathSeparator常量:表示路径的分隔符(windows是:“;”)
public static final String separator常量:表示路径的分隔符(windows是:“\”)
public File(String pathName)创建File类的对象,传入完整路径
public boolean creatNewFile() throws IOException创建新文件
public boolean delete()删除文件
public boolean exists()判断文件是否存在
public boolean isDirectory()判断给定的路径是否是一个目录
public long length()返回文件的大小
public String[] list()列出指定文件目录的全部内容,只是列出了名称
public File[] listFiles()列出指定目录的全部内容,会列出路径
public boolean mkdir()创建一个目录
public boolean renameTo()将已有的文件重新命名

使用File类操作文件

  • File类的对象实例化完成后,就可以使用creatNewFile()创建一个新文件,但此方法使用了throws关键字声明,因此必须使用try…catch进行异常处理。
  • 创建新的文件:
import java.io.File;
import java.io.IOException;

public class FileTest {
    public static void main(String[] args) {
        //创建新文件
        File file = new File("E:\\daima\\java\\IO\\src\\File\\test\\test1.txt");
//        String path = "E:" + File.separator + "daima" + File.separator + "java+IO"
//                + File.separator + "src" + File.separator + "File"
//                + File.separator + "test" + File.separator + "test2.txt";
//        File file1 = new File(path);

        try {
            file.createNewFile();
            //file1.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //观察File类中的两个常量
        System.out.println("pathSeparator: " + File.pathSeparator);
        System.out.println("separator:" + File.separator);
    }
}
//pathSeparator: ;
//separator:\

在这里插入图片描述

  • 删除一个指定的文件:
//将上例创建的test1.txt删除。
file.delete();

//判断文件是否存在然后删除
if(file.exists()){
	file.delete();
}
在每次执行完毕后,文件并不会立刻创建或删除,会有一些延迟,这是因为所有的
操作都要通过JVM完成所造成的。
  • 创建一个文件夹:
//创建一个文件夹:
File file1 = new File("E:\\daima\\java\\IO\\src\\File\\test\\books");
file1.mkdir();

在这里插入图片描述

  • 列出指定目录的全部文件:
//使用list()方法列出一个目录中的全部内容:
File file2 = new File("E:\\daima\\java\\IO");
String str[] = file2.list();
for (int i = 0; i < str.length; i++) {
	System.out.println(str[i]);
}
//.idea
//IO.iml
//out
//src

//使用listFiles()方法列出一个目录中的全部内容:
File files[] = file2.listFiles();
for(int i = 0; i < str.length;i++){
	System.out.println(files[i]);
}
//E:\daima\java\IO\.idea
//E:\daima\java\IO\IO.iml
//E:\daima\java\IO\out
//E:\daima\java\IO\src
  • 判断一个给定路径是否是目录:
if (file2.isDirectory()) {
	System.out.println(file2.getPath() + "路径是目录。");
} else {
	System.out.println(file2.getPath() + "不是目录。");
}
//E:\daima\java\IO路径是目录。

RandomAccessFile类

  • 此类为随机读取类,可以随机读取一个文件中指定位置的数据。
  • RandomAccessFile类的常用操作方法:
方法描述
public RandomAccessFile(File file,String mode)throws FileNotFoundException接受File类的对象,指定操作路径,但是在设置时需要设置模式,r为只读;w为只写,rw为读写。
public RandomFileAccessFile(String name,String mode)throws FileNotFoundException不再使用File类对象表示文件,而是直接输入了固定的文件路径。
public void close()throws IOException关闭操作。
public int read(byte[] b)throws IOException将内容读取到一个byte数组中。
public final byte readByte()throws IOException读取一个字节。
public final int readInt()throws IOException从文件中读取整型数据。
public void seek(long pos)throws IOException设置读指针的位置。
public final void writeBytes(String s)throws IOException将一个字符串写入到文件中,按字节的方式处理。
public final void writeInt(int v)throws IOException将一个int型数据写入文件,长度为4位。
public int skipBytes(int n)throws IOException将指针跳过指定的字节。
  • 写文件:
import java.io.File;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {
    public static void main(String[] args) throws Exception{
        //写文件
        File file = new File("E:\\daima\\java\\IO\\src\\randaccf\\test.txt");
        RandomAccessFile rdf = new RandomAccessFile(file,"rw");
        String name = null;
        int age = 0;
        name = "zhangsan";
        age = 25;
        //将姓名写入文件中:
        rdf.writeBytes(name);
        //将年龄写入文件中
        rdf.writeInt(age);
        name ="lisi";
        age = 23;
        rdf.writeBytes(name);
        rdf.writeInt(age);
        name = "wangwu";
        age = 30;
        rdf.writeBytes(name);
        rdf.writeInt(age);
        rdf.close();
    }
}
写完后可以通过Random Access的方式进行读取。
  • 使用RandomAccessFile类读取数据:
 		RandomAccessFile raf = new RandomAccessFile(file,"r");
        byte b[] = new byte[8];
        raf.skipBytes(12);
        for(int i = 0;i < b.length;i++) {
            b[i] = raf.readByte();
        }
        name = new String(b);
        age = raf.readInt();
        System.out.println("第二个人的信息-->姓名:" + name + "年龄:" + age);

        raf.seek(0);
        b = new byte[8];
        for(int i = 0;i < b.length;i++) {
            b[i] = raf.readByte();
        }
        name = new String(b);
        age = raf.readInt();
        System.out.println("第一个人的信息-->姓名:" + name + "年龄:" + age);

        raf.skipBytes(12);
        b = new byte[8];
        for(int i = 0;i < b.length;i++) {
            b[i] = raf.readByte();
        }
        name = new String(b);
        age = raf.readInt();
        System.out.println("第三个人的信息-->姓名:" + name + "年龄:" + age);
//第二个人的信息-->姓名:lisi    年龄:23
//第一个人的信息-->姓名:zhangsan年龄:25
//第二个人的信息-->姓名:wangwu  年龄:30

字节流与字符流基本操作

  • 程序中所有的数据都是以流的方式进行传输或者保存的,程序需要时要使用输入流数据读取存入数据,而当程序需要将一些数据保存起来时,就要使用输出流。
  • java.io中的操作主要包括字节流、字符流两大类,两类都有输入和输出的操作。在字节流中输出要用OutputStream类完成,输入则用InputStream类。在字符流中输出主要是用Writer完成,输入主要是用Reader完成。
  • IO操作步骤:
    • 使用File类打开一个文件。
    • 通过字节流或字符流的子类指定输出的位置。
    • 进行读/写操作。
    • 关闭输入/输出。

字节流

字节输出流:OutputStream

  • OutputStream是整个IO包中字节输出流最大父类,定义:
public abstract class OutputStream extends Object implements CloseableFlushable
  • OutputStream类常用方法:
方法描述
public void close()throws IOException关闭输出流
public void flush()throws IOException刷新缓冲区
public void write(byte[] b)throws IOException将一个byte数组写入数据流
public void write(byte[] b,int off,int len)throws IOException将一个指定范围的byte数组写入数据流
public abstract void write(int b)throws IOException将一个字节数据写入数据流
此时使用FileOutputStream子类构造方法:
	public FileOutputStream(File file)throws FileNotFoundException
  • 向文件中写入字符串:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class OutputStreamTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\outstream\\test.txt");
        OutputStream out = new FileOutputStream(file);
        //向文件写入字符串
        String str = "Hello World!!!";
        byte b0[] = str.getBytes();
        out.write(b0);
        
        //使用write(int t)的方式写入内容。
        byte b1[] = str.getBytes();
        for (int i = 0; i < b1.length; i++) {
            out.write(b1[i]);
        }
        out.close();
    }
}

追加新内容

  • 可以通过FileOutputStream类的另外一个构造方法进行实例化表示文件的追加内容。
public FileOutputStream(File file,boolean append) throws IOException
其中将append设置位true则表示在文件的末尾追加内容。
  • 修改之前的成宿,追加文件内容:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class OutputStreamTest1 {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\outstream\\test.txt");
        OutputStream out = new FileOutputStream(file, true);
        String str = "by bike!!!";
        byte b[] = str.getBytes();
        for (int i = 0; i < b.length; i++) {
            out.write(b[i]);
        }
        out.close();
    }
}

字节流输入:InputStream

  • InputStream定义:
public abstract class InputStream extends Object implements Closeable;
  • InputStream常用方法:
方法描述
public int available()throws IOException可以取得输入文件的大小。
public void close()throws IOException关闭输入流。
public abstreact int read()throws IOException读入内容,以数字的方式读取。
public int read(byte[] b)throws IOException将内容读到byte数组中,同时返回读入的个数。
  • 从文件中读取内容:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\outstream\\test.txt");
        InputStream in = new FileInputStream(file);
        byte b[] = new byte[1024];
        int len = in.read(b);
        in.close();
        System.out.println("读取数据的长度:" + len);
        System.out.println("内容为:" + new String(b, 0, len));
    }
}

字符流

  • 在程序中一个字符两个字节,那么Java提供了Reader和Writer两个专门操作字符流的类。

字符输出流:Writer

  • 字符输出流的常用方法:
方法描述
public abstract void close()throws IOException关闭输入流。
public void write(String str)throws IOException将字符串输出。
public void write(char[] cubf)throws IOException将字符数组输出。
public abstract void flush()throws IOException强制性清空缓存。
  • 向文件写入数据:
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class WriteTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\writeread\\test.txt");
        Writer w = new FileWriter(file);
        String str = "Hello world!!!";
        w.write(str);
        w.close();
    }
}

追加新内容:

  • FileWriter追加文件内容:
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class AddTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\writeread\\test.txt");
        Writer out = new FileWriter(file);
        String str = "\r\nHello world!!!";
        out.write(str);
        out.close();
    }
}

字符输入流:Reader

  • Reader类的常用方法:
方法描述
public abstract void close()throws IOException关闭输入流。
public int read()throws IOException读取单个字符。
public int read(char[] cbuf)throws IOEception将内容读取到字符数组中,返回读入的长度。
  • 从我文件中读取内容:
import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class ReadTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\writeread\\test.txt");
        Reader reader = new FileReader(file);
        char[] c = new char[1024];
        int len = reader.read(c);
        reader.close();
        System.out.println("内容为:" + new String(c, 0, len));

    }
}

字节流与字符流的区别

  • 字节流在操作时不会用到缓冲区,是文件本身直接操作的,而字符流在操作时使用了缓冲区。
  • 使用字节流不关闭执行。- 字节流是直接操作文件本身的。
  • 字符流操作时使用了缓冲区,而在关闭字符流时会强制性的将缓冲区中内容进行输出,但如果程序没有关闭,则缓冲区中的内容是无法输出的。
  • 文件在硬盘或在传输时都是以字节的方式进行的,而字符是只有在内存中才会形成,字节流使用较广泛。

文件复制

  • 将源文件中的内容全部读取到内存中,并一次性写入到目标文件中。
  • 不将源文件中的内容全部读取出来,而是采用边读边写的方式。
//实现复制功能

import java.io.*;

public class CopyTest {
    public static void main(String[] args) {
        if(args.length!=2) {
            System.out.println("输入的参数不对。");
            System.out.println("例如:Java copy 源文件路径 目标文件路径");
            System.exit(1);
        }
        File file1 = new File(args[0]);
        File file2 = new File(args[1]);
        if(!file1.exists()) {
            System.out.println("源文件不存在。");
            System.exit(1);
        }
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(file1);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try{
            output = new FileOutputStream(file2);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(input != null&&output!=null) {
            int temp=0;
            try{
                while((temp =input.read())!=-1){
                    output.write(temp);
                }
                System.out.println("复制完成!");
            }catch (IOException e){
                e.printStackTrace();
                System.out.println("复制失败!");
            }
            try {
                input.close();
                output.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

转换流–OutputStreamWriter类和InputStreamReader类

  • OutputStreamWriter类是Writer类的子类,将输入的字符流变为字节流,即将一个字符流的输出对象变为字节流的输出对象。
  • InputStreamReader类是Reader类的子类,将输入的字节流变为字符流,即将一个字节流的输入对象变为字符流的输入对象。
  • 将字节输出流变为字符输出流:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class OutputStreamWriterTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\oswandisr\\test.txt");
        Writer out = new OutputStreamWriter(new FileOutputStream(file));
        out.write("hello world");
        out.close();
    }
}

  • 将字节输入流变为字符输入流:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class InputStreamReaderTest {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\daima\\java\\IO\\src\\oswandisr\\test.txt");
        Reader reader = new InputStreamReader(new FileInputStream(file));
        char c[] = new char[1024];
        int len = reader.read(c);
        reader.close();
        System.out.println(new String(c, 0, len));
    }

内容操作流

  • 之前的操作都是从文件中来的,我们也可以将输入和输出位置设置在内存上,这时候就要用到ByteArrayInputStream、ByteArrayOutputStream来完成内存的输入和输出功能。
  • ByteArrayInputStream类的主要方法:
方法描述
public ByteArrayInputStream(byte[] buf)将全部的内容写入内存中。
public ByteArrayInputStream(byte[] buf,int offest,int length)将指定范围内的内容写入到内存中。
  • ByteArrayOutputStream类的主要方法:
方法描述
public ByteArrayOutputStream()创建对象。
public void write(int b)将内容从内存中取出。
  • 使用内存操作流完成一个大写字母转变为小写字母:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayTest {
    public static void main(String[] args) {
        String str = "HELLO WORLD";
        ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int temp = 0;
        while ((temp = bis.read()) != -1) {
            char c = (char) temp;
            bos.write(Character.toLowerCase(c));
        }
        String newStr = bos.toString();
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(newStr);
    }
}

管道流

  • 管道流主要作用是可以进行两个线程之间的通信。要连接两个输入输出区必须使用。
  • 管道流分为管道输出流(PipedOutputStream)和管道输入流(PipedInputStream)
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class Send implements Runnable {
    private PipedOutputStream pos = null;

    public Send() {
        this.pos = new PipedOutputStream();
    }

    @Override
    public void run() {
        String str = "hello world!!!";
        try {
            this.pos.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            this.pos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PipedOutputStream getPos() {
        return pos;
    }
}

class Receive implements Runnable {
    private PipedInputStream pis = null;

    public Receive() {
        this.pis = new PipedInputStream();
    }

    @Override
    public void run() {
        byte b[] = new byte[1024];
        int len = 0;
        try {
            len = this.pis.read(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            this.pis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("接收内容为:" + new String(b, 0, len));
    }

    public PipedInputStream getPis() {
        return pis;
    }
}

public class PipedTest {
    public static void main(String[] args) {
        Send send = new Send();
        Receive receive = new Receive();
        try {
            send.getPos().connect(receive.getPis());
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(send).start();
        new Thread(receive).start();
    }
}

打印流

打印流基本操作

  • 在整个IO中,打印流是输出信息最方便的类,主要包含字节打印流和字符打印流,可以打印任何的数据类型,这里主要看Print Stream类。
  • PrintStream类的常用方法:
方法描述
public PrintStream(File file)throws FileNotFoundException通过一个File对象实例化PrintStream类。
public PrintStream(OutputStream)接收OutputStream对象,实例化PrintStream类。
public PrintStream printf(Local l,String format,Object…args)根据指定的Locale格式化输出。
public PrintStream printf(String format,Object…args)根据本地环境格式化输出。
public void print(boolean b)此方法被重载多次,输出任意数据。
public void println(boolean b)此方法被重载多次,输出任意数据后换行。
  • 使用PrintStream输出:
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintTest {
    public static void main(String[] args) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream(new File("E:\\daima\\java\\IO\\src\\printstream\\test.txt")));
        ps.print("hello");
        ps.println("world");
        ps.print("1+1=" + 2);
        ps.close();
    }
}

使用打印流进行格式化

  • 格式化输出的方式可以用printf()方法实现。
  • 格式化输出:
字符描述
%s表示内容为字符串
%d表示内容为整数
%f表示内容为小数
%c表示内容为字符
  • 格式化输出:
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintTest1 {
    public static void main(String[] args) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream(new File("E:\\daima\\java\\IO\\src\\printstream\\test.txt")));
        String name = "张三";
        int age = 30;
        float score = 90.5f;
        char sex = 'M';
        ps.printf("姓名: %s;年龄: %d;成绩: %f;性别: %c",name,age,score,sex);
        ps.close();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值