java文件流的读写和转换

一、文件流读写

这些都是计算机与硬盘之间发生的IO操作,基于硬盘的读写相对是比较慢的,这个操作的速度受到硬盘的读写速度的制约
为了能够提供读写速度,一定程度上饶过硬盘的限制,java提供了一种缓冲流来实现

1)FileInputStream 文件字节输入流

 public static void testFileInputStream(String inPath){
    try {
        FileInputStream in = new FileInputStream(inPath);
        byte[] b = new byte[10];
        int len = 0;

        // in.read方法有一个返回值,返回值是读取的数据长度,如果读取到最后一个数据,还会向后读一个,返回-1
        // 也就意味着当in.read的返回值是-1的时候整个文件就读取完毕了
        while ((len = in.read(b)) != -1){
            System.out.println("byte流:" + new String(b,0, len));
            // new String(b,0, len) 参数1是缓冲数据的数组,参数2是从数组的哪个位置开始转化字符串,参数3是总共转化的字符长度
        }

        in.close(); // 注意,流在使用完毕之后一定要关闭
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2)FileOutputStream 文件字节输出流

public static void testFileOutputSteam(String outPath, String content){
   try {
        FileOutputStream out = new FileOutputStream(outPath); // 指定文件输出数据
        out.write(content.getBytes()); // 把数据写到内存
        out.flush(); // 把内存中的数据写到硬盘
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3)copyFileAsSteam 字节流拷贝文件

public static void copyFileAsSteam(String inPath, String outPath){
    try {
        // 读取源文件
        FileInputStream in = new FileInputStream(inPath);

        // 复制到哪里
        FileOutputStream out = new FileOutputStream(outPath);

        byte[] b = new byte[10];

        int len = 0;

        while ((len = in.read(b)) != -1){
            // 参数1是写的缓存数组,参数2是从数组的哪个位置开始,参数3是写的总长度
            out.write(b, 0 , len);
        }

        // 把写到内存的数据写到硬盘
        out.flush();

        out.close();
        in.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

4)FileReader 文件字符输入流

public static void testFileReader(String inPath){
    try {
        FileReader fileReader = new FileReader(inPath);
        char[] chars = new char[10];

        int len = 0;

        while ((len = fileReader.read(chars)) != -1){
            System.out.println("char流:" + new String(chars,0, len));
        }

        fileReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

5)FileWriter 文件字符输出流

public static void testFileWriter(String outPath, String content){
    try {
        FileWriter fileWriter = new FileWriter(outPath); // 有文件的话会覆盖重写,没有的话会新建
        fileWriter.write(content); // 写到内存
        fileWriter.flush(); // 内存写到硬盘
        fileWriter.close(); // 关闭流
    } catch (Exception e) {
        e.printStackTrace();
    }
}

6)copyFileAsFile 字符流拷贝文件

public static void copyFileAsFile(String inPath, String outPath){
    try {
        FileReader fr = new FileReader(inPath);
        FileWriter fw = new FileWriter(outPath);

        char[] c = new char[100];
        int len = 0;

        while ((len = fr.read(c)) != -1){ // 读数据
            fw.write(c,0 , len); // 写数据到内存
        }

        fw.flush(); // 写到硬盘
        fw.close();
        fr.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

二、缓冲流文件读写

缓冲流是基于内存的
缓冲流就是先把数据缓冲内存里,在内存中去做io操作,基于内存的io操作大概能比基于硬盘的io操作快75000多倍

1)BufferedInputStream 缓冲字节输入流

 public static void testBufferedInputStream(String inPath){
    try {
        // 文件字节输入流对象
        FileInputStream in = new FileInputStream(inPath);
        // 把文件字节输入流放到缓冲字节输入流对象
        BufferedInputStream bi = new BufferedInputStream(in);

        byte[] b = new byte[100];
        int len = 0;

        while ((len = bi.read(b)) != -1 ){
            System.out.println(new String(b, 0 , len));
        }

        bi.close();
        in.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2)BufferedOutputStream 缓冲字节输出流

 public static void testBufferedOutputStream(String outPath, String content){
    try {
        FileOutputStream out = new FileOutputStream(outPath);
        BufferedOutputStream bo = new BufferedOutputStream(out);

        bo.write(content.getBytes());
        bo.flush();
        bo.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3)copyFileAsBufferedStream 缓冲字节流复制文件

 public static void copyFileAsBufferedStream(String inPath, String outPath){
    try {
        // 缓冲字节输入流
        BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inPath));

        // 缓冲字节输出流
        BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(outPath));

        byte[] b = new byte[100];
        int len = 0;

        while ((len = bi.read(b)) != -1){ // 读
            bo.write(b,0, len); // 写内存
        }

        bo.flush(); // 写硬盘
        bo.close();
        bi.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

4)BufferedReader 缓冲字符输入流

 public static void testBufferedReader(String inPath){
    try {
        FileReader fr = new FileReader(inPath);
        BufferedReader br = new BufferedReader(fr);

        char[] c = new char[1024];
        int len = 0;
        while ((len = br.read(c)) != -1){
            System.out.println(new String(c, 0, len));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

5)BufferedWriter 缓冲字符输出流

 public static void testBufferedWriter(String outPath, String content){
   try {
        FileWriter fw = new FileWriter(outPath);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.write(content);

        bw.flush();
        bw.close();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

6)copyFileAsBuffered 缓冲字符流复制文件

 public static void copyFileAsBuffered(String inPath, String outPath){
    try {
        BufferedReader br = new BufferedReader(new FileReader(inPath)); // 读字符流
        BufferedWriter bw = new BufferedWriter(new FileWriter(outPath)); // 写字符流

        char[] c = new char[1024];
        int len = 0;
        while ((len = br.read(c)) != -1){
            bw.write(c, 0, len);
        }

        bw.flush();
        bw.close();
        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

7)DataOutputStream 输出指定数据类型

 public static void testDataOutputStream(String outPath){
   try {
        DataOutputStream out = new DataOutputStream(new FileOutputStream(outPath));

        out.writeInt(100);
//            out.writeBoolean(false);

        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

8)DataInputStream 输入指定数据类型

 public static void testDataInputStream(String inPath){
    try {
        DataInputStream in = new DataInputStream(new FileInputStream(inPath));

        System.out.println(in.readInt());

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

三、转换流

1)InputStreamReader 转换字节输入流为字符输入流

public static void testInputStreamReader(String inPath){
    try {
        FileInputStream fs = new FileInputStream(inPath);
        // 把字节转换为字符流
        InputStreamReader in = new InputStreamReader(fs,"UTF-8"); // 参数1是字节流,参数2是编码

        char[] c = new char[100];
        int len = 0;
        while ((len = in.read(c)) != -1){
            System.out.println(new String(c,0,len));
        }

        in.close();
        fs.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2)OutputStreamWriter 转换字节输出流为字符输出流

public static void testOutputStreamWriter(String outPath, String content){
    try {
        FileOutputStream fs = new FileOutputStream(outPath);
        OutputStreamWriter ow = new OutputStreamWriter(fs, "UTF-8");

       ow.write(content);
       ow.flush();
       ow.close();
       fs.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

四、对象的序列化和反序列化

1)ObjectOutputStream 对象的序列化

public static void testObjectOutputStream(String outPath){
    try {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outPath));

        Person person = new Person();
        person.name = "张三";
        person.age = 19;

        out.writeObject(person);

        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2)ObjectInputStream 对象的反序列化

public static void testObjectInputStream(String inPath){
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(inPath));

        Object obj = in.readObject();
        Person p = (Person) obj;

        System.out.println(p.name);
        System.out.println(p.age);

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

五、文件的随机读写

1)RandomAccessFile 随机读文件

public static void testRandomAccessFile(String inPath, String mode){
    //RandomAccessFile的构造有两个参数,参数1是读写的文件的路径
    // 参数2是指定 RandomAccessFile 的访问模式
    // r: 以只读方式打开
    // rw: 打开以便读取和写入
    // rwd:打开以便读取和写入;同步文件内容的更新
    // rws:打开以便读取和写入;同步文件内容和元数据的更新
    // 最常用的是r,rw
    try {
        RandomAccessFile rf = new RandomAccessFile(inPath, mode);

        // 设置读取文件内容的起始点
        rf.seek(11);

        byte[] b = new byte[1000];
        int len = 0;
        while ((len= rf.read(b)) != -1){
            System.out.println(new String(b,0,len));
        }

        rf.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2)RandomAccessFile 随机写文件

public static void testRandomAccessFileWrite(String outPath, String content){
    try {
        RandomAccessFile ra = new RandomAccessFile(outPath, "rw");
// 		如果是在文件开头或者中间写,会覆盖等长的内容
//            ra.seek(0); // 设置写的起始点
        ra.seek(ra.length()); // 设置写的起始点,代表从文件的最后结尾写,也就是文件的追加

        ra.write(content.getBytes());

        ra.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java中,可以使用读写文件是一种连接数据源和目标的通道,可以用来读取或写入数据。 下面是使用Java读写文件的一些示例代码: #### 读取文件 ``` import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class ReadFileExample { public static void main(String[] args) { InputStream inputStream = null; try { // 打开文件输入 inputStream = new FileInputStream("example.txt"); // 读取文件内容 int data = inputStream.read(); while (data != -1) { // 将读取的数据转换为字符并输出 System.out.print((char) data); data = inputStream.read(); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭文件输入 if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` #### 写入文件 ``` import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class WriteFileExample { public static void main(String[] args) { OutputStream outputStream = null; try { // 打开文件输出 outputStream = new FileOutputStream("example.txt"); // 写入文件内容 String content = "Hello, World!"; for (int i = 0; i < content.length(); i++) { outputStream.write(content.charAt(i)); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭文件输出 if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` 注意,在读写文件时要注意关闭文件,以免出现资源泄露的问 ### 回答2: Java 提供了多种方式来构建读写文件的功能。下面是一个常见的示例,演示了如何读取一个文件并将其内容写入到另一个文件中。 ```java import java.io.*; public class FileReadWrite { public static void main(String[] args) { // 定义输入文件和输出文件的路径 String inputFile = "input.txt"; String outputFile = "output.txt"; try { // 创建文件输入文件输出 FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); // 创建缓冲区 byte[] buffer = new byte[1024]; int bytesRead; // 读取输入中的数据,并写入输出 while ((bytesRead = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } // 关闭输入和输出 fis.close(); fos.close(); System.out.println("文件读写完成。"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码首先定义了输入文件和输出文件的路径,然后创建了一个文件输入和一个文件输出。接着创建了一个缓冲区,并使用 while 循环从输入中读取数据,并将读取到的数据写入输出。 最后,关闭了输入和输出,并输出了一个提示信息,表示文件读写完成。 这只是一个简单的示例,Java 还提供了其他更高级的来满足不同的需求,例如字符、缓冲、对象等。使用这些,可以更方便地进行文件读写操作。 ### 回答3: Java构建读写文件的基本步骤如下: 1. 创建文件对象:使用File类或路径字符串创建一个File对象,指定要读写文件。 2. 创建输入:使用FileInputStream或BufferedReader类创建一个输入对象,用于从文件中读取数据。 3. 创建输出:使用FileOutputStream或BufferedWriter类创建一个输出对象,用于向文件中写入数据。 4. 读取文件内容:使用输入对象的read()方法、readLine()方法等读取文件中的数据,并将其存储在变量中。 5. 写入文件内容:使用输出对象的write()方法、append()方法等将数据写入文件中。 6. 关闭:使用close()方法关闭输入和输出,释放资源。 以下是一个读取文件并写入文件的示例代码: ```java import java.io.*; public class FileReadWriteExample { public static void main(String[] args) { try { // 创建文件对象 File inputFile = new File("input.txt"); File outputFile = new File("output.txt"); // 创建输入和输出 FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); // 读取文件内容并写入新文件 int ch; while ((ch = fis.read()) != -1) { fos.write(ch); } // 关闭 fis.close(); fos.close(); System.out.println("文件读写成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码首先创建一个输入文件对象`inputFile`和输出文件对象`outputFile`,然后使用`FileInputStream`和`FileOutputStream`分别创建对应的输入`fis`和输出`fos`。 在读取和写入文件内容的过程中,我们通过`fis.read()`方法读取输入中的数据,并使用`fos.write()`方法将数据写入输出。 最后,在关闭输入和输出后,我们打印一条成功的提示信息。 请注意,在实际使用中,我们应该添加适当的异常处理机制来处理可能出现的异常情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值