java File基础数据的读取和写出

本文通过两个示例程序详细介绍了如何使用Java进行文件的基本读写操作。包括利用FileInputStream从文件中读取数据,并展示了如何获取文件可读的最大字节数;同时,也介绍了FileOutputStream的使用方法,如写出单个字符、字符数组及部分字符数组到文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

File基础数据的读取和写出

package FileInputStream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamTest {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis=new FileInputStream("E:\\javaTxt\\adc.txt");
            System.out.println("最多能读取"+fis.available());
            fis = new FileInputStream("E:\\javaTxt\\adc.txt");
//            int x = fis.read();
//            while (x!=-1){
//                System.out.println(x);
//                x = fis.read();
            byte[] b = new byte[5];
            int x1 = fis.read(b);
            while (x1!=-1){
                for (byte b1:b){
                    System.out.println((char) b1);
                }
                System.out.println("读取的个数"+x1);
                x1 =fis.read(b);
            }

            int x2= -1;
            while ((x2=fis.read(b))!=-1){
                System.out.println("x2读取个数————————————————"+x1);
            }

//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

package FileOutputStream;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamTest {

    public static void main(String[] args) {
        //java文件输入流


        {
            FileOutputStream fos=null;
            try {
                fos = new FileOutputStream("E:\\javaTxt\\adc.txt");
                //写出int值 unicode编码
                fos.write(97);//写一个a
                //写一个数组
                byte[] b ={98,99,100,101,'f'};
                fos.write(b);
                //把b数组的一部分写出去
                fos.write(b,0,2);
                //再写出一个字符串
                fos.write("你们也不背".getBytes());

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值