文件的读写的三种方式java.io

常见的问题:当需要既需要读,还要写时,创建的顺序不能改变
在这里插入图片描述

高效杜文件最新的写法

public class TestBfrdNew {

	public static void main(String[] args) {
		// 高效读取文本文件:BufferedReader对象,默认缓冲区:8192个字符。
		BufferedReader bfrd = null;
		// 是字节流和字符流的桥梁,可以解决文件字符集不匹配,读取中文乱码问题
		InputStreamReader isr = null;
		try {
			// 创建高效读取文件对象
			isr = new InputStreamReader(new FileInputStream("/Users/zhukang/Tempfiles/io/kh88/ddd.txt"), "gbk");
			bfrd = new BufferedReader(isr);
			
			// 一次可以读取一行,如果读取不到,返回null
			String readLineStr = bfrd.readLine();
			while(readLineStr != null){
				System.out.println(readLineStr);
				readLineStr = bfrd.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bfrd.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

高效读写文件:

//写文件
public class TestBfrd {

	public static void main(String[] args) {
		// 高效读取文本文件:BufferedReader对象
		BufferedReader bfrd = null;
		// FileReader fr = null;
		try {
			// 创建高效读取文件对象
			// fr = new FileReader("/Users/zhukang/Tempfiles/io/kh88/ddd.txt");
			bfrd = new BufferedReader(new FileReader("/Users/zhukang/Tempfiles/io/kh88/ddd.txt"));
			
			// 一次可以读取一行,如果读取不到,返回null
			String readLineStr = bfrd.readLine();
			while(readLineStr != null){
				System.out.println(readLineStr);
				readLineStr = bfrd.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bfrd.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
读文件
public class TestBfwt {

	public static void main(String[] args) {
		// 字符流高效写文件:BufferedWriter
		BufferedReader bfrd = null;
		BufferedWriter bfwt = null;

		try {
			// 先写文件(读写同一个文件,不能先定义写对象,默认会覆盖且直接创建一个空白文件)
			bfwt = new BufferedWriter(new FileWriter("/Users/zhukang/Tempfiles/io/kh88/fff.txt"));
			// 高效写入内容,分行写
			bfwt.write("------今天,2021年春运火车票正式开抢。");
			bfwt.newLine();
			bfwt.write("------据预计,2021年春运全国铁路将发送旅客4.07亿人次。");
			bfwt.newLine();
			bfwt.write("------疫情之下的春运,防疫准备充足吗?购票又有了哪些新变化?一起了解一下。");
			bfwt.flush();
			System.out.println("高效写入文件成功!");
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bfwt.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}
// 文件内容互换
public class TestBfrwrp {

	public static void main(String[] args) throws Exception{
		// 高效读写文件,进行内容替换
		BufferedReader bfrd = new BufferedReader(new FileReader("/Users/zhukang/Tempfiles/io/kh88/ggg.txt"));
		BufferedWriter bfwt = new BufferedWriter(new FileWriter("/Users/zhukang/Tempfiles/io/kh88/hhh.txt"));
		
		// 读取文件并解析
		StringBuilder sbd = new StringBuilder();
		String line = bfrd.readLine();
		while (line != null){
			sbd.append(line + "\n");
			line = bfrd.readLine();
		}
		
		// 输出
		System.out.println("替换前:" + sbd.toString());

		// 内容替换
		String contentStr = sbd.toString().replace("{name}", "二哈").replace("{type}", "哈士奇").replace("{master}", "张三");

		System.out.println("替换后:" + sbd.toString());
		
		// 写入文件
		bfwt.write(contentStr);
		bfwt.flush();
		
		bfrd.close();
		bfwt.close();
	}
}

字符流读取

//读取文件
public class TestFr {
    public static void main(String args[]){
        FileReader fr = null;
        StringBuilder str = new StringBuilder();
        try {
            fr = new FileReader(new File("E:\\a.txt"));
            //定义字符缓存数组
            char [] chars = new char[10];

            int readCount = 0;

            while ((readCount = fr.read()) > 0){
                str.append(new String(chars,0,readCount));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
//写入文件
public class TestFw {
	public static void main(String[] args) {
		// 字符流写文本文件用法:FileWriter对象
		FileWriter fw = null;
		String str = "正在学习字符流写文件";
		
		// 输出流对象指向的目标文件,可以不存在,会自动创建一个空文件
		try {
			fw = new FileWriter("/Users/zhukang/Tempfiles/io/kh88/eee.txt");
			
			// 写入内容,支持直接写入字符串
			fw.write(str);
			// fw.write(str, 0, 6);
			// fw.write(str.toCharArray());
			
			// 刷新缓冲区
			fw.flush();
			
			System.out.println("字符流写文件成功");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
	}
}

字节流 fileInputStream 和 fileOutputStream 的读取方式:实现文件复制(写入文件,必须要刷新缓冲区 .flush())


// 文件读取
public class TestFis {
    public static void main(String args[]){
        FileInputStream fis = null;
        File file = new File("E:\\a.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {

            fis = new FileInputStream(file);

            byte [] words = new byte[1024];
            int readCount = 0;
            while ((readCount = fis.read(words)) > 0){
                System.out.println(new String(words,0,readCount));
            }
            System.out.println("文件读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

//文件写入
public class FileFos {

    public static void main(String args[]) throws IOException {

        FileOutputStream fos = null;

        String str = "牛逼plus";
        byte [] bytes = str.getBytes();
        try {
			// 默认是false,当是true时,不会覆盖掉文件内容,自动添加到后面
            fos = new FileOutputStream("E:\\a.txt",true);
            fos.write(bytes);
            // 刷新缓冲区 , 全部输出到目标文件中
            fos.flush();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fos.close();
        }
    }
}

文件复制
 FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("E:\\c.txt");
            fileInputStream = new FileInputStream("E:\\a.txt");
            byte [] b = new byte[10];
            int readCount = 0;
            while((readCount = fileInputStream.read(b)) > 0){
                fileOutputStream.write(b,0,readCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值