Java实验 输入输出流

一、实验内容

编写应用程序,创建文件对象,分别完成二部分内容:

  • 通过文件字节输入流和输出流,完成一张图片的读取和写入操作;
  • 通过文件字符输入流和输出流,完成TXT内容的写入和读取操作,完成实验报告。

 

package io;

import java.io.*;

public class FileIO {
    public static void main(String[] args) {
        // 读取和写入图片文件
        String imageFilePath = "E:\\文件\\test\\losto.jpg";
        String outputImageFilePath = "E:\\文件\\test\\lotso1.jpg";

        try {
//创建文件对象
File imageFile = new File(imageFilePath);
File outputImageFile = new File(outputImageFilePath);

            // 创建文件字节输入流
            FileInputStream fileInputStream = new FileInputStream(imageFilePath);

            // 创建文件字节输出流
            FileOutputStream fileOutputStream = new  FileOutputStream(outputImageFilePath);

            // 读取图片文件
            byte[] buffer = new byte[1024];
            int byteRead;
            //read()方法从源中读取单个数据,如果未读出字节就返回-1
            while ((byteRead = fileInputStream.read(buffer)) != -1) {
                // 写入图片文件
                fileOutputStream.write(buffer, 0, byteRead);
            }

            // 关闭输入和输出流
            fileInputStream.close();
            fileOutputStream.close();
            System.out.println("图片文件读取和写入完成!");
        } catch (IOException e) {
            e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因
        }

        // 写入和读取文本文件
        String textFilePath = "E:\\文件\\test\\losto.txt";
        String outputTextFilePath = "E:\\文件\\test\\losto1.txt";

        try {
	// 创建文件对象
File textFile = new File(textFilePath);
File outputTextFile = new File(outputTextFilePath);

            // 创建文件字符输入流
            FileReader fileReader = new FileReader(textFilePath);

            // 创建文件字符输出流
            FileWriter fileWriter = new FileWriter(outputTextFilePath);

            // 读取文本文件
            int character;
            while ((character = fileReader.read()) != -1) {
                // 写入文本文件
                fileWriter.write(character);
            }

            // 关闭输入和输出流
            fileReader.close();
            fileWriter.close();

            // 创建文件字符输入流,用于读取文本文件
            BufferedReader bufferedReader = new BufferedReader(new FileReader(outputTextFilePath));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            // 关闭输入流
            bufferedReader.close();

            System.out.println("文本文件读取和写入完成!");
            System.out.println("读取到的内容为:" + stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值