文件的简单读写

本文介绍了一个简单的Java程序,演示了如何使用FileInputStream和FileOutputStream进行文件的读取和写入操作。程序首先检查文件是否存在,然后通过缓冲读取器逐行读取内容,并将新内容写入另一个文件。

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

/**
 * 文件简单的读写
 * @author Android
 *
 */
public class FileStream01 {
public static void main(String[] args) {
    //定义文件 text.txt
    File fir = new  File("text.txt");
  //判断fir是否存在
    if (fir.exists()) {
        System.out.println("exists(文件存在)");
    }
    try {
        
        
        //需要读取的文件  FileInputStearm 文件输入流  (程序中...)
        FileInputStream fie = new FileInputStream(fir);
        //InoutStearmReade 来读取文件
        InputStreamReader isr = new InputStreamReader(fie,"UTF-8");
        /**
         * 当BufferedReader在读取文本文件时,会先尽量从文件中读入字符数据并置入缓冲区,
                 而之后若使用read()方法,会先从缓冲区中进行读取。如果缓冲区数据不足,才会再从文件中读取,
                使用BufferedWriter时,写入的数据并不会先输出到目的地,而是先存储至缓冲区中。如果缓冲区中的数据满了,才会一次对目的地进行写出
         */
        BufferedReader br = new BufferedReader(isr);
        
        String line; //存放当前读取到的
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //循环结束,关闭输入流
        br.close();
        isr.close();
        fie.close();
        
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }



     /**
     * 文件的输出流
     * 文件的写入流
     */
    File newfile = new File("newtext.txt");
    try {
        
        
        
        FileOutputStream fos = new FileOutputStream(newfile);
        OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        
        try {
            bw.write("鹅,鹅,鹅  \n");
            bw.write("曲项向天歌  \n");
            bw.write("白毛虎绿水 \n");
            bw.write("红掌拨清波  \n");
            
            bw.close();
            osw.close();
            fos.close();
            
            
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
         } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值